1. Pypy
  2. Untitled project
  3. pypy

Commits

Jean-Philippe St. Pierre  committed 9391336

More work on PyPy-AVM

  • Participants
  • Parent commits 1bed6ba
  • Branches avm

Comments (0)

Files changed (23)

File pypy/translator/avm1/.ropeproject/config.py

  • Ignore whitespace
-# The default ``config.py``
-
-
-def set_prefs(prefs):
-    """This function is called before opening the project"""
-
-    # Specify which files and folders to ignore in the project.
-    # Changes to ignored resources are not added to the history and
-    # VCSs.  Also they are not returned in `Project.get_files()`.
-    # Note that ``?`` and ``*`` match all characters but slashes.
-    # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
-    # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
-    # '.svn': matches 'pkg/.svn' and all of its children
-    # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
-    # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
-    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
-                                  '.hg', '.svn', '_svn', '.git']
-
-    # Specifies which files should be considered python files.  It is
-    # useful when you have scripts inside your project.  Only files
-    # ending with ``.py`` are considered to be python files by
-    # default.
-    #prefs['python_files'] = ['*.py']
-
-    # Custom source folders:  By default rope searches the project
-    # for finding source folders (folders that should be searched
-    # for finding modules).  You can add paths to that list.  Note
-    # that rope guesses project source folders correctly most of the
-    # time; use this if you have any problems.
-    # The folders should be relative to project root and use '/' for
-    # separating folders regardless of the platform rope is running on.
-    # 'src/my_source_folder' for instance.
-    #prefs.add('source_folders', 'src')
-
-    # You can extend python path for looking up modules
-    #prefs.add('python_path', '~/python/')
-
-    # Should rope save object information or not.
-    prefs['save_objectdb'] = True
-    prefs['compress_objectdb'] = False
-
-    # If `True`, rope analyzes each module when it is being saved.
-    prefs['automatic_soa'] = True
-    # The depth of calls to follow in static object analysis
-    prefs['soa_followed_calls'] = 0
-
-    # If `False` when running modules or unit tests "dynamic object
-    # analysis" is turned off.  This makes them much faster.
-    prefs['perform_doa'] = True
-
-    # Rope can check the validity of its object DB when running.
-    prefs['validate_objectdb'] = True
-
-    # How many undos to hold?
-    prefs['max_history_items'] = 32
-
-    # Shows whether to save history across sessions.
-    prefs['save_history'] = True
-    prefs['compress_history'] = False
-
-    # Set the number spaces used for indenting.  According to
-    # :PEP:`8`, it is best to use 4 spaces.  Since most of rope's
-    # unit-tests use 4 spaces it is more reliable, too.
-    prefs['indent_size'] = 4
-
-    # Builtin and c-extension modules that are allowed to be imported
-    # and inspected by rope.
-    prefs['extension_modules'] = []
-
-    # Add all standard c-extensions to extension_modules list.
-    prefs['import_dynload_stdmods'] = True
-
-    # If `True` modules with syntax errors are considered to be empty.
-    # The default value is `False`; When `False` syntax errors raise
-    # `rope.base.exceptions.ModuleSyntaxError` exception.
-    prefs['ignore_syntax_errors'] = False
-
-    # If `True`, rope ignores unresolvable imports.  Otherwise, they
-    # appear in the importing namespace.
-    prefs['ignore_bad_imports'] = False
-
-
-def project_opened(project):
-    """This function is called after opening the project"""
-    # Do whatever you like here!

File pypy/translator/avm1/.ropeproject/globalnames

  • Ignore whitespace
-�}qUavm1q]q(UActionStringEqualsqUActionDefineLocalqUActionMultiplyqUActionCallFunctionqUActionShiftLeftqUActionSetVariableq	UActionAsciiToCharq
-UActionGetPropertyq
-ActionStopqU	ActionAndqUBranchingActionBaseqU
-ActionLessq
-ActionJumpq$UActionNewObjectq%U	Undefinedq&UActionCallMethodq'UActionMBCharToAsciiq(U
-ActionWithqPU
-ActionSwapqQU
-ActionPushqcUActionToIntegerqdUActionTypedEqualsqeU
-ActionCallqfUActionStringLessqgUActionSetMemberqhU
-ActionPlayqiU	DataTypesqjUActionStringLengthqkU

File pypy/translator/avm1/.ropeproject/history

  • Ignore whitespace
-�]q(]q]qe.

File pypy/translator/avm1/.ropeproject/objectdb

  • Ignore whitespace
-�}qUavm1.pyq}qUBlock.__init__qcrope.base.oi.memorydb
-ScopeInfo
-q)�q}qUinstanceqUdefinedq	hUActionDefineFunction2q
-��Uunknown�q

File pypy/translator/avm1/avm1.py

View file
  • Ignore whitespace
-
 # AVM1 = ActionScript Virtual Machine 1
 # Used for ActionScript 1 and 2
 
                _global="preload_global")
 
 class Action(object):
-    
+
     ACTION_NAME = "NotImplemented"
     ACTION_ID = 0x00
 
     offset = 0
     label_name = ""
-    
+
     def serialize(self):
         inner_data = self.gen_data()
         outer_data = self.gen_outer_data()
         header = struct.pack("<BH", self.ACTION_ID, len(inner_data))
         return header + inner_data + outer_data
-    
+
     def __len__(self):
         return 6 + len(self.gen_data()) + len(self.gen_outer_data())
-    
+
     def gen_data(self):
         return ""
 
     def gen_outer_data(self):
         return ""
-    
+
     def get_block_props_early(self, block):
         pass
 
             return ""
         else:
             return super(ActionConstantPool, self).serialize()
-    
+
     def gen_data(self):
         return struct.pack("H", len(self.pool)) + "\0".join(self.pool) + "\0"
 
     AUTO_LABEL_TEMPLATE = "label%d"
     MAX_REGISTERS = 4
     FUNCTION_TYPE = 0
-    
+
     def __init__(self, toplevel, insert_end=False):
         if toplevel:
             self.constants = toplevel.constants
         else:
             self.constants = ActionConstantPool()
             self.registers = []
-        
+
         self.code = ""
         self._sealed = False
         self.insert_end = insert_end
-        
+
         self.labels = {}
         self.branch_blocks = []
         self.actions = []
-        
+
         self.current_offset = 0
         self.label_count = 0
-    
+
     def get_free_register(self):
         if None in self.registers:
             return self.registers.index(None)
             index = self.get_free_register()
         self.registers[index] = value
         return index
-    
+
     def find_register(self, value):
         if value in self.registers:
             return self.registers.index(value)
         return -1
-    
+
     def free_register(self, index):
         self.registers[index] = None
-    
+
     def __len__(self):
         return self.current_offset + (2 if self.insert_end else 0)
 
     @property
     def sealed(self):
         return self._sealed
-    
+
     def add_action(self, action):
         if self._sealed:
             raise SealedBlockError("Block is sealed. Cannot add new actions")
 
         assert isinstance(action, Action)
-        
+
         self.code = "" # Dirty the code.
         action.offset = self.current_offset
         action.get_block_props_early(self)
-        
+
         # Do some early optimizations. Combine two pushes into one.
         if len(self.actions) > 0 and action.ACTION_NAME == "ActionPush" and self.actions[-1].ACTION_NAME == "ActionPush":
             old_action = self.actions[-1]
             self.actions.pop()
             self.current_offset -= 1 # len(ShortAction) is 1
             return None
-            
+
         if not isinstance(action, Block): # Don't add block length until we've finalized.
             self.current_offset += len(action)
-        
+
         self.actions.append(action)
         return action
-    
+
     def serialize(self):
         if not self._sealed:
             raise SealedBlockError("Block must be sealed before it can be serialized")
         name = Block.AUTO_LABEL_TEMPLATE % self.label_count
         self.labels[name] = -1
         return name
-        
+
     def set_label_here(self, name):
         self.labels[name] = self.current_offset
 
         self.function_name = name
         self.params = parameters
         self.preload_register_count = 1 # Start at 1.
-        
+
         # Flags
         self.registers        = [None]
         self.preload_parent   = False
 
         for name in parameters:
             self.registers.append(name)
-        
+
     def eval_flags(self):
-        
+
         # According to the docs, this is the order of register allocation.
         if self.preload_this and "this" not in self.registers:
             self.suppress_this = False
             self.registers.insert(1, "this")
