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