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