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