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 set(object): 396 def __init__(self, iterable): pass 397 def add(self, item): pass 398 def clear(self): pass 399 def copy(self): pass 400 def difference(self, other): pass 401 def difference_update(self, other): pass 402 def discard(self, item): pass 403 def intersection(self, other): pass 404 def intersection_update(self, other): pass 405 def issubset(self, other): pass 406 def issuperset(self, other): pass 407 def pop(self): pass 408 def remove(self, item): pass 409 def symmetric_difference(self, other): pass 410 def symmetric_difference_update(self, other): pass 411 def union(self, other): pass 412 def update(self, other): pass 413 414 # See below for slice. 415 416 class str(basestring): 417 pass 418 419 class type(object): 420 pass 421 422 class tuple(object): 423 424 #"Implementation of tuple." 425 426 def __init__(self, args): pass 427 428 def __getitem__(self, index): 429 430 "Return the item or slice specified by 'index'." 431 432 return _getitem(self, index) 433 434 def __getslice__(self, start, end=None): 435 436 "Return a slice starting from 'start', with the optional 'end'." 437 438 return _tuple(_getslice(self, start, end)) 439 440 def __len__(self): pass 441 def __add__(self, other): pass 442 def __str__(self): pass 443 444 def __bool__(self): 445 446 "Tuples are true if non-empty." 447 448 return self.__len__() != 0 449 450 def __iter__(self): 451 452 "Return an iterator." 453 454 return listiterator(self) 455 456 # Special implementation methods. 457 458 def __get_single_item__(self, index): pass 459 460 class unicode(basestring): 461 pass 462 463 class xrange(object): 464 465 "Implementation of xrange." 466 467 NO_END = object() 468 469 def __init__(self, start_or_end, end=NO_END, step=1): 470 471 "Initialise the xrange with the given 'start_or_end', 'end' and 'step'." 472 473 if end is xrange.NO_END: 474 self.start = 0 475 self.end = start_or_end 476 else: 477 self.start = start_or_end 478 self.end = end 479 480 self.step = step 481 self.current = self.start 482 self.limited = self.end is not xrange.NO_END 483 484 def __iter__(self): 485 486 "Return an iterator, currently self." 487 488 return self 489 490 def next(self): 491 492 "Return the next item or raise a StopIteration exception." 493 494 if self.limited: 495 if self.step < 0 and self.current <= self.end or self.step > 0 and self.current >= self.end: 496 raise StopIteration() 497 498 current = self.current 499 self.current += self.step 500 return current 501 502 class slice(xrange): 503 504 "Implementation of slice." 505 506 def __init__(self, start_or_end=None, end=xrange.NO_END, step=1): 507 508 "Initialise the slice with the given 'start_or_end', 'end' and 'step'." 509 510 xrange.__init__(self, start_or_end, end, step) 511 512 # Exceptions and warnings. 513 514 class BaseException(object): 515 516 "Implementation of BaseException." 517 518 def __init__(self, *args): 519 self._pc = None # remember where the exception occurred 520 self.args = args 521 522 class Exception(BaseException): pass 523 class Warning(object): pass 524 525 class ArithmeticError(Exception): pass 526 class AssertionError(Exception): pass 527 class AttributeError(Exception): pass 528 class DeprecationWarning(Exception): pass 529 class EOFError(Exception): pass 530 class EnvironmentError(Exception): pass 531 class FloatingPointError(Exception): pass 532 class FutureWarning(Warning): pass 533 class GeneratorExit(Exception): pass 534 class ImportError(Exception): pass 535 class ImportWarning(Warning): pass 536 class IndentationError(Exception): pass 537 class IndexError(Exception): pass 538 class IOError(Exception): pass 539 class KeyError(Exception): pass 540 class KeyboardInterrupt(Exception): pass 541 class LookupError(Exception): pass 542 class MemoryError(Exception): pass 543 class NameError(Exception): pass 544 class NotImplementedError(Exception): pass 545 class OSError(Exception): pass 546 class OverflowError(Exception): pass 547 class PendingDeprecationWarning(Warning): pass 548 class ReferenceError(Exception): pass 549 class RuntimeError(Exception): pass 550 class RuntimeWarning(Warning): pass 551 class StandardError(Exception): pass 552 class StopIteration(Exception): "Implementation of StopIteration." 553 class SyntaxError(Exception): pass 554 class SyntaxWarning(Warning): pass 555 class SystemError(Exception): pass 556 class SystemExit(Exception): pass 557 class TabError(Exception): pass 558 class TypeError(Exception): pass 559 class UnboundLocalError(Exception): pass 560 class UnicodeDecodeError(Exception): pass 561 class UnicodeEncodeError(Exception): pass 562 class UnicodeError(Exception): pass 563 class UnicodeTranslateError(Exception): pass 564 class UnicodeWarning(Warning): pass 565 class UserWarning(Warning): pass 566 class ValueError(Exception): pass 567 class ZeroDivisionError(Exception): pass 568 569 # Various types. 570 571 #class ellipsis: pass 572 573 class NoneType: 574 def __bool__(self): 575 "None is always false." 576 return False 577 578 class NotImplementedType: pass 579 580 # General functions. 581 # NOTE: Some of these are actually provided by classes in CPython. 582 # NOTE: We may refuse to support some of these in practice, such as... 583 # NOTE: __import__, super, reload. 584 585 def abs(number): pass 586 def all(iterable): pass 587 def any(iterable): pass 588 def callable(obj): pass 589 def chr(i): pass 590 def classmethod(function): pass 591 def cmp(x, y): pass 592 def compile(source, filename, mode, flags=None, dont_inherit=None): pass 593 def delattr(obj, name): pass 594 def dir(obj=None): pass 595 def divmod(x, y): pass 596 def enumerate(iterable): pass 597 def eval(source, globals=None, locals=None): pass 598 def execfile(filename, globals=None, locals=None): pass 599 def filter(function, sequence): pass 600 601 _getattr_default=object() # a unique placeholder for a missing value 602 def getattr(obj, name, default=_getattr_default): 603 604 "Implementation of getattr (activating the _accessor type)." 605 606 _accessor # avoid isinstance but ensure that this class is included 607 608 try: 609 return _getattr(obj, name) 610 except AttributeError: 611 if default is not _getattr_default: 612 return default 613 else: 614 raise 615 616 def globals(): pass 617 def hasattr(obj, name): pass 618 def hash(obj): pass 619 def help(*args): pass 620 def hex(number): pass 621 def id(obj): pass 622 def input(prompt=None): pass 623 624 def isinstance(obj, cls_or_tuple): 625 626 """ 627 Return whether 'obj' is an instance of 'cls_or_tuple', where the latter is 628 either a class or a tuple of classes. 629 """ 630 631 # NOTE: CPython insists on tuples, but any sequence might be considered 632 # NOTE: acceptable. 633 634 if _isinstance(cls_or_tuple, tuple): 635 for cls in cls_or_tuple: 636 if obj.__class__ is cls or _isinstance(obj, cls): 637 return True 638 return False 639 else: 640 return obj.__class__ is cls_or_tuple or _isinstance(obj, cls_or_tuple) 641 642 def issubclass(obj, cls_or_tuple): pass 643 644 def iter(collection): 645 646 "Implementation of iter without callable plus sentinel support." 647 648 return collection.__iter__() 649 650 def len(obj): 651 652 "Implementation of len." 653 654 return obj.__len__() 655 656 def locals(): pass 657 658 def map(function, *args): pass 659 660 def max(*args): 661 662 "Implementation of max." 663 664 highest = args[0] 665 for arg in args[1:]: 666 if arg > highest: 667 highest = arg 668 return highest 669 670 def min(*args): 671 672 "Implementation of min." 673 674 lowest = args[0] 675 for arg in args[1:]: 676 if arg > lowest: 677 lowest = arg 678 return lowest 679 680 def oct(number): pass 681 def open(name, mode=None, buffering=None): pass 682 def ord(c): pass 683 def pow(x, y, z=None): pass 684 def property(fget=None, fset=None, fdel=None, doc=None): pass 685 686 def range(start_or_end, end=None, step=1): 687 688 "Implementation of range." 689 690 return list(xrange(start_or_end, end, step)) 691 692 def raw_input(prompt=None): pass 693 def reduce(function, sequence, initial=None): pass 694 def reload(module): pass 695 def repr(obj): pass 696 def reversed(sequence): pass 697 def round(number, ndigits=None): pass 698 def setattr(obj, name, value): pass 699 def sorted(iterable, cmp=None, key=None, reverse=False): pass 700 def staticmethod(function): pass 701 def sum(sequence, start=0): pass 702 def super(*args): pass 703 def unichr(i): pass 704 def vars(obj=None): pass 705 def zip(*args): pass 706 707 # Utility functions. 708 709 def _binary_op(self, other, op): 710 711 "Test the type of 'other' and perform 'op'." 712 713 if self.__class__ is other.__class__: 714 return op(self, other) 715 else: 716 return NotImplemented 717 718 def _negate(result): 719 720 "Negate any valid logical value." 721 722 if result is NotImplemented: 723 return result 724 else: 725 return not result 726 727 def _get_absolute_index(index, length): 728 729 """ 730 Return the absolute index for 'index' given a collection having the 731 specified 'length'. 732 """ 733 734 if index < 0: 735 return length + index 736 else: 737 return index 738 739 def _normalise_index(index, length): 740 741 "Normalise 'index' for a collection having the specified 'length'." 742 743 return _min(length, _max(0, _get_absolute_index(index, length))) 744 745 def _max(x, y): 746 747 "Return the maximum of 'x' and 'y'." 748 749 if x >= y: 750 return x 751 else: 752 return y 753 754 def _min(x, y): 755 756 "Return the minimum of 'x' and 'y'." 757 758 if x <= y: 759 return x 760 else: 761 return y 762 763 def _getitem(seq, index): 764 765 "Return the item or slice specified by 'index'." 766 767 if isinstance(index, int): 768 index = _normalise_index(index, len(seq)) 769 return seq.__get_single_item__(index) 770 elif isinstance(index, slice): 771 return seq.__getslice__(index.start, index.end) 772 else: 773 raise TypeError 774 775 def _getslice(seq, start, end=None): 776 777 "Return a slice starting from 'start', with the optional 'end'." 778 779 length = len(seq) 780 781 if start is None: 782 start = 0 783 else: 784 start = _normalise_index(start, length) 785 786 if end is None: 787 end = length 788 else: 789 end = _normalise_index(end, length) 790 791 result = [] 792 while start < end: 793 result.append(seq.__get_single_item__(start)) 794 start += 1 795 return result 796 797 # Special implementation classes. 798 799 class _accessor(str): 800 801 "A string which can be used to access attributes." 802 803 def __new__(self): 804 # Reserve space for an object table index. 805 self._index = None 806 807 # Special implementation functions. 808 809 def _getattr(obj, name): pass 810 def _isinstance(obj, cls): pass 811 def _print(dest, *args): pass 812 def _printnl(dest, *args): pass 813 def _tuple(l): pass 814 815 # Reference some names to ensure their existence. This should be everything 816 # mentioned in a get_builtin or load_builtin call. Instances from this module 817 # should be predefined constants. 818 819 function 820 AttributeError 821 #IndexError 822 NoneType 823 NotImplementedType 824 #StopIteration 825 TypeError 826 827 bool 828 #ellipsis 829 #list 830 tuple 831 type 832 #xrange 833 834 # vim: tabstop=4 expandtab shiftwidth=4