Changeset 2383


Ignore:
Timestamp:
Sep 20, 2012, 1:15:37 PM (7 years ago)
Author:
ksherdy
Message:

Added final Python AST node types. Disallow the translation of non-supported operators, e.g. binary +, -.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • proto/Compiler/py2pablo.py

    r2382 r2383  
    66#
    77import unparse, ast, sys
     8
     9def readfile(filename):
     10    f = open(filename, 'r')
     11    contents = f.read()
     12    f.close()
     13    return contents
     14
     15def writefile(filename, code):
     16    f=open(filename, 'w')
     17    f.write(code)
     18    f.close()
    819
    920class ScopeStack():
     
    134145        self.write(") ")
    135146        self.do_block(t.body)
    136 ###        # collapse nested ifs into equivalent elifs.
    137 ###        while (t.orelse and len(t.orelse) == 1 and
    138 ###               isinstance(t.orelse[0], ast.If)):
    139 ###            t = t.orelse[0]
    140 ###            self.fill("else if (")
    141 ###            self.dispatch(t.test)
    142 ###            self.write(") ")
    143 ###            self.do_block(t.body)
    144 ###        # final else
     147#       
     148#   Support the translation of only 'if else'.
     149#       
     150#        # collapse nested ifs into equivalent elifs.
     151#        while (t.orelse and len(t.orelse) == 1 and
     152#               isinstance(t.orelse[0], ast.If)):
     153#            t = t.orelse[0]
     154#            self.fill("else if (")
     155#            self.dispatch(t.test)
     156#            self.write(") ")
     157#            self.do_block(t.body)
     158#        # final else
    145159        if t.orelse:
    146160            self.fill("else ")
     
    191205        self.write(";")
    192206
    193 #
    194 #    unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
    195 #    def _UnaryOp(self, t):
    196 #        pass
    197 #
    198 #    binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",
    199 #                    "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
    200 #                    "FloorDiv":"//", "Pow": "**"}
    201 #    def _BinOp(self, t):
    202 #        pass
    203 #
    204 #    cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
    205 #                        "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}
    206 #    def _Compare(self, t):
    207 #        pass
    208 #
    209 #    def _BoolOp(self, t):
    210 #        pass
    211 #
    212 #    def _Attribute(self,t):
    213 #        pass
    214 #
    215 #    def _Call(self, t):
    216 #        pass
    217 #
     207    unop = {"Invert":"~", "USub":"-"}
     208    def Cgen_UnaryOp(self, t):
     209        self.write("(")
     210        self.write(self.unop[t.op.__class__.__name__])
     211        self.write(" ")
     212        # If we're applying unary minus to a number, parenthesize the number.
     213        # This is necessary: -2147483648 is different from -(2147483648) on
     214        # a 32-bit machine (the first is an int, the second a long), and
     215        # -7j is different from -(7j).  (The first has real part 0.0, the second
     216        # has real part -0.0.)
     217        if isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num):
     218            self.write("(")
     219            self.dispatch(t.operand)
     220            self.write(")")
     221        else:
     222            self.dispatch(t.operand)
     223        self.write(")")
     224
     225    binop = { "BitOr":"|", "BitXor":"^", "BitAnd":"&"}
     226    def Cgen_BinOp(self, t):
     227        self.write("(")
     228        self.dispatch(t.left)
     229        self.write(" " + self.binop[t.op.__class__.__name__] + " ")
     230        self.dispatch(t.right)
     231        self.write(")")
     232
     233    def Cgen_Compare(self, t):
     234        self.exitNodeNotSupported(t)
     235       
     236    def Cgen_BoolOp(self, t):
     237        self.exitNodeNotSupported(t)
     238
     239    def _Attribute(self,t):
     240        self.dispatch(t.value)
     241        # Special case: 3.__abs__() is a syntax error, so if t.value
     242        # is an integer literal then we need to either parenthesize
     243        # it or add an extra space to get 3 .__abs__().
     244        if isinstance(t.value, ast.Num) and isinstance(t.value.n, int):
     245            self.write(" ")
     246        self.write(".")
     247        self.write(t.attr)
     248
     249    def _Call(self, t):
     250        self.dispatch(t.func)
     251        self.write("(")
     252        comma = False
     253        for e in t.args:
     254            if comma: self.write(", ")
     255            else: comma = True
     256            self.dispatch(e)
     257        self.write(")")
     258
    218259    def _arguments(self, t):
    219260        first = True
     
    230271                self.dispatch(d)
    231272
    232         # varargs
    233         if t.vararg:
    234             if first:first = False
    235             else: self.write(", ")
    236             self.write("*")
    237             self.write(t.vararg)
    238 
    239         # kwargs
    240         if t.kwarg:
    241             if first:first = False
    242             else: self.write(", ")
    243             self.write("**"+t.kwarg)
    244 #
    245 #    def _Str(self, tree):
    246 #        pass
    247 #   
    248     def Cgen_Name(self, t):
     273    def _Str(self, tree):
     274        self.write('"%s"' % tree.s)
     275 
     276    def _Name(self, t):
    249277        self.write(t.id)
    250 #   
    251 #    def _Num(self, t):
    252 #        pass
     278       
     279    def  _Num(self, t):
     280        repr_n = repr(t.n)
     281        # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2.
     282        if repr_n.startswith("-"):
     283            self.write("(" + repr_n + ")")
     284        else: self.write(repr_n)
    253285
    254286    def _Import(self, t):
     
    323355        self.exitNodeNotSupported(t)
    324356
    325 def readfile(filename):
    326     f = open(filename, 'r')
    327     contents = f.read()
    328     f.close()
    329     return contents
    330 
    331 def writefile(filename, code):
    332     f=open(filename, 'w')
    333     f.write(code)
    334     f.close()
    335 
    336 # Helpers
    337 class Variables(ast.NodeVisitor):
    338     def __init__(self,node):
    339         self.params = []
    340         self.stores = []
    341         self.generic_visit(node)
    342     def visit_Name(self, nm):
    343         if isinstance(nm.ctx, ast.Param):
    344             self.params.append(nm.id)
    345         if isinstance(nm.ctx, ast.Store):
    346             if nm.id not in self.stores: self.stores.append(nm.id)
    347     def getLocals(self):
    348         return [v for v in self.stores if not v in self.params]
    349     def getParams(self):
    350         return [v for v in self.params]
    351 
    352357import optparse
    353358
     
    386391        Py2Pablo(s)
    387392   
    388    
    389 
    390    
    391    
Note: See TracChangeset for help on using the changeset viewer.