1 #!/usr/bin/env python 2 3 """ 4 Simple built-in classes and functions. 5 6 Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 21 -------- 22 23 Objects which provide code that shall always be compiled should provide 24 docstrings. Objects without code should be provided by native library code. 25 26 Classes without docstrings do not have instantiators generated for them. 27 28 Methods defined in classes are generated if they have docstrings, regardless of 29 whether their classes have docstrings. 30 """ 31 32 import native 33 34 class object: 35 def __init__(self): 36 "No-operation." 37 pass 38 def __bool__(self): 39 "Objects are true by default." 40 return True 41 42 class basestring(object): 43 def __init__(self, x=None): pass 44 def __contains__(self, value): pass 45 46 def __getitem__(self, index): 47 # Note usage. 48 IndexError 49 50 def __getslice__(self, start, end=None): pass 51 52 def __iadd__(self, other): 53 "Return a new string for the operation." 54 return _binary_op(self, other, native._str_add) 55 56 __add__ = __radd__ = __iadd__ 57 58 def __mul__(self, other): pass 59 def __rmul__(self, other): pass 60 def __mod__(self, other): pass 61 def __rmod__(self, other): pass 62 63 def __lt__(self, other): 64 "Return a new boolean for the comparison." 65 return _binary_op(self, other, native._str_lt) 66 67 def __gt__(self, other): 68 "Return a new boolean for the comparison." 69 return _binary_op(self, other, native._str_gt) 70 71 def __le__(self, other): 72 "Return a new boolean for the comparison." 73 return _negate(self.__gt__(other)) 74 75 def __ge__(self, other): 76 "Return a new boolean for the comparison." 77 return _negate(self.__lt__(other)) 78 79 def __eq__(self, other): 80 "Return a new boolean for the comparison." 81 return _binary_op(self, other, native._str_eq) 82 83 def __ne__(self, other): 84 "Return a new boolean for the comparison." 85 return _negate(self.__eq__(other)) 86 87 def __len__(self): pass 88 def __str__(self): pass 89 90 def __bool__(self): 91 return _negate(native._str_eq(self, "")) 92 93 def join(self, l): pass 94 def split(self, s): pass 95 def startswith(self, s): pass 96 def endswith(self, s): pass 97 98 class bool(object): 99 def __bool__(self): 100 "Identity operation." 101 return self 102 def __str__(self): pass 103 104 class buffer(object): 105 def __init__(self, size): pass 106 def append(self, s): pass 107 def __str__(self): pass 108 109 class complex(object): 110 def __init__(self, real, imag=None): pass 111 112 class dict(object): 113 def __init__(self, *args): pass 114 def __setitem__(self, key, value): pass 115 116 def __getitem__(self, key): 117 # Note usage. 118 KeyError 119 120 class file(object): 121 def read(self, n=None): pass 122 def write(self, s): pass 123 def close(self): pass 124 125 class float(object): 126 def __init__(self, number_or_string=None): pass 127 def __iadd__(self, other): pass 128 def __isub__(self, other): pass 129 def __add__(self, other): pass 130 def __radd__(self, other): pass 131 def __sub__(self, other): pass 132 def __rsub__(self, other): pass 133 def __mul__(self, other): pass 134 def __rmul__(self, other): pass 135 def __div__(self, other): pass 136 def __rdiv__(self, other): pass 137 def __floordiv__(self, other): pass 138 def __rfloordiv__(self, other): pass 139 def __mod__(self, other): pass 140 def __rmod__(self, other): pass 141 def __pow__(self, other): pass 142 def __rpow__(self, other): pass 143 def __lt__(self, other): pass 144 def __gt__(self, other): pass 145 def __le__(self, other): pass 146 def __ge__(self, other): pass 147 def __eq__(self, other): pass 148 def __ne__(self, other): pass 149 def __neg__(self): pass 150 def __pos__(self): pass 151 def __str__(self): pass 152 def __bool__(self): pass 153 154 class frozenset(object): 155 def __init__(self, iterable): pass 156 157 class function(object): 158 pass 159 160 class int(object): 161 def __init__(self, number_or_string=None): pass 162 163 def __iadd__(self, other): 164 "Return a new int for the operation." 165 return _binary_op(self, other, native._int_add) 166 167 def __isub__(self, other): 168 "Return a new int for the operation." 169 return _binary_op(self, other, native._int_sub) 170 171 def __imul__(self, other): 172 "Return a new int for the operation." 173 return _binary_op(self, other, native._int_mul) 174 175 def __idiv__(self, other): 176 "Return a new int for the operation." 177 return _binary_op(self, other, native._int_div) 178 179 def __imod__(self, other): 180 "Return a new int for the operation." 181 return _binary_op(self, other, native._int_mod) 182 183 def __ipow__(self, other): 184 "Return a new int for the operation." 185 return _binary_op(self, other, native._int_pow) 186 187 def __iand__(self, other): 188 "Return a new int for the operation." 189 return _binary_op(self, other, native._int_and) 190 191 def __ior__(self, other): 192 "Return a new int for the operation." 193 return _binary_op(self, other, native._int_or) 194 195 def __ixor__(self, other): 196 "Return a new int for the operation." 197 return _binary_op(self, other, native._int_xor) 198 199 __add__ = __radd__ = __iadd__ 200 __sub__ = __isub__ 201 202 def __rsub__(self, other): 203 "Return a new int for the operation." 204 return _binary_op(self, other, native._int_rsub) 205 206 __mul__ = __rmul__ = __imul__ 207 __div__ = __idiv__ 208 209 def __rdiv__(self, other): 210 "Return a new int for the operation." 211 return _binary_op(self, other, native._int_rdiv) 212 213 def __floordiv__(self, other): pass 214 def __rfloordiv__(self, other): pass 215 216 __mod__ = __imod__ 217 218 def __rmod__(self, other): 219 "Return a new int for the operation." 220 return _binary_op(self, other, native._int_rmod) 221 222 __pow__ = __ipow__ 223 224 def __rpow__(self, other): 225 "Return a new int for the operation." 226 return _binary_op(self, other, native._int_rpow) 227 228 __and__ = __rand__ = __iand__ 229 __or__ = __ror__ = __ior__ 230 __xor__ = __rxor__ = __ixor__ 231 232 def __lt__(self, other): 233 "Return a new boolean for the comparison." 234 return _binary_op(self, other, native._int_lt) 235 236 def __gt__(self, other): 237 "Return a new boolean for the comparison." 238 return _binary_op(self, other, native._int_gt) 239 240 def __le__(self, other): 241 "Return a new boolean for the comparison." 242 return _negate(self.__gt__(other)) 243 244 def __ge__(self, other): 245 "Return a new boolean for the comparison." 246 return _negate(self.__lt__(other)) 247 248 def __eq__(self, other): 249 "Return a new boolean for the comparison." 250 return _binary_op(self, other, native._int_eq) 251 252 def __ne__(self, other): 253 "Return a new boolean for the comparison." 254 return _negate(self.__eq__(other)) 255 256 def __neg__(self): pass 257 def __pos__(self): pass 258 def __str__(self): pass 259 def __lshift__(self): pass 260 def __rlshift__(self): pass 261 def __rshift__(self): pass 262 def __rrshift__(self): pass 263 264 def __bool__(self): 265 "Return whether this int is non-zero." 266 return _negate(native._int_eq(self, 0)) 267 268 class list(object): 269 270 "Implementation of list." 271 272 def __init__(self, args=None): 273 274 "Initialise the list." 275 276 self.__new__() 277 278 if args is not None: 279 self.extend(args) 280 281 def __new__(self): 282 # Reserve space for a fragment reference. 283 self._elements = None 284 285 def __getitem__(self, index): 286 287 "Return the item or slice specified by 'index'." 288 289 return _getitem(self, index) 290 291 def __contains__(self, value): pass 292 def __setitem__(self, index, value): pass 293 294 def __getslice__(self, start, end=None): 295 296 "Return a slice starting from 'start', with the optional 'end'." 297 298 return _getslice(self, start, end) 299 300 def __setslice__(self, start, end, slice): pass 301 def append(self, value): pass 302 303 def extend(self, iterable): 304 305 "Extend the list with the contents of 'iterable'." 306 307 for i in iterable: 308 self.append(i) 309 310 def pop(self): pass 311 def sort(self, cmp=None, key=None, reverse=0): pass 312 def __len__(self): pass 313 def __add__(self, other): pass 314 def __iadd__(self, other): pass 315 def __str__(self): pass 316 317 def __bool__(self): 318 319 "Lists are true if non-empty." 320 321 return self.__len__() != 0 322 323 def __iter__(self): 324 325 "Return an iterator." 326 327 return listiterator(self) 328 329 # Special implementation methods. 330 331 def __get_single_item__(self, index): pass 332 333 class listiterator(object): 334 335 "Implementation of listiterator." 336 337 def __init__(self, l): 338 339 "Initialise with the given list 'l'." 340 341 self.l = l 342 self.i = 0 343 344 def next(self): 345 346 "Return the next item." 347 348 try: 349 value = self.l[self.i] 350 self.i += 1 351 return value 352 except IndexError: 353 raise StopIteration() 354 355 class long(object): 356 def __init__(self, number_or_string=None): pass 357 def __iadd__(self, other): pass 358 def __isub__(self, other): pass 359 def __add__(self, other): pass 360 def __radd__(self, other): pass 361 def __sub__(self, other): pass 362 def __rsub__(self, other): pass 363 def __mul__(self, other): pass 364 def __rmul__(self, other): pass 365 def __div__(self, other): pass 366 def __rdiv__(self, other): pass 367 def __floordiv__(self, other): pass 368 def __rfloordiv__(self, other): pass 369 def __and__(self, other): pass 370 def __rand__(self, other): pass 371 def __or__(self, other): pass 372 def __ror__(self, other): pass 373 def __xor__(self, other): pass 374 def __rxor__(self, other): pass 375 def __lt__(self, other): pass 376 def __gt__(self, other): pass 377 def __le__(self, other): pass 378 def __ge__(self, other): pass 379 def __eq__(self, other): pass 380 def __ne__(self, other): pass 381 def __neg__(self): pass 382 def __pos__(self): pass 383 def __str__(self): pass 384 def __bool__(self): pass 385 386 class set(object): 387 def __init__(self, iterable): pass 388 389 # See below for slice. 390 391 class str(basestring): 392 pass 393 394 class type(object): 395 pass 396 397 class tuple(object): 398 399 #"Implementation of tuple." 400 401 def __init__(self, args): pass 402 403 def __getitem__(self, index): 404 405 "Return the item or slice specified by 'index'." 406 407 return _getitem(self, index) 408 409 def __getslice__(self, start, end=None): 410 411 "Return a slice starting from 'start', with the optional 'end'." 412 413 return _tuple(_getslice(self, start, end)) 414 415 def __len__(self): pass 416 def __add__(self, other): pass 417 def __str__(self): pass 418 419 def __bool__(self): 420 421 "Tuples are true if non-empty." 422 423 return self.__len__() != 0 424 425 def __iter__(self): 426 427 "Return an iterator." 428 429 return listiterator(self) 430 431 # Special implementation methods. 432 433 def __get_single_item__(self, index): pass 434 435 class unicode(basestring): 436 pass 437 438 class xrange(object): 439 440 "Implementation of xrange." 441 442 NO_END = object() 443 444 def __init__(self, start_or_end, end=NO_END, step=1): 445 446 "Initialise the xrange with the given 'start_or_end', 'end' and 'step'." 447 448 if end is xrange.NO_END: 449 self.start = 0 450 self.end = start_or_end 451 else: 452 self.start = start_or_end 453 self.end = end 454 455 self.step = step 456 self.current = self.start 457 self.limited = self.end is not xrange.NO_END 458 459 def __iter__(self): 460 461 "Return an iterator, currently self." 462 463 return self 464 465 def next(self): 466 467 "Return the next item or raise a StopIteration exception." 468 469 if self.limited: 470 if self.step < 0 and self.current <= self.end or self.step > 0 and self.current >= self.end: 471 raise StopIteration() 472 473 current = self.current 474 self.current += self.step 475 return current 476 477 class slice(xrange): 478 479 "Implementation of slice." 480 481 def __init__(self, start_or_end=None, end=xrange.NO_END, step=1): 482 483 "Initialise the slice with the given 'start_or_end', 'end' and 'step'." 484 485 xrange.__init__(self, start_or_end, end, step) 486 487 # Exceptions and warnings. 488 489 class BaseException(object): 490 491 "Implementation of BaseException." 492 493 def __init__(self, *args): 494 self._pc = None # remember where the exception occurred 495 self.args = args 496 497 class Exception(BaseException): pass 498 class Warning(object): pass 499 500 class ArithmeticError(Exception): pass 501 class AssertionError(Exception): pass 502 class AttributeError(Exception): pass 503 class DeprecationWarning(Exception): pass 504 class EOFError(Exception): pass 505 class EnvironmentError(Exception): pass 506 class FloatingPointError(Exception): pass 507 class FutureWarning(Warning): pass 508 class GeneratorExit(Exception): pass 509 class ImportError(Exception): pass 510 class ImportWarning(Warning): pass 511 class IndentationError(Exception): pass 512 class IndexError(Exception): pass 513 class IOError(Exception): pass 514 class KeyError(Exception): pass 515 class KeyboardInterrupt(Exception): pass 516 class LookupError(Exception): pass 517 class MemoryError(Exception): pass 518 class NameError(Exception): pass 519 class NotImplementedError(Exception): pass 520 class OSError(Exception): pass 521 class OverflowError(Exception): pass 522 class PendingDeprecationWarning(Warning): pass 523 class ReferenceError(Exception): pass 524 class RuntimeError(Exception): pass 525 class RuntimeWarning(Warning): pass 526 class StandardError(Exception): pass 527 class StopIteration(Exception): "Implementation of StopIteration." 528 class SyntaxError(Exception): pass 529 class SyntaxWarning(Warning): pass 530 class SystemError(Exception): pass 531 class SystemExit(Exception): pass 532 class TabError(Exception): pass 533 class TypeError(Exception): pass 534 class UnboundLocalError(Exception): pass 535 class UnicodeDecodeError(Exception): pass 536 class UnicodeEncodeError(Exception): pass 537 class UnicodeError(Exception): pass 538 class UnicodeTranslateError(Exception): pass 539 class UnicodeWarning(Warning): pass 540 class UserWarning(Warning): pass 541 class ValueError(Exception): pass 542 class ZeroDivisionError(Exception): pass 543 544 # Various types. 545 546 #class ellipsis: pass 547 class NoneType: pass 548 class NotImplementedType: pass 549 550 # General functions. 551 # NOTE: Some of these are actually provided by classes in CPython. 552 # NOTE: We may refuse to support some of these in practice, such as... 553 # NOTE: __import__, super, reload. 554 555 def abs(number): pass 556 def all(iterable): pass 557 def any(iterable): pass 558 def callable(obj): pass 559 def chr(i): pass 560 def classmethod(function): pass 561 def cmp(x, y): pass 562 def compile(source, filename, mode, flags=None, dont_inherit=None): pass 563 def delattr(obj, name): pass 564 def dir(obj=None): pass 565 def divmod(x, y): pass 566 def enumerate(iterable): pass 567 def eval(source, globals=None, locals=None): pass 568 def execfile(filename, globals=None, locals=None): pass 569 def filter(function, sequence): pass 570 571 _getattr_default=object() # a placeholder for a missing value 572 def getattr(obj, name, default=_getattr_default): 573 574 "Implementation of getattr." 575 576 _accessor # avoid isinstance but ensure that this class is included 577 578 try: 579 return _getattr(obj, name) 580 except AttributeError: 581 if default is not _getattr_default: 582 return default 583 else: 584 raise 585 586 def globals(): pass 587 def hasattr(obj, name): pass 588 def hash(obj): pass 589 def help(*args): pass 590 def hex(number): pass 591 def id(obj): pass 592 def input(prompt=None): pass 593 594 def isinstance(obj, cls_or_tuple): 595 596 """ 597 Return whether 'obj' is an instance of 'cls_or_tuple', where the latter is 598 either a class or a tuple of classes. 599 """ 600 601 # NOTE: CPython insists on tuples, but any sequence might be considered 602 # NOTE: acceptable. 603 604 if _isinstance(cls_or_tuple, tuple): 605 for cls in cls_or_tuple: 606 if obj.__class__ is cls or _isinstance(obj, cls): 607 return True 608 return False 609 else: 610 return obj.__class__ is cls_or_tuple or _isinstance(obj, cls_or_tuple) 611 612 def issubclass(obj, cls_or_tuple): pass 613 614 def iter(collection): 615 616 "Implementation of iter without callable plus sentinel support." 617 618 return collection.__iter__() 619 620 def len(obj): 621 622 "Implementation of len." 623 624 return obj.__len__() 625 626 def locals(): pass 627 628 def map(function, *args): pass 629 630 def max(*args): 631 632 "Implementation of max." 633 634 highest = args[0] 635 for arg in args[1:]: 636 if arg > highest: 637 highest = arg 638 return highest 639 640 def min(*args): 641 642 "Implementation of min." 643 644 lowest = args[0] 645 for arg in args[1:]: 646 if arg > lowest: 647 lowest = arg 648 return lowest 649 650 def oct(number): pass 651 def open(name, mode=None, buffering=None): pass 652 def ord(c): pass 653 def pow(x, y, z=None): pass 654 def property(fget=None, fset=None, fdel=None, doc=None): pass 655 656 def range(start_or_end, end=None, step=1): 657 658 "Implementation of range." 659 660 return list(xrange(start_or_end, end, step)) 661 662 def raw_input(prompt=None): pass 663 def reduce(function, sequence, initial=None): pass 664 def reload(module): pass 665 def repr(obj): pass 666 def reversed(sequence): pass 667 def round(number, ndigits=None): pass 668 def setattr(obj, name, value): pass 669 def sorted(iterable, cmp=None, key=None, reverse=False): pass 670 def staticmethod(function): pass 671 def sum(sequence, start=0): pass 672 def super(*args): pass 673 def unichr(i): pass 674 def vars(obj=None): pass 675 def zip(*args): pass 676 677 # Utility functions. 678 679 def _binary_op(self, other, op): 680 681 "Test the type of 'other' and perform 'op'." 682 683 if self.__class__ is other.__class__: 684 return op(self, other) 685 else: 686 return NotImplemented 687 688 def _negate(result): 689 690 "Negate any valid logical value." 691 692 if result is NotImplemented: 693 return result 694 else: 695 return not result 696 697 def _get_absolute_index(index, length): 698 699 """ 700 Return the absolute index for 'index' given a collection having the 701 specified 'length'. 702 """ 703 704 if index < 0: 705 return length + index 706 else: 707 return index 708 709 def _normalise_index(index, length): 710 711 "Normalise 'index' for a collection having the specified 'length'." 712 713 return _min(length, _max(0, _get_absolute_index(index, length))) 714 715 def _max(x, y): 716 717 "Return the maximum of 'x' and 'y'." 718 719 if x >= y: 720 return x 721 else: 722 return y 723 724 def _min(x, y): 725 726 "Return the minimum of 'x' and 'y'." 727 728 if x <= y: 729 return x 730 else: 731 return y 732 733 def _getitem(seq, index): 734 735 "Return the item or slice specified by 'index'." 736 737 if isinstance(index, int): 738 index = _normalise_index(index, len(seq)) 739 return seq.__get_single_item__(index) 740 elif isinstance(index, slice): 741 return seq.__getslice__(index.start, index.end) 742 else: 743 raise TypeError 744 745 def _getslice(seq, start, end=None): 746 747 "Return a slice starting from 'start', with the optional 'end'." 748 749 length = len(seq) 750 751 if start is None: 752 start = 0 753 else: 754 start = _normalise_index(start, length) 755 756 if end is None: 757 end = length 758 else: 759 end = _normalise_index(end, length) 760 761 result = [] 762 while start < end: 763 result.append(seq.__get_single_item__(start)) 764 start += 1 765 return result 766 767 # Special implementation classes. 768 769 class _accessor(str): 770 771 "A string which can be used to access attributes." 772 773 def __new__(self): 774 # Reserve space for an object table index. 775 self._index = None 776 777 # Special implementation functions. 778 779 def _getattr(obj, name): pass 780 def _isinstance(obj, cls): pass 781 def _print(dest, *args): pass 782 def _printnl(dest, *args): pass 783 def _tuple(l): pass 784 785 # Reference some names to ensure their existence. This should be everything 786 # mentioned in a get_builtin or load_builtin call. Instances from this module 787 # should be predefined constants. 788 789 function 790 AttributeError 791 #IndexError 792 #NoneType 793 NotImplementedType 794 #StopIteration 795 TypeError 796 797 bool 798 #ellipsis 799 #list 800 tuple 801 type 802 #xrange 803 804 # vim: tabstop=4 expandtab shiftwidth=4