-            
+
         if self.preload_args and "arguments" not in self.registers:
             self.suppress_args = False
             self.registers.insert(2, "arguments")
-            
+
         if self.preload_super and "super" not in self.registers:
             self.suppress_super = False
             self.registers.insert(3, "super")
-            
+
         if self.preload_root and "_root" not in self.registers:
             self.registers.insert(4, "_root")
-            
+
         if self.preload_parent and "_parent" not in self.registers:
             self.registers.insert(5, "_parent")
-        
+
         if self.preload_global and "_global" not in self.registers:
             self.registers.insert(6, "_global")
-        
+
     def gen_data(self):
 
         bits = BitStream()
         bits.write_bit(self.preload_this)
         bits.zero_fill(7) # skip over 7 Reserved bits
         bits.write_bit(self.preload_global)
-        
+
         self.block_data = Block.serialize(self)
         bytes = [self.function_name, "\0",
                  struct.pack("HB", len(self.params), len(self.registers)),
                  bits.serialize()]
-        
+
         for name in self.params:
             bytes += [chr(self.registers.index(name)), name, "\0"]
-        
+
         bytes += [struct.pack("H", len(self.block_data))]
         return "".join(bytes)
 
     ACTION_ID = 0x96
 
     USE_CONSTANTS = False
-    
+
     def __init__(self, *args):
         self.values = []
         self.add_element(*args)
-    
+
     def add_element(self, element):
         if hasattr(element, "__iter__") and not isinstance(element, (basestring, tuple)):
             for t in element:
                 element = (None, element)
             assert isinstance(element, tuple)
             self.values.append(element)
-        
+
     def get_block_props_early(self, block):
         if not ActionPush.USE_CONSTANTS: return
         for index, (value, type) in enumerate(self.values):
             if type == STRING:
                 constant_index = block.constants.add_constant(value)
                 self.values[index] = (constant_index, CONSTANT8 if constant_index < 256 else CONSTANT16)
-    
+
     def gen_data(self):
         bytes = []
         for value, type in self.values:
     def __init__(self, catch_object, try_block=None, catch_block=None, finally_block=None):
 
         self.catch_object = catch_object
-        
+
         self.try_block = try_block or Block()
         self.catch_block = catch_block or Block()
         self.finally_block = finally_block or Block()
 
     def gen_data(self):
         return struct.pack("HB", self.index, self.skip_count)
-    
+
 class ActionWaitForFrame2(Action):
     ACTION_NAME = "ActionWaitForFrame2"
     ACTION_ID = 0x8d
 class ActionWith(Action):
     ACTION_NAME = "ActionWith"
     ACTION_ID = 0x94
-    
+
     def __init__(self, with_block):
         self.block = with_block or Block()
-    
+
     def gen_data(self):
         return struct.pack("H", len(self.block)) + self.block.serialize()
 
     return ''.join('_' + c.lower() if c.isupper() else c for c in name)[1:]
 
 def make_short_action(value, name, push_count=0):
-    
     def __len__(self):
         return 1 # 1 (Action ID)
-    
+
     def serialize(self):
         return chr(self.ACTION_ID)
-    
+
     act = type(name, (Action,), dict(ACTION_ID=value, ACTION_NAME=name, push_count=push_count,
                                      __len__=__len__, serialize=serialize))
 

File pypy/translator/avm1/avm1gen.py

View file
  • Ignore whitespace
             
         super(PyPyAVM1Gen, self).load(v, *args)
 
-
     def new(self, TYPE):
         if isinstance(TYPE, ootype.List):
             self.oonewarray(None)
-    
+
+    def push_primitive_constant(self, TYPE, value):
+        if TYPE is ootype.Void:
+            self.push_null()
+        elif TYPE is ootype.String:
+            if value._str is None:
+                self.push_null()
+            else:
+                self.push_const(value._str)
+        else:
+            self.push_const(value)

File pypy/translator/avm1/records_flymake.py

  • Ignore whitespace
