# HG changeset patch # User Paul Boddie # Date 1206399198 -3600 # Node ID e704da427db4762876a831288f9e99ee01ac4d5f # Parent 1725bf186f7381289266890739104897e7482ae0 Removed the builtins module definitions from the code, adding a separate module adapted from that included with the "simplify" project which is processed in the test program. Introduced instantiator functions for classes, replacing the use of __init__ methods where classes are known to be invoked. diff -r 1725bf186f73 -r e704da427db4 lib/builtins.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lib/builtins.py Mon Mar 24 23:53:18 2008 +0100 @@ -0,0 +1,234 @@ +#!/usr/bin/env python + +""" +Simple built-in classes and functions. + +Copyright (C) 2005, 2006, 2007, 2008 Paul Boddie + +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +details. + +You should have received a copy of the GNU General Public License along with +this program. If not, see . +""" + +class object: + def __init__(self): pass + def __bool__(self): pass + def __iadd__(self, other): pass + +class bool: + def __bool__(self): pass + def __str__(self): pass + +class buffer: + def __init__(self, size): pass + def append(self, s): pass + def __str__(self): pass + +class dict: + def __init__(self, *args): pass + def __setitem__(self, key, value): pass + def __getitem__(self, key): pass + +class file: + def write(self, s): pass + +class float: + def __init__(self, number_or_string=None): pass + def __iadd__(self, other): pass + def __isub__(self, other): pass + def __add__(self, other): pass + def __radd__(self, other): pass + def __sub__(self, other): pass + def __rsub__(self, other): pass + def __mul__(self, other): pass + def __rmul__(self, other): pass + def __div__(self, other): pass + def __rdiv__(self, other): pass + def __floordiv__(self, other): pass + def __rfloordiv__(self, other): pass + def __mod__(self, other): pass + def __pow__(self, other): pass + def __rpow__(self, other): pass + def __lt__(self, other): pass + def __gt__(self, other): pass + def __le__(self, other): pass + def __ge__(self, other): pass + def __eq__(self, other): pass + def __ne__(self, other): pass + def __neg__(self): pass + def __pos__(self): pass + def __str__(self): pass + def __bool__(self): pass + +class int: + def __init__(self, number_or_string=None): pass + def __iadd__(self, other): pass + def __isub__(self, other): pass + def __add__(self, other): pass + def __radd__(self, other): pass + def __sub__(self, other): pass + def __rsub__(self, other): pass + def __mul__(self, other): pass + def __rmul__(self, other): pass + def __div__(self, other): pass + def __rdiv__(self, other): pass + def __floordiv__(self, other): pass + def __rfloordiv__(self, other): pass + def __mod__(self, other): pass + def __pow__(self, other): pass + def __and__(self, other): pass + def __rand__(self, other): pass + def __or__(self, other): pass + def __ror__(self, other): pass + def __xor__(self, other): pass + def __rxor__(self, other): pass + def __lt__(self, other): pass + def __gt__(self, other): pass + def __le__(self, other): pass + def __ge__(self, other): pass + def __eq__(self, other): pass + def __ne__(self, other): pass + def __neg__(self): pass + def __pos__(self): pass + def __str__(self): pass + def __bool__(self): pass + +class list: + def __init__(self, args=()): pass + def __getitem__(self, index): pass + def __setitem__(self, index, value): pass + def __getslice__(self, start, end=None): pass + def __setslice__(self, start, end, slice): pass + def append(self, value): pass + def __len__(self): pass + def __add__(self, other): pass + def __iadd__(self, other): pass + def __str__(self): pass + def __iter__(self): pass + def __bool__(self): pass + +class long: + def __init__(self, number_or_string=None): pass + def __iadd__(self, other): pass + def __isub__(self, other): pass + def __add__(self, other): pass + def __radd__(self, other): pass + def __sub__(self, other): pass + def __rsub__(self, other): pass + def __mul__(self, other): pass + def __rmul__(self, other): pass + def __div__(self, other): pass + def __rdiv__(self, other): pass + def __floordiv__(self, other): pass + def __rfloordiv__(self, other): pass + def __and__(self, other): pass + def __rand__(self, other): pass + def __or__(self, other): pass + def __ror__(self, other): pass + def __xor__(self, other): pass + def __rxor__(self, other): pass + def __lt__(self, other): pass + def __gt__(self, other): pass + def __le__(self, other): pass + def __ge__(self, other): pass + def __eq__(self, other): pass + def __ne__(self, other): pass + def __neg__(self): pass + def __pos__(self): pass + def __str__(self): pass + def __bool__(self): pass + +class none: + def __bool__(self): pass + def __str__(self): pass + +NoneType = none + +class slice: + def __init__(self, start_or_end, end=None, step=None): pass + +class str: + def __init__(self, x=None): pass + def __getitem__(self, index): pass + def __getslice__(self, start, end=None): pass + def __iadd__(self, other): pass + def __add__(self, other): pass + def __radd__(self, other): pass + def __mul__(self, other): pass + def __radd__(self, other): pass + def __mod__(self, other): pass + def __lt__(self, other): pass + def __gt__(self, other): pass + def __le__(self, other): pass + def __ge__(self, other): pass + def __eq__(self, other): pass + def __ne__(self, other): pass + def __len__(self): pass + def __str__(self): pass + def __bool__(self): pass + def join(self, l): pass + +class tuple: + def __init__(self, args): pass + def __getitem__(self, index): pass + def __getslice__(self, start, end=None): pass + def __len__(self): pass + def __add__(self, other): pass + def __str__(self): pass + def __iter__(self): pass + def __bool__(self): pass + +class xrange: + def __init__(self, start_or_end, end=None, step=1): pass + def __iter__(self): pass + def next(self): pass + +class Exception: + def __init__(self, *args): pass + +class AssertionError(Exception): + pass + +class AttributeError(Exception): + pass + +class IndexError(Exception): + pass + +class StopIteration(Exception): + pass + +class TypeError(Exception): + pass + +class NotImplementedType: + pass + +# General functions. + +def isinstance(obj, cls): pass +def issubclass(cls1, cls2): pass +def len(x): pass +def max(*l): pass +def range(start_or_end, end=None, step=None): pass + +# Special values. + +True = bool() +False = bool() +None = none() +stdin = file() +stdout = file() +stderr = file() +NotImplemented = NotImplementedType() + +# vim: tabstop=4 expandtab shiftwidth=4 diff -r 1725bf186f73 -r e704da427db4 micropython/__init__.py --- a/micropython/__init__.py Sat Mar 22 22:31:54 2008 +0100 +++ b/micropython/__init__.py Mon Mar 24 23:53:18 2008 +0100 @@ -62,7 +62,7 @@ self.path = path or [os.getcwd()] self.verbose = verbose - self.modules = {"__builtins__" : micropython.inspect.builtins} + self.modules = {} self.loading = set() # Remember the tables once generated. @@ -115,7 +115,7 @@ # Position the module in the image and make a translation. module.location = pos - trans = micropython.ast.Translation(module, objtable, paramtable) + trans = micropython.ast.Translation(module, objtable, paramtable, self.modules.get("__builtins__")) # Add header details. @@ -222,12 +222,11 @@ t.add(obj.full_name(), obj.parameters()) # Classes are callable, too. - # Copy details of the appropriate __init__ method to make an - # entry for the class. + # Take details of the appropriate __init__ method to make an + # entry for an instantiation function for the class. elif isinstance(obj, micropython.inspect.Class): - init_method = objtable.table[obj.full_name()]["__init__"].value - t.add(obj.full_name(), init_method.parameters()) + t.add(obj.full_name(), obj.get_instantiator().parameters()) return self.paramtable diff -r 1725bf186f73 -r e704da427db4 micropython/ast.py --- a/micropython/ast.py Sat Mar 22 22:31:54 2008 +0100 +++ b/micropython/ast.py Mon Mar 24 23:53:18 2008 +0100 @@ -48,7 +48,7 @@ "A translated module." - def __init__(self, module, objtable, paramtable): + def __init__(self, module, objtable, paramtable, builtins=None): """ Initialise the translation with an inspected 'module' and an attribute @@ -60,6 +60,10 @@ self.module = module self.objtable = objtable self.paramtable = paramtable + self.builtins = builtins + + # The current unit being translated. + self.unit = None # Wiring within the code. @@ -410,21 +414,23 @@ elif isinstance(unit, micropython.inspect.Module): self.new_op(AttrInstruction(unit.module_attributes()[name])) else: - raise TranslateError(self.module.full_name(), node, "Program unit %r has no local %r" % (unit, name)) + raise TranslateError(self.module.full_name(), node, "Program unit %r has no local %r." % (unit, name)) elif scope == "global": globals = self.module.module_attributes() if globals.has_key(name): self.new_op(AttrInstruction(globals[name])) else: - raise TranslateError(self.module.full_name(), node, "Module %r has no attribute %r" % (self.module, name)) + raise TranslateError(self.module.full_name(), node, "Module %r has no attribute %r." % (self.module, name)) else: - self.new_op(AttrInstruction(self._get_builtin(name))) + self.new_op(AttrInstruction(self._get_builtin(name, node))) - def _get_builtin(self, name): - builtins = micropython.inspect.builtins.module_attributes() - return builtins[name] + def _get_builtin(self, name, node): + if self.builtins is not None: + return self.builtins[name] + else: + raise TranslateError(self.module.full_name(), node, "No __builtins__ module is available for name %r." % name) # Optimisation methods. @@ -460,11 +466,9 @@ context = last.attr.parent # Handle calls to classes. - # NOTE: That the actual invocation target will be a __new__ method - # NOTE: which calls the __init__ method, returning the new instance. if isinstance(target, micropython.inspect.Class): - target = self.objtable.table[target.full_name()]["__init__"].value + target = target.get_instantiator() context = micropython.inspect.Instance() # A special context is chosen to avoid generating unnecessary diff -r 1725bf186f73 -r e704da427db4 micropython/inspect.py --- a/micropython/inspect.py Sat Mar 22 22:31:54 2008 +0100 +++ b/micropython/inspect.py Mon Mar 24 23:53:18 2008 +0100 @@ -316,6 +316,7 @@ self.location = None self.code_location = None + self.instantiator = None def __repr__(self): if self.location is not None: @@ -330,6 +331,15 @@ self.finalise_class_attributes() self.finalise_instance_attributes() + def get_instantiator(self): + + "Return a function which can be used to instantiate the class." + + if self.instantiator is None: + init_method = self.all_class_attributes()["__init__"].value + self.instantiator = init_method.function_from_method() + return self.instantiator + # Class-specific methods. def add_base(self, base): @@ -665,6 +675,12 @@ for i, attr in enumerate(self.locals().values()): attr.position = i + j + def function_from_method(self): + + "Make a function from a method." + + return Function(self.name, self.parent, self.argnames[1:], self.has_star, self.has_dstar, self.global_namespace, self.node) + class UnresolvedName(NamespaceDict): "A module, class or function which was mentioned but could not be imported." @@ -767,6 +783,7 @@ self.visitor = self self.importer = importer + self.builtins = self.importer.modules.get("__builtins__") self.loaded = 0 # Current expression state. @@ -926,7 +943,7 @@ # NOTE: Potentially dubious measure to permit __init__ availability. # If no bases exist, adopt the 'object' class. - if not node.bases: + if not node.bases and not (self.name == "__builtins__" and node.name == "object") : expr = self.dispatch(compiler.ast.Name("object")) cls.add_base(expr.value) @@ -1054,7 +1071,10 @@ return value.namespace.get(node.attrname) elif isinstance(value, UnresolvedName): return UnresolvedName(node.attrname, value.full_name(), self) - return builtins.get(node.attrname) + if self.builtins is not None: + return self.builtins.get(node.attrname) + else: + return UnresolvedName(node.attrname, value.full_name(), self) def visitGlobal(self, node): if self.namespaces: @@ -1121,8 +1141,8 @@ return self.namespaces[-1][name] elif self.has_key(name): return self[name] - elif builtins.has_key(name): - return builtins[name] + elif self.builtins is not None and self.builtins.has_key(name): + return self.builtins[name] else: return None @@ -1191,71 +1211,4 @@ pass -# Built-in types initialisation. - -class Builtins(Module): - - "The special built-in types module." - - def __init__(self): - Module.__init__(self, "__builtins__") - self.loaded = 1 - self.module = None - - for key in ['ArithmeticError', 'AssertionError', 'AttributeError', - 'BaseException', 'DeprecationWarning', 'EOFError', 'Ellipsis', - 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', - 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', - 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', - 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', - 'None', 'NotImplemented', 'NotImplementedError', 'OSError', - 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', - 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', - 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', - 'TabError', 'True', 'TypeError', 'UnboundLocalError', - 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', - 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', - 'ValueError', 'Warning', 'ZeroDivisionError', - 'basestring', 'bool', 'buffer', 'complex', 'dict', 'file', 'float', - 'frozenset', 'int', # 'list', - 'long', 'object', 'set', 'slice', 'str', - 'tuple', 'type', 'unicode', 'xrange']: - - cls = Class(key, self, self) - cls.set("__init__", Function("__init__", cls, [], 0, 0, cls)) - self.store(key, cls) - - # NOTE: Temporary measure - provide detailed built-ins. - - cls = Class("list", self, self) - cls.set("__init__", Function("__init__", cls, [], 0, 0, cls)) - cls.set("__iter__", Function("__iter__", cls, [], 0, 0, cls)) - self.store("list", cls) - - cls = Class("listiterator", self, self) - cls.set("__init__", Function("__init__", cls, [], 0, 0, cls)) - cls.set("next", Function("next", cls, [], 0, 0, cls)) - self.store("listiterator", cls) - - # NOTE: Incomplete: some functions have more than one parameter. - - for key in ['__import__', 'abs', 'all', 'any', 'callable', 'chr', - 'classmethod', 'cmp', 'compile', 'delattr', 'dir', 'divmod', - 'enumerate', 'eval', 'execfile', 'filter', 'getattr', 'globals', - 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'isinstance', - 'issubclass', 'iter', 'len', 'locals', 'map', 'max', 'min', 'oct', - 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce', - 'reload', 'repr', 'reversed', 'round', 'setattr', 'sorted', - 'staticmethod', 'sum', 'super', 'unichr', 'vars', 'zip']: - self[key] = Function(key, self, ['arg'], 0, 0, self) - - def store(self, name, obj): - self.set(name, obj) - self.all_objects.add(obj) - - def vacuum(self): - pass - -builtins = Builtins() - # vim: tabstop=4 expandtab shiftwidth=4 diff -r 1725bf186f73 -r e704da427db4 test.py --- a/test.py Sat Mar 22 22:31:54 2008 +0100 +++ b/test.py Mon Mar 24 23:53:18 2008 +0100 @@ -13,6 +13,7 @@ i = micropython.Importer(sys.path, "-v" in sys.argv) try: + builtins = i.load_from_file("lib/builtins.py", "__builtins__") if len(sys.argv) < 2: m = i.load("micropython") #m = i.load_from_file("micropython/__init__.py")