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