-
-from pypy.translator.avm1.util import BitStream
-from math import log, ceil, sqrt
-
-def serialize_style_list(lst):
-    bits = BitStream()
-
-    if len(lst) <= 0xFF:
-        bits.write_bit_value(len(lst), 8)
-    else:
-        bits.write_bit_value(0xFF, 8)
-        bits.write_bit_value(len(lst), 16)
-
-    for style in lst:
-        bits += style.serialize()
-
-    return bits
-
-def nbits(n, *a):
-    return int(ceil(log(max(1, n, *a), 2)))
-
-def nbits_abs(n, *a):
-    return nbits(abs(n), *(abs(n) for n in a))
-
-def style_list_bits(lst):
-    return nbits(len(lst))
-
-def clamp(n, minimum, maximum):
-    return max(minimum, min(n, maximum))
-
-class RecordHeader(object):
-
-    def __init__(self, type, length):
-        self.type = type
-        self.length = length
-
-    def serialize(self):
-        bits = BitStream()
-        bits.write_int_value(self.type, 10)
-        if self.length < 0x3F:
-            bits.write_int_value(self.length, 6)
-        else:
-            bits.write_int_value(0x3F, 6)
-            bits.write_int_value(self.length, 32)
-        return bits
-
-    def parse(self, bitstream):
-        self.type = bitstream.read_bit_value(10)
-        self.length = bitstream.read_bit_value(6)
-        if self.length >= 0x3F:
-            self.length = bitstream.read_bit_value(32)
-
-class _EndShapeRecord(object):
-    
-    def __call__(self, *a, **b):
-        pass
-
-    def serialize(self):
-        bitstream = BitStream()
-        bitstream.zero_fill(6)
-        return bitstream
-
-EndShapeRecord = _EndShapeRecord()
-
-class Rect(object):
-
-    def __init__(self, XMin=0, XMax=0, YMin=0, YMax=0):
-        self.XMin = XMin
-        self.XMax = XMax
-        self.YMin = YMin
-        self.YMax = YMax
-        
-    def union(self, rect, *rects):
-        r = Rect(min(self.XMin, rect.XMin),
-                 max(self.XMax, rect.XMax),
-                 min(self.YMin, rect.YMin),
-                 max(self.YMax, rect.YMax))
-        if len(rects) > 0:
-            return r.union(*rects)
-        return r
-    
-    def serialize(self):
-        if self.XMin > self.XMax or self.YMin > self.YMax:
-            raise ValueError, "Maximum values in a RECT must be larger than the minimum values."
-
-        # Find our values in twips.
-        twpXMin = self.XMin * 20
-        twpXMax = self.XMax * 20
-        twpYMin = self.YMin * 20
-        twpYMax = self.YMax * 20
-        
-        # Find the number of bits required to store the longest
-        # value, then add one to account for the sign bit.
-        NBits = nbits_abs(twpXMin, twpXMax, twpYMin, twpYMax)+1
-
-        if NBits > 31:
-            raise ValueError, "Number of bits per value field cannot exceede 31."
-
-        # And write out our bits.
-        bits = BitStream()
-        bits.write_int_value(NBits, 5)
-        bits.write_int_value(twpXMin, NBits)
-        bits.write_int_value(twpXMax, NBits)
-        bits.write_int_value(twpYMin, NBits)
-        bits.write_int_value(twpYMax, NBits)
-
-        return bits
-
-    def parse(self, bitstream):
-        
-        NBits = bitstream.read_bit_value(5)
-        self.XMin = bitstream.read_bit_value(NBits)
-        self.XMax = bitstream.read_bit_value(NBits)
-        self.YMin = bitstream.read_bit_value(NBits)
-        self.YMax = bitstream.read_bit_value(NBits)
-
-class XY(object):
-
-    def __init__(self, X=0, Y=0):
-        self.X = 0
-        self.Y = 0
-
-    def serialize(self):
-        # Convert to twips plz.
-        twpX = self.X * 20
-        twpY = self.Y * 20
-
-        # Find the number of bits required to store the longest
-        # value, then add one to account for the sign bit.
-        NBits = nbits_abs(twpX, twpY)
-
-        bits = BitStream()
-        bits.write_int_value(NBits, 5)
-        bits.write_int_value(twpX, NBits)
-        bits.write_int_value(twpY, NBits)
-
-        return bits
-
-    def parse(self, bitstream):
-        
-        NBits = bitstream.read_bit_value(5)
-        self.X = bitstream.read_bit_value(NBits)
-        self.Y = bitstream.read_bit_value(NBits)
-
-class RGB(object):
-
-    def __init__(self, color):
-        self.color = color & 0xFFFFFF
-
-    def serialize(self):
-        bits = BitStream()
-        bits.write_int_value(self.color, 24)
-        return bits
-
-    def parse(self, bitstream):
-        self.color = bitstream.read_bit_value(24)
-
-class RGBA(RGB):
-    
-    def __init__(self, color, alpha=1.0):
-        super(RGBA, self).__init__(color)
-        self.alpha = alpha
-
-    def serialize(self):
-        bits = RGB.serialize(self)
-        
-        from pypy.translator.avm1.tags import DefineShape
-        
-        # If we are in a DefineShape and the version does not support
-        # alpha (DefineShape1 or DefineShape2), don't use alpha!
-        if DefineShape._current_variant not in (1, 2):
-            bits.write_int_value(int(self.alpha * 0xFF), 8)
-        
-        return bits
-
-    def parse(self, bitstream):
-        RGB.parse(self, bitstream)
-        self.alpha = bitstream.read_bit_value(8) / 0xFF
-
-class CXForm(object):
-    has_alpha = False
-    def __init__(self, rmul=1, gmul=1, bmul=1, radd=0, gadd=0, badd=0):
-        self.rmul = rmul
-        self.gmul = gmul
-        self.bmul = bmul
-        self.amul = 1
-        self.radd = radd
-        self.gadd = gadd
-        self.badd = badd
-        self.aadd = 0
-
-    def serialize(self):
-        has_add_terms = self.radd != 0 or self.gadd != 0 or self.badd != 0 or self.aadd != 0
-        has_mul_terms = self.rmul != 1 or self.gmul != 1 or self.bmul != 1 or self.amul != 1
-        
-        rm = abs(self.rmul * 256)
-        gm = abs(self.gmul * 256)
-        bm = abs(self.bmul * 256)
-        am = abs(self.amul * 256)
-        
-        ro = clamp(self.radd, -255, 255)
-        go = clamp(self.gadd, -255, 255)
-        bo = clamp(self.badd, -255, 255)
-        ao = clamp(self.aadd, -225, 255)
-        
-        NBits = 0
-        if has_mul_terms: NBits = nbits_abs(rm, gm, bm, am)
-        if has_add_terms: NBits = max(NBits, nbits_abs(ro, go, bo, ao))
-        
-        bits = BitStream()
-        bits.write_int_value(NBits, 4)
-
-        if has_mul_terms:
-            bits.write_int_value(rm, NBits)
-            bits.write_int_value(gm, NBits)
-            bits.write_int_value(bm, NBits)
-            if self.has_alpha: bits.write_int_value(am, NBits)
-
-        if has_add_terms:
-            bits.write_int_value(ro, NBits)
-            bits.write_int_value(go, NBits)
-            bits.write_int_value(bo, NBits)
-            if self.has_alpha: bits.write_int_value(ao, NBits)
-
-        return bits
-
-class CXFormWithAlpha(CXForm):
-    has_alpha = True
-    def __init__(self, rmul=1, gmul=1, bmul=1, amul=1, radd=0, gadd=0, badd=0, aadd=0):
-        super(self, CXFormWithAlpha).__init__(rmul, gmul, bmul, radd, gadd, badd)
-        self.amul = amul
-        self.aadd = aadd
-
-class Matrix(object):
-    
-    def __init__(self, a=1, b=0, c=0, d=1, tx=0, ty=0):
-        self.a, self.b, self.c, self.d, self.tx, self.ty = a, b, c, d, tx, ty
-
-    def serialize(self):
-        
-        def write_prefixed_values(a, b):
-            NBits = nbits(a, b)
-            bits.write_int_value(NBits, 5)
-            bits.write_int_value(a, NBits)
-            bits.write_int_value(b, NBits)
-        
-        bits = BitStream()
-        if self.a != 1 or self.d != 1: # HasScale
-            bits.write_bit(True)
-            write_prefixed_values(self.a, self.d)
-        else:
-            bits.write_bit(False)
-
-        if self.b != 0 or self.c != 0: # HasRotate
-            bits.write_bit(True)
-            write_prefixed_values(self.b, self.c)
-        else:
-            bits.write_bit(False)
-
-        write_prefixed_values(self.tx * 20, self.ty * 20)
-        return bits
-
-class Shape(object):
-
-    def __init__(self):
-        self.shapes = []
-        
-        self.edge_bounds = Rect()
-        self.shape_bounds = Rect()
-        
-        self.has_scaling = False
-        self.has_non_scaling = False
-        
-        self.bounds_calculated = False
-
-    def add_shape_record(self, shape):
-        self.shapes.append(shape)
-        self.bounds_calculated = False
-    
-    def add_shape(self, shape):
-        self.shapes.expand(shape.shapes)
-        self.bounds_calculated = False
-
-    def serialize(self):
-        if EndShapeRecord not in self.shapes:
-            self.shapes.append(EndShapeRecord())
-
-        bits = BitStream()
-
-        bits.write_int_value(0, 8) # NumFillBits and NumLineBits
-        for record in self.shapes:
-            bits += record.serialize()
-
-        return bits
-
-    def calculate_bounds(self):
-
-        if self.bounds_calculated:
-            return
-
-        last = 0, 0
-        style = None
-        for record in self.shapes:
-            last, (self.shape_bounds, self.edge_bounds), (has_scale, has_non_scale, style) = \
-                  record.calculate_bounds(last, self.shape_bounds, self.edge_bounds, style)
-            if has_scale:
-                self.has_scaling = True
-            if has_non_scale:
-                self.has_non_scaling = True
-
-        self.bounds_calculated = True
-
-class ShapeWithStyle(Shape):
-
-    def __init__(self, fills=None, strokes=None):
-        super(self, ShapeWithStyle).__init__(self)
-        self.fills = fills or []
-        self.strokes = strokes or []
-
-    def add_fill_style(self, style):
-        style.parent = self.fills
-        self.fills.append(style)
-
-    def add_line_style(self, style):
-        style.parent = self.strokes
-        self.strokes.append(style)
-        
-    def add_shape(self, shape):
-        Shape.add_shape(self, shape)
-        try:
-            self.fills += shape.fills
-            self.strokes += shape.strokes
-        except AttributeError:
-            pass
-    
-    def serialize(self):
-        bits = BitStream()
-        bits += serialize_style_list(self.fills)
-        bits += serialize_style_list(self.strokes)
-        bits.write_int_value(style_list_bits(self.fills), 4)
-        bits.write_int_value(style_list_bits(self.strokes), 4)
-        return bits
-
-class LineStyle(object):
-
-    caps = "round"
-    
-    def __init__(self, width=1, color=0, alpha=1.0):
-        self.width = width
-        self.color = RGBA(color, alpha)
-
-    @property
-    def index(self):
-        return self.parent.find(self)
-    
-    def serialize(self):
-        bits = BitStream()
-        bits.write_int_value(self.width * 20, 16)
-        bits += self.color.serialize()
-        return bits
-
-class LineStyle2(LineStyle):
-
-    def __init__(self, width=1, fillstyle=None, pixel_hinting=False, scale_mode=None, caps="round", joints="round", miter_limit=3):
-
-        color, alpha, self.fillstyle = 0, 1.0, None
-        
-        if isinstance(fillstyle, RGBA):
-            color = fillstyle.color
-            alpha = fillstyle.alpha
-        elif isinstance(fillstyle, RGB):
-            color = fillstyle.color
-        elif isinstance(fillstyle, int):
-            if fillstyle > 0xFFFFFF:
-                color = fillstyle & 0xFFFFFF
-                alpha = fillstyle >> 6 & 0xFF
-            else:
-                color = fillstyle
-        elif isinstance(fillstyle, FillStyleSolidFill):
-            color = fillstyle.color.color
-            alpha = fillstyle.color.alpha
-        elif isinstance(fillstyle, FillStyle):
-            self.fillstyle = fillstyle
-        
-        super(self, LineStyle2).__init__(self, width, color, alpha)
-        self.pixel_hinting = pixel_hinting
-        self.h_scale = (scale_mode == "normal" or scale_mode == "horizontal")
-        self.v_scale = (scale_mode == "normal" or scale_mode == "vertical")
-
-        if caps == "square":  self.caps = 2
-        elif caps == None:    self.caps = 1
-        elif caps == "round": self.caps = 0
-        else:
-            raise ValueError, "Invalid cap style '%s'." % caps
-
-        if joints == "miter":   self.joints = 2
-        elif joints == "bevel": self.joints = 1
-        elif joints == "round": self.joints = 0
-
-        self.miter_limit = miter_limit
-
-    def serialize(self):
-
-        bits = BitStream()
-        bits.write_int_value(self.width * 20, 8)
-        bits.write_int_value(self.width * 20 >> 8, 8)
-
-        bits.write_int_value(self.caps, 2)
-        bits.write_int_value(self.joints, 2)
-        bits.write_bit(self.fillstyle is not None);
-        bits.write_bit(self.h_scale)
-        bits.write_bit(self.v_scale)
-        bits.write_bit(self.pixel_hinting)
-
-        if self.joints == 2:
-            bits.write_fixed_value(self.miter_limit, 16, True)
-
-        if self.fillstyle:
-            bits.write_bits(self.fillstyle.serialize())
-        else:
-            bits.write_bits(self.color.serialize())
-
-        return bits
-
-    def cap_style_logic(self, style, last, delta):
-        # Half thickness (radius of round cap; diameter is thickness)
-        off = style.width / 2.0
-        dx, dy = delta
-        lx, ly = last
-        
-        if style.caps == "round":
-            r = Rect()
-            r.XMin = cmp(dx, 0) * off
-            r.YMin = cmp(dy, 0) * off
-            r.XMax = r.XMin + dx
-            r.YMax = r.XMax + dy
-            return r
-        
-        if style.caps == "square":
-            
-            # Account for the length of the caps.
-            dellen = sqrt(dx*dx + dy*dy)  # Delta length
-            norm = (dellen+off*2)/dellen  # Extra length
-            dx *= norm                    # Add the extra length
-            dy *= norm
-            sqx, sqy = delta              # Square cap offset
-            norm = off/dellen             # Offset amount
-            sqx *= norm                   # Position offsets.
-            sqy *= norm
-            
-            # And offset the position.
-            lx -= sqx
-            ly -= sqy
-
-        # Right-hand normal to vector delta relative to (0, 0).
-        p1x, p1y = (-dy, dx)
-        norm = sqrt(p1x*p1x + p1y*p1y)
-        p1x /= norm
-        p1y /= norm
-
-        # Left-hand normal to vector delta relative to (0, 0)
-        p2x, p2y = (-p1x, -p1y)
-        
-        # Right-hand normal to vector delta relative to delta.
-        p3x, p3y = (p1x + dx, p1y + dy)
-
-        # Left-hand normal to vector delta relative to delta.
-        p4x, p4y = (p2x + dx, p2y + dy)
-
-        return Rect(
-            min(p1x, p2x, p3x, p4x) + lx,
-            max(p1x, p2x, p3x, p4x) + lx,
-            min(p1y, p2y, p3y, p4y) + ly,
-            max(p1y, p2y, p3y, p4y) + ly)
-
-class FillStyle(object):
-
-    TYPE = -1
-    
-    @property
-    def index(self):
-        return self.parent.find(self)
-    
-    def serialize(self):
-        bits = BitStream()
-        bits.write_int_value(self.TYPE, 8)
-        bits += self.serialize_inner()
-        return bits
-
-class FillStyleSolidFill(object):
-    
-    def __init_(self, color, alpha=1.0):
-        self.color = RGBA(color, alpha)
-
-    def serialize_inner(self):
-        return self.color.serialize()
-
-class GradRecord(object):
-
-    def __init__(self, ratio, color, alpha=1.0):
-        self.ratio = ratio
-        self.color = RGBA(color, alpha)
-
-    def serialize(self):
-        bits = BitStream()
-        bits.write_int_value(self.ratio, 8)
-        bits += self.color.serialize()
-        return bits
-
-class Gradient(object):
-
-    def __init__(self, grads, spread="pad", interpolation="rgb", focalpoint=0):
-        import operator
-        grads.sort(key=operator.attrgetter("ratio"))
-        self.grads = grads
-        self.spread = spread
-        self.interpolation = interpolation
-        self.focalpoint = focalpoint
-        
-    @classmethod
-    def from_begin_gradient_fill(cls, colors, alphas, ratios, spread, interpolation, focalpoint):
-        grads = [GradRecord(*t) for t in zip(ratios, colors, alphas)]
-        return cls(grads, spread, interpolation, focalpoint)
-    
-class StraightEdgeRecord(object):
-
-    def __init__(self, delta_x, delta_y):
-        self.delta_x = delta_x
-        self.delta_y = delta_y
-        self.bounds_calculated = False
-
-    def serialize(self):
-            
-        bits = BitStream()
-        
-        if self.delta_x == 0 and self.delta_y == 0:
-            return bits
-
-        bits.write_bit(True) # TypeFlag
-        bits.write_bit(True) # StraightFlag
-
-        X = self.delta_x * 20
-        Y = self.delta_y * 20
-
-        NBits = nbits_abs(X, Y)
-
-        if NBits > 15:
-            raise ValueError("Number of bits per value field cannot exceed 15")
-        
-        bits.write_int_value(NBits, 4)
-        NBits += 2
-        if X == 0:
-            # Vertical Line
-            bits.write_bit(False) # GeneralLineFlag
-            bits.write_bit(True)  # VerticalLineFlag
-            bits.write_int_value(Y, NBits)
-        elif Y == 0:
-            # Horizontal Line
-            bits.write_bit(False) # GeneralLineFlag
-            bits.write_bit(True)  # HorizontalLineFlag
-            bits.write_int_value(X, NBits)
-        else:
-            # General Line
-            bits.write_bit(True) # GeneralLineFlag
-            bits.write_int_value(X, NBits)
-            bits.write_int_value(Y, NBits)
-
-        return bits
-
-    def calculate_bounds(self, last, shape_bounds, edge_bounds, style):
-        rect = Rect(last[0], last[1], self.delta_x, self.delta_y)
-        return ((self.delta_x, self.delta_y),
-                (shape_bounds.union(rect),
-                 edge_bounds.union(LineStyle2.cap_style_logic(style,
-                              last, (self.delta_x, self.delta_y)))),
-                (False, False, style))
-
-
-class CurvedEdgeRecord(object):
-
-    def __init__(self, controlx, controly, anchorx, anchory):
-        self.controlx = controlx
-        self.controly = controly
-        self.anchorx = anchorx
-        self.anchory = anchory
-
-    def serialize(self):
-            
-        bits = BitStream()
-        
-        if self.delta_x == 0 and self.delta_y == 0:
-            return bits
-
-        bits.write_bit(True)  # TypeFlag
-        bits.write_bit(False) # StraightFlag
-
-        cX = self.controlx * 20
-        cY = self.controly * 20
-        aX = self.anchorx  * 20
-        aY = self.anchory  * 20
-        
-        NBits = nbits_abs(cX, cY, aX, aY)
-
-        if NBits > 15:
-            raise ValueError("Number of bits per value field cannot exceed 15")
-
-        bits.write_int_value(NBits, 4)
-        NBits += 2
-        bits.write_int_value(cX, NBits)
-        bits.write_int_value(cY, NBits)
-        bits.write_int_value(aX, NBits)
-        bits.write_int_value(aY, NBits)
-        return bits
-    
-    def _get_x(self, t):
-        return self.controlx * 2 * (1-t) * t + self.anchorx * t * t;
-
-    def _get_y(self, t):
-        return self.controly * 2 * (1-t) * t + self.anchory * t * t;
-
-    def _get_p(self, t):
-        return (self._get_x(t), self._get_y(t))
-    
-    def calculate_bounds(self, last, shape_bounds, edge_bounds, style):
-        union = Rect(0, 0, 0, 0)
-        # CurvedEdgeRecord Bounds
-        # Formulas somewhat based on
-        # http://code.google.com/p/bezier/source/browse/trunk/bezier/src/flash/geom/Bezier.as
-        # Maths here may be incorrect
-        
-        # extremumX = last.x - 2 * control.x + anchor.x
-        # extremumX = last.x - 2 * ( controlDeltaX - last.x ) + anchorDeltaX - last.x
-        # extremumX = (last.x - last.x) - 2 * ( controlDeltaX - last.x ) + anchorDeltaX
-	# extremumX = -2 * ( controlDeltaX - last.x ) + anchorDeltaX
-        
-	# For the case of last.[x/y] = 0, we can use the formula below.
-
-        x = -2 * self.controlx + self.anchorx
-        t = -self.controlx / x
-        p = self._get_x(t)
-
-        if t <= 0 or t >= 1:
-            union.XMin = last[0] + min(self.anchorx, 0)
-            union.XMax = union.XMin + max(self.anchorx, 0)
-        else:
-            union.XMin = min(p, 0, self.anchorx + last[0])
-            union.XMax = union.XMin + max(p - last[0], 0, self.anchorx)
-            
-        y = -2 * self.controly + self.anchory
-        t = -self.controly / y
-        p = self._get_y(t)
-
-        if t <= 0 or t >= 1:
-            union.YMin = last[1] + min(self.anchory, 0)
-            union.YMax = union.YMin + max(self.anchory, 0)
-        else:
-            union.YMin = min(p, 0, self.anchory + last[1])
-            union.YMax = union.YMin + max(p - last[0], 0, self.anchorY)
-
-        # CapStyle logic:
-
-        # Assume that p0 is last (start anchor),
-        # p1 is control, and p2 is (end) anchor.
-
-        # Get some small increments in the segment to
-        # find somewhat of a slope derivative type thing.
-
-        # We should be able to pass these two line deltas
-        # into LineStyle2.cap_style_logic and union the
-        # results.
-        
-        slope1 = self._get_p(0.01)
-        slope2 = (self.anchorx - self._get_x(0.99), self.anchory - self._get_y(0.99))
-        end_cap_rect   = LineStyle2.cap_style_logic(style, last, slope2)
-        start_cap_rect = LineStyle2.cap_style_logic(style, last, slope1)
-
-        return ((self.anchorx, self.anchory),
-                (shape_bounds.union(union),
-                 edge_bounds.union(union, start_cap_rect, end_cap_rect)),
-                (False, False, style))
-
-class StyleChangeRecord(object):
-
-    def __init__(self, delta_x, delta_y, linestyle=None,
-                 fillstyle0=None, fillstyle1=None,
-                 fillstyles=None, linestyles=None):
-        
-        self.delta_x = delta_x
-        self.delta_y = delta_y
-        self.linestyle = linestyle
-        self.fillstyle0 = fillstyle0
-        self.fillstyle1 = fillstyle1
-        self.fillstyles = fillstyles
-        self.linestyles = linestyles
-
-    def serialize(self):
-        bits = BitStream()
-        if self.fillstyle0 is not None and self.fillstyle1 is not None and \
-               self.fillstyle0.parent != self.fillstyle1.parent:
-            raise ValueError("fillstyle0 and fillstyle1 do not have the same parent!")
-        
-        fsi0 = 0 if self.fillstyle0 is None else self.fillstyle0.index
-        fsi1 = 0 if self.fillstyle1 is None else self.fillstyle1.index
-        lsi  = 0 if self.linestyle  is None else self.linestyle.index
-
-        fbit = 0 if self.fillstyle0 is None else style_list_bits(self.fillstyle0.parent)
-        lbit = 0 if self.linestyle  is None else style_list_bits(self.linestyle.parent)
-        
-        from pypy.translator.avm.tags import DefineShape
-        
-        new_styles = ((DefineShape._current_variant > 1) and
-                     ((self.linestyles != None and len(self.linestyles) > 0) or
-                      (self.fillstyles != None and len(self.fillstyles) > 0)))
-
-        bits.write_bit(False)       # TypeFlag
-        bits.write_bit(new_styles)  # StateNewStyles
-        bits.write_bit(lsi  > 0)    # StateLineStyle
-        bits.write_bit(fsi0 > 0)    # StateFillStyle0
-        bits.write_bit(fsi1 > 0)    # StateFillStyle1
-
-        move_flag = self.delta_x != 0 or self.delta_y != 0
-
-        if move_flag:
-            bits += XY(self.delta_x, self.delta_y).serialize()
-
-        if fsi0 > 0:  bits.write_int_value(fsi0, fbit) # FillStyle0
-        if fsi1 > 0:  bits.write_int_value(fsi1, fbit) # FillStyle1
-        if lsi  > 0:  bits.write_int_value(lsi,  lbit) # LineStyle
-        
-        if new_styles:
-            bits += ShapeWithStyle._serialize_style_list(self.fillstyles) # FillStyles
-            bits += ShapeWithStyle._serialize_style_list(self.linestyles) # LineStyles
-
-            bits.write_int_value(style_list_bits(self.fillstyles), 4) # FillBits
-            bits.write_int_value(style_list_bits(self.linestyles), 4) # LineBits
-
-        return bits

