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