File pypy/translator/avm1/test/harness_flymake.py

  • Ignore whitespace
-
-from pypy.translator.avm1.test import browsertest as b
-from pypy.translator.avm1 import avm1 as a, avm1gen as g, swf as s, tags as t, records as r
-
-class TestHarness(object):
-    def __init__(self, name):
-        self.testname  = name
-        self.swf = s.SwfData()
-        self.swf.add_tag(t.SetBackgroundColor(0x333333))
-        self.swf.add_tag(t.DefineEditText(r.Rect(0, 0, 0, 0), "txt",
-                                          "Testing %s." % (name,), color=r.RGBA(0xFFFFFF)))
-        self.swf.add_tag(t.PlaceObject2(1, 2))
-        self.actions = g.AVM1Gen(t.DoAction())
-        self.swf.add_tag(self.actions.block)
-        self.swf.add_tag(t.ShowFrame())
-        self.swf.add_tag(t.End())
-        self.start_test()
-        
-    def print_text(self, text):
-        self.actions.push_const("txt", "\n" + text)
-        self.actions.push_var("txt")
-        self.actions.swap()
-        self.actions.emit('typed_add')
-        self.actions.set_variable()
-
-    def print_var(self, prefix, varname):
-        self.actions.push_const("txt")
-        self.actions.push_var("txt")
-        self.actions.push_const("\n" + prefix)
-        self.actions.push_var(varname)
-        self.actions.emit('typed_add')
-        self.actions.emit('typed_add')
-        self.actions.set_variable()
-
-    def print_stack(self, prefix):
-        self.actions.push_const("txt")
-        self.actions.swap()
-        self.actions.push_var("txt")
-        self.actions.swap()
-        self.actions.push_const("\n" + prefix)
-        self.actions.swap()
-        self.actions.emit('typed_add')
-        self.actions.emit('typed_add')
-        self.actions.set_variable()
-    
-    def start_test(self):
-        self.print_text("Running test %s." % self.testname)
-        self.actions.push_const("result")
-        
-    def finish_test(self):
-        # result value is on the stack,
-        # followed by the string "result"
-        self.actions.set_variable()
-        self.print_var("Got: ", "result")
-        self.actions.push_const("/test.result", "") # URL, target
-        self.actions.action(a.ActionGetURL2("POST", True, True))
-        self.actions.push_const("javascript:window.close()", "") # Close the window.
-        self.actions.action(a.ActionGetURL2(""))
-
-    def do_test(self, debug=False):
-        self.finish_test()
-        self.actions.scope.block.seal()
-        if debug:
-            f = open("test.swf", "w")
-            f.write(self.swf.serialize())
-            f.close()
-        return b.browsertest(self.testname, self.swf)

File pypy/translator/avm1/types_.py

View file
  • Ignore whitespace
 
-from pypy.translator.avm import avm1
 from pypy.rlib.rarithmetic import r_longlong, r_ulonglong
 from pypy.rpython.ootypesystem import ootype
 from pypy.rpython.lltypesystem import lltype
 
+from mech.fusion.avm1 import types_, actions
+
 _pytype_to_avm1 = {
-    str:         avm1.STRING,
-    unicode:     avm1.STRING,
-    int:         avm1.INTEGER,
-    long:        avm1.INTEGER,
-    r_longlong:  avm1.INTEGER,
-    r_ulonglong: avm1.INTEGER,
-    bool:        avm1.BOOLEAN,
-    float:       avm1.DOUBLE,
+    r_longlong:  types_.INTEGER,
+    r_ulonglong: types_.INTEGER,
 }
 
+_pytype_to_avm1.update(types_._pytype_to_avm1)
+
 def pytype_to_avm1(value):
     return (value, _pytype_to_avm1[type(value)])
 

File pypy/translator/avm2/avm2gen.py

View file
  • Ignore whitespace
-
 """ backend generator routines
 """
 
 from pypy.translator.oosupport.constant import push_constant
 from pypy.translator.oosupport.function import render_sub_op
 
-
 from itertools import chain
 
 class PyPyAvm2ilasm(avm2gen.Avm2ilasm, Generator):
-
-    def __init__(self, db, abc):
-        super(PyPyAvm2ilasm, self).__init__(abc)
+    def __init__(self, db, abc, optimize=False):
+        super(PyPyAvm2ilasm, self).__init__(abc, optimize=optimize)
         self.db  = db
         self.cts = db.genoo.TypeSystem(db)
 
     def _get_type(self, TYPE):
-        return self.cts.lltype_to_cts(TYPE)
-
-    def _get_class_context(self, name, DICT):
-        class_desc = query.get_class_desc(name)
-        if class_desc:
-            BaseType = class_desc.BaseType
-            if '.' in BaseType:
-                ns, name = class_desc.BaseType.rsplit('.', 1)
-            else:
-                ns, name = '', BaseType
-            class_desc.super_name = constants.packagedQName(ns, name)
-            class_desc.name       = constants.packagedQName(class_desc.Package, class_desc.ShortName)
-            return class_desc
-        else:
-            return super(PyPyAvm2ilasm, self).get_class_context(name, DICT)
+        t = self.cts.lltype_to_cts(TYPE)
+        if t:
+            return t.multiname()
+        return super(PyPyAvm2ilasm, self)._get_type(TYPE)
 
     def load(self, v, *args):
         if isinstance(v, flowmodel.Variable):
         for e in args:
             self.load(e)
 
-    # def prepare_call_oostring(self, OOTYPE):
-    #     self.I(instructions.findpropstrict(types._str_qname))
-    
-    # def call_oostring(self, OOTYPE):
-    #     self.I(instructions.callproperty(types._str_qname, 1))
-        
-    # call_oounicode = call_oostring
-    # prepare_call_oounicode = prepare_call_oostring
-    
     def oonewarray(self, TYPE, length=1):
         self.load(types.vec_qname)
         self.load(self.cts.lltype_to_cts(TYPE.ITEM))
         self.I(instructions.applytype(1))
         self.load(length)
         self.I(instructions.construct(1))
-        self.I(instructions.coerce(self.cts.lltype_to_cts(TYPE).multiname()))
-    
+        self.I(instructions.coerce(self.cts.lltype_to_cts(TYPE)))
+
     def push_primitive_constant(self, TYPE, value):
         if TYPE is ootype.Void:
             self.push_null()
         elif TYPE is ootype.String:
             if value._str is None:
                 self.push_null()
+                self.downcast(types.types.string)
             else:
                 self.push_const(value._str)
         else:
 
     def new(self, TYPE):
         # XXX: assume no args for now
-        t = self.cts.lltype_to_cts(TYPE).multiname()
+        t = self._get_type(TYPE)
         self.emit('findpropstrict', t)
         self.emit('constructprop', t, 0)
 
         self.I(instructions.getproperty(constants.MultinameL(
                     constants.PROP_NAMESPACE_SET)))
 
-    def array_length(self):
-        self.I(instructions.getproperty(constants.QName("length")))
-    
-    def call_graph(self, graph, func_name=None):
+    def call_graph(self, graph, args=[]):
         """
         Call a graph.
         """
-        if func_name is None:
-            self.db.pending_function(graph)
-        func_name = func_name or graph.name
+        self.db.pending_function(graph)
         namespace = getattr(graph.func, '_namespace_', None)
+        numargs = len(args)
         if namespace:
-            qname = constants.packagedQName(namespace, func_name)
+            qname = constants.packagedQName(namespace, graph.name)
         else:
-            qname = constants.QName(func_name)
+            qname = constants.QName(graph.name)
         self.emit('findpropstrict', qname)
-        self.emit('callproperty', qname)
+        self.load(*args)
+        self.emit('callproperty', qname, numargs)
 
     def store(self, v):
         """
         self.push_var(v.name)
 
     push_arg = push_local
-
-    def new(self, TYPE):
-        # XXX: assume no args for now
-        TYPE = self._get_type(TYPE)
-        self.emit('findpropstrict', TYPE)
-        self.emit('constructprop', TYPE, 0)

File pypy/translator/avm2/class_.py

View file
  • Ignore whitespace
 from pypy.translator.cli.node import Node
 from pypy.translator.oosupport.constant import push_constant
 
-from mech.fusion.avm2 import constants as c, traits
+from mech.fusion.avm2 import constants, traits
 from pypy.translator.avm2 import types_ as types
 
 try:
     def get_base_class(self):
         base_class = self.INSTANCE._superclass
         if self.INSTANCE is self.db.genoo.EXCEPTION:
-            return c.QName("Error")
+            return constants.QName("Error")
         if self.is_root(base_class):
-            return c.QName("Object")
+            return constants.QName("Object")
         else:
             ns, name = self.db.class_name(base_class).rsplit('::', 1)
-            return c.packagedQName(ns, name)
+            return constants.packagedQName(ns, name)
 
     def is_abstract(self):
         return False # XXX
             return
 
         self.ilasm = ilasm
-        self.gen = CLIBaseGenerator(self.db, ilasm)
 
-        ilasm.begin_class(c.packagedQName(self.namespace, self.name), self.get_base_class())
+        ilasm.begin_class(constants.packagedQName(self.namespace, self.name), self.get_base_class())
         for f_name, (f_type, f_default) in self.INSTANCE._fields.iteritems():
             cts_type = self.cts.lltype_to_cts(f_type)
             f_name = self.cts.escape_name(f_name)
             if cts_type != types.types.void:
-                ilasm.context.add_instance_trait(traits.AbcSlotTrait(c.QName(f_name), cts_type.multiname()))
+                ilasm.context.add_instance_trait(traits.AbcSlotTrait(constants.QName(f_name), cts_type.multiname()))
 
         self._ctor()
         self._toString()
                 while context:
                     if m_name in context._methods:
                         f.override = True
-                        print "Overriding", m_name
                         break
                     context = context._superclass
 
                            if ARG is not ootype.Void]
                 returntype = self.cts.lltype_to_cts(METH.RESULT)
                 ilasm.begin_method(m_name, arglist, returntype)
-                ilasm.emit('findpropstrict', c.QName("Error"))
+                ilasm.emit('findpropstrict', constants.QName("Error"))
                 ilasm.push_const("Abstract method %s::%s called" % (self.name, m_name))
-                ilasm.emit('constructprop', c.QName("Error"), 1)
-                ilasm.emit('throw')
+                ilasm.emit('constructprop', constants.QName("Error"), 1)
+                ilasm.throw()
                 ilasm.exit_context()
 
         ilasm.exit_context()
     
     def _ctor(self):
-        self.ilasm.context.make_iinit()
+        self.ilasm.begin_constructor()
         # set default values for fields
         default_values = self.INSTANCE._fields.copy()
         default_values.update(self.INSTANCE._overridden_defaults)
                 self.ilasm.push_this()
                 push_constant(self.db, F_TYPE, f_default, self.gen)
                 # class_name = self.db.class_name(INSTANCE_DEF)
-                self.ilasm.emit('setproperty', c.QName(f_name))
-
-        self.ilasm.exit_context()
+                self.ilasm.set_field(f_name)
+        self.ilasm.end_constructor()
 
     def _toString(self):
         if self.is_root(self.INSTANCE._superclass):
         wrapper = "Exception" if self.exception else "Instance"
         self.ilasm.begin_method('toString', [], types.types.string, override=override)
         self.ilasm.load("%sWrapper('%s')" % (wrapper, self.name))
-        self.ilasm.emit('returnvalue')
-        self.ilasm.exit_context()
-
+        self.ilasm.return_value()
+        self.ilasm.end_method()

File pypy/translator/avm2/conftest.py

View file
  • Ignore whitespace
 def pytest_addoption(parser):
     group = parser.getgroup("pypy-tamarin options")
     group.addoption('--swf', action="store_const", const="swf", dest="tamtarget", default="swf",
-            help="generate a swf and abc and use a browsertest to run")
+                    help="generate a .swf and .abc and use a browsertest and Flash Player to run")
     group.addoption('--tamarin', action="store_const", const="tamarin", dest="tamtarget",
-                    help="generate an abc that uses tamarin")
+                    help="generate an abc that uses Tamarin")
+    group.addoption('--no-mf-optimize', action="store_false", default=True, dest="mf_optim",
+                    help="don't do simple MF optimizations")

File pypy/translator/avm2/function.py

View file
  • Ignore whitespace
+
 from functools import partial
 
 from pypy.objspace.flow import model as flowmodel
 from pypy.rpython.lltypesystem.lltype import Void
 from pypy.translator.oosupport.function import Function as OOFunction
 from pypy.translator.cli.node import Node
-from pypy.translator.avm2 import types_ as types
 from mech.fusion.avm2 import constants
 
 class Function(OOFunction, Node):
-    
+
     auto_propagate_exceptions = True
 
-    def __init__(self, *args, **kwargs):
-        OOFunction.__init__(self, *args, **kwargs)
-        
+    def __init__(self, db, graph, name=None, is_method=False, is_entrypoint=False):
+        OOFunction.__init__(self, db, graph, name, is_method, is_entrypoint)
+
         if hasattr(self.db.genoo, 'exceptiontransformer'):
             self.auto_propagate_exceptions = False
-        
+
         namespace = getattr(self.graph.func, '_namespace_', None)
         if namespace:
             if '.' in namespace:
         else:
             self.namespace = None
             self.classname = None
-        
+
         self.override = False
-        
+
     def _create_generator(self, ilasm):
         ilasm.db = self.db
         return ilasm
-    
+
     def record_ll_meta_exc(self, ll_meta_exc):
         # record the type only if it doesn't belong to a native_class
         ll_exc = ll_meta_exc._INSTANCE
 
         if self.is_method:
             self.args = self.args[1:]
-        
+
         returntype, returnvar = self.cts.llvar_to_cts(self.graph.getreturnvar())
 
         if self.classname:
             self.generator.begin_class(constants.packagedQName(self.namespace, self.classname))
-        
+
         self.generator.begin_method(self.name, self.args, returntype, static=not self.is_method, override=self.override)
-        
+
+        self.declare_locals()
+
     def end_render(self):
-        # if self.generator.scope.islabel:
-        #     self.generator.exit_scope()
         if self.classname:
             self.generator.exit_context()
         self.generator.exit_context()
-        
+
     def render_return_block(self, block):
         return_var = block.inputargs[0]
         if return_var.concretetype is Void:
     def set_label(self, label):
         return self.generator.set_label(label)
 
+    def declare_locals(self):
+        for TYPE, name in set(self.locals):
+            TYPE.load_default(self.generator)
+            self.generator.store_var(name)
+
     def _trace_enabled(self):
         return True
 
     def _render_op(self, op):
         print "Rendering op:", op
         super(Function, self)._render_op(op)
-    
-    def _setup_link(self, link):
-        target = link.target
-        linkvars = []
-        for to_load, to_store in zip(link.args, target.inputargs):
-            if isinstance(to_load, flowmodel.Variable) and to_load.name == to_store.name:
-                continue
-            if to_load.concretetype is ootype.Void:
-                continue
-            linkvars.append((to_load, to_store))
-        
-        # after SSI_to_SSA it can happen to have to_load = [a, b] and
-        # to_store = [b, c].  If we store each variable sequentially,
-        # 'b' would be overwritten before being read.  To solve, we
-        # first load all the values on the stack, then store in the
-        # appropriate places.
 
-        if self._trace_enabled():
-            self._trace('link', writeline=True)
-            for to_load, to_store in linkvars:
-                self._trace_value('%s <-- %s' % (to_store, to_load), to_load)
-            self._trace('', writeline=True)
-        
-        for to_load, to_store in linkvars:
-            self.generator.load(to_load)
-            self.generator.store(to_store)
+    ## def _setup_link(self, link):
+    ##     target = link.target
+    ##     linkvars = []
+    ##     for to_load, to_store in zip(link.args, target.inputargs):
+    ##         if isinstance(to_load, flowmodel.Variable) and to_load.name == to_store.name:
+    ##             continue
+    ##         if to_load.concretetype is ootype.Void:
+    ##             continue
+    ##         linkvars.append((to_load, to_store))
 
-    
+    ##     # after SSI_to_SSA it can happen to have to_load = [a, b] and
+    ##     # to_store = [b, c].  If we store each variable sequentially,
+    ##     # 'b' would be overwritten before being read.  To solve, we
+    ##     # first load all the values on the stack, then store in the
+    ##     # appropriate places.
+
+    ##     if self._trace_enabled():
+    ##         self._trace('link', writeline=True)
+    ##         for to_load, to_store in linkvars:
+    ##             self._trace_value('%s <-- %s' % (to_store, to_load), to_load)
+    ##         self._trace('', writeline=True)
+
+    ##     for to_load, to_store in linkvars:
+    ##         self.generator.load(to_load)
+
+    ##     for to_load, to_store in reversed(linkvars):
+    ##         self.generator.store(to_store)
+
     def begin_try(self, cond):
         if cond:
             self.ilasm.begin_try()
-    
+
     def end_try(self, target_label, cond):
         if cond:
             self.ilasm.end_try()

File pypy/translator/avm2/genavm.py

View file
  • Ignore whitespace
-
 import py
 from mech.fusion.avm2.abc_ import AbcFile
 
 from pypy.translator.avm2.types_ import Avm2TypeSystem
 
 class GenAVM2(GenOO):
-    
+
     opcodes    = opcodes
     Function   = TamarinFunction
     Database   = LowLevelDatabase
     RecordConst   = Avm2RecordConst
     ListConst     = Avm2ArrayListConst
     ArrayConst    = Avm2ArrayListConst
-    
+
     def __init__(self, tmpdir, translator, entrypoint, config=None, exctrans=False):
         GenOO.__init__(self, tmpdir, translator, entrypoint, config, exctrans)
         self.const_stat = str(tmpdir.join('const_stat'))
         clsdef = bk.getuniqueclassdef(Exception)
         ll_Exception = rtyper.exceptiondata.get_standard_ll_exc_instance(rtyper, clsdef)
         self.EXCEPTION = ll_Exception._inst._TYPE
-    
+
     def create_assembler(self):
         self.abc = AbcFile()
-        return PyPyAvm2ilasm(self.db, self.abc)
+        return PyPyAvm2ilasm(self.db, self.abc, True)
 
     def generate_source(self):
         if self.ilasm is None:
 
     def serialize_abc(self):
         return self.abc.serialize()
-
-    # Don't do treebuilding stuff
-    # def stack_optimization(self):
-    #     pass

File pypy/translator/avm2/library.py

View file
  • Ignore whitespace
+
+from pypy.rpython.ootypesystem import ootype
+
+from mech.fusion.avm2.constants import QName, packagedQName, TYPE_MULTINAME_TypeName
+from mech.fusion.avm2.query import ClassDesc
+from mech.fusion.avm2.library import Library
+from mech.fusion.avm2.playerglobal.flash.utils import Vector
+
+from pypy.translator.avm2.types_ import vec_qname
+
+## Monkey Patching!
+
+ClassDesc._nativeclass = None
+
+class PyPyLibrary(Library):
+    def resolve_class(self, TYPE):
+        if self.has_type(TYPE):
+            return self.get_type(TYPE)
+        if playerglobal_lib.has_type(TYPE):
+            return self.get_type(TYPE)
+        if TYPE.KIND == TYPE_MULTINAME_TypeName and TYPE.name == vec_qname:
+            assert len(TYPE.types) == 1
+            return Vector[TYPE.types[0]]
+        if getattr(TYPE, "multiname", None):
+            return TYPE.multiname()
+
+    def convert_classdesc(self, classdesc):
+        resolve = self.resolve_class
+        from pypy.translator.avm2.runtime import NativeClass, NativeInstance
+        from pypy.translator.avm2.runtime import _overloaded_static_meth, _static_meth
+
+        if classdesc._nativeclass is not None:
+            return classdesc._nativeclass
+
+        TYPE = NativeInstance(classdesc.Package, classdesc.ShortName, None, {}, {})
+        Class = NativeClass(TYPE, {}, {})
+        classdesc._nativeclass = Class
+        if classdesc.FullName == QName('Object'):
+            TYPE._set_superclass(ootype.ROOT)
+        else:
+            BASETYPE = resolve(classdesc.BaseType)
+            TYPE._set_superclass(BASETYPE)
+
+        TYPE._isArray = classdesc.IsArray
+        if classdesc.IsArray:
+            TYPE._ELEMENT = resolve(classdesc.ElementType)
+
+        # add both static and instance methods, and static fields
+        static_meths = self.group_methods(classdesc.StaticMethods,
+            _overloaded_static_meth, _static_meth, ootype.StaticMethod)
+        meths = self.group_methods(classdesc.Methods, ootype.overload,
+                              ootype.meth, ootype.Meth)
+        Class._add_methods(static_meths)
+        Class._add_static_fields(dict((name,
+            resolve(t)) for name, t in classdesc.StaticFields]))
+        Class._add_static_fields(dict((name,
+            resolve(t)) for name, t, g, s in classdesc.StaticProperties))
+        TYPE._add_methods(meths)
+        TYPE._add_fields(dict((name, resolve(t)) for name, t in classdesc.Fields))
+        TYPE._add_fields(dict((name, resolve(t)) for name, t, g, s in classdesc.Properties))
+        return Class
+
+    def group_methods(self, methods, overload, meth, Meth):
+        from pypy.translator.avm2.runtime import OverloadingResolver
+        groups = {}
+        for name, args, result, AS3 in methods:
+            groups[name] = args, result, AS3
+
+        res = {}
+        attrs = dict(resolver=OverloadingResolver)
+        for name, methlist in groups.iteritems():
+            meths = [meth(Meth([self.resolve_class(arg) for arg in args],
+                          self.resolve_class(result))) for (args, result) in methlist]
+            res[name] = overload(*meths, **attrs)
+        return res
+
+from mech.fusion.avm2.library import get_playerglobal
+
+playerglobal_lib = get_playerglobal(Library=PyPyLibrary)
+playerglobal_lib.install_global(__name__.rpartition(".")[0]+".playerglobal")

File pypy/translator/avm2/metavm.py

View file
  • Ignore whitespace
 from pypy.rpython.ootypesystem import ootype
-from pypy.translator.oosupport.metavm import MicroInstruction, \
-     PushAllArgs, StoreResult, GetField, SetField, DownCast
-from pypy.translator.oosupport.metavm import _Call as _OOCall
+from pypy.translator.oosupport.metavm import MicroInstruction, PushAllArgs, \
+     StoreResult, GetField, SetField, DownCast, _Call as _OOCall, \
+     get_primitive_name
 from pypy.translator.avm2.runtime import _static_meth, NativeInstance
 from pypy.translator.avm2 import types_ as types
 from mech.fusion.avm2 import constants
     return ret_type, arg_types
 
 class _Call(_OOCall):
-    
     def render(self, generator, op):
         callee = op.args[0].value
         if isinstance(callee, _static_meth):
             self._render_static_function(generator, callee, op.args)
         else:
-            _OOCall.render(self, generator, op)
+            generator.call_graph(op.args[0].value.graph, op.args[1:])
 
     def _render_static_function(self, generator, funcdesc, args):
         import pdb; pdb.set_trace()
 
 
 class _CallMethod(_Call):
+    DISPATCH = {
+        ootype.Array : {
+            "ll_setitem_fast": lambda gen: gen.array_setitem(),
+            "ll_getitem_fast": lambda gen: gen.array_getitem(),
+            "ll_length": lambda gen: gen.get_field("length", types.types.int),
+        },
+        ootype.AbstractString : {
+            "ll_append": lambda gen: gen.emit('add'),
+            "ll_stritem_nonneg": lambda gen: gen.call_method("charAt", 1, types.types.string),
+            "ll_strlen": lambda gen: gen.get_field("length", types.types.int),
+        },
+    }
     def render(self, generator, op):
         method = op.args[0]
         self._render_method(generator, method.value, op.args[1:])
         else:
             generator.load(*args)
 
-        if isinstance(this.concretetype, ootype.Array) and this.concretetype.ITEM is not ootype.Void:
-            if method_name == "ll_setitem_fast":
-                generator.array_setitem()
-            elif method_name == "ll_getitem_fast":
-                generator.array_getitem()
-            elif method_name == "ll_length":
-                generator.array_length()
-            else:
-                assert False
-        elif isinstance(this.concretetype, ootype.AbstractString):
-            if method_name == "ll_append":
-                generator.emit('add')
-            elif method_name == "ll_stritem_nonneg":
-                generator.call_method("charAt", 1)
-            elif method_name == "ll_strlen":
-                generator.get_field("length")
+        for TYPE, D in self.DISPATCH.iteritems():
+            if isinstance(this.concretetype, TYPE):
+                D[method_name](generator)
+                break
         else:
             generator.call_method(method_name, len(args)-1)
 

File pypy/translator/avm2/runtime.py

View file
  • Ignore whitespace
 from pypy.rpython.ootypesystem.rootype import OOInstanceRepr
 from pypy.rpython.ootypesystem import ootype
 from pypy.rpython.ootypesystem.ootype import Meth, StaticMethod
-# from pypy.translator.avm2 import constants
 
 ## Annotation model
 
         meth = self._static_methods[meth_name]
         return meth._resolver.annotate(args_s)
 
-    # def _load_class(self):
-    #     names = self._INSTANCE._namespace.split('.')
-    #     names.append(self._INSTANCE._classname)
-    #     obj = PythonNet
-    #     for name in names:
-    #         obj = getattr(obj, name)
-    #     self._PythonNet_class = obj
-
-    # def __getattr__(self, attr):
-    #     if attr in self._static_methods or attr in self._static_fields:
-    #         self._load_class()
-    #         return getattr(self._PythonNet_class, attr)
-    #     else:
-    #         raise AttributeError, attr
-
-    # def __call__(self, *args):
-    #     self._load_class()
-    #     return self._PythonNet_class(*args)
-
 
 class Entry(ExtRegistryEntry):
     _type_ = NativeClass
         return SomeOOInstance(self.instance._INSTANCE)
 
 
-# BOXABLE_TYPES = [ootype.Signed, ootype.Unsigned, ootype.SignedLongLong,
-#                  ootype.UnsignedLongLong, ootype.Bool, ootype.Float,
-#                  ootype.Char, ootype.String]
-
-# class BoxedSpace:
-#     objects = {}
-#     index = 0
-#     def put(cls, obj):
-#         index = cls.index
-#         cls.objects[index] = obj
-#         cls.index += 1
-#         return index
-#     put = classmethod(put)
-
-#     def get(cls, index):
-#         return cls.objects[index]
-#     get = classmethod(get)
-
-# def box(x):
-#     t = type(x)
-#     if t is int:
-#         return CLR.System.Int32(x)
-#     elif t is r_uint:
-#         return CLR.System.UInt32(x)
-#     elif t is r_longlong:
-#         return CLR.System.Int64(x)
-#     elif t is r_ulonglong:
-#         return CLR.System.UInt64(x)
-#     elif t is bool:
-#         return CLR.System.Boolean(x)
-#     elif t is float:
-#         return CLR.System.Double(x)
-#     elif t is str or t is unicode:
-#         if len(x) == 1:
-#             return CLR.System.Char(x)
-#         else:
-#             return CLR.System.String(x)
-#     elif isinstance(x, ootype._class):
-#         if hasattr(x, '_FUNC'):
-#             TYPE = x._FUNC
-#             assert isinstance(TYPE, ootype.StaticMethod)
-#             return typeof(TYPE)
-#         else:
-#             name = '%s.%s' % (x._INSTANCE._namespace, x._INSTANCE._classname)
-#             t = CLR.System.Type.GetType(name)
-#             assert t is not None
-#             return t
-#     elif isinstance(x, PythonNet.System.Object):
-#         return x
-#     elif x is None:
-#         return None
-#     else:
-#         # cast RPython instances to System.Object is trivial when
-#         # translated but not when interpreting, because Python for
-#         # .NET doesn't support passing aribrary Python objects to
-#         # .NET. To solve, we store them in the BoxedSpace, then we
-#         # return an opaque objects, which will be used by unbox to
-#         # retrieve the original RPython instance.
-#         index = BoxedSpace.put(x)
-#         res = PythonNet.pypy.test.ObjectWrapper(index)
-#         return res
-
-# def unbox(x, TYPE):
-#     if isinstance(x, PythonNet.pypy.test.ObjectWrapper):
-#         x = BoxedSpace.get(x.index)