Exemple #1
0
 def insertToString(self, cls, basecls, visitor):
     # visitor.logger.debug('insertToString', cls, basecls)
     name = 'toString'
     if name not in cls.symbols:
         # visitor.logger.debug('insertToString do', cls, basecls)
         clsname = ast.Call(ast.Identifier('getClassName'), [])
         thisptr = ast.Call(ast.Identifier('formatId'), [])
         expr = None
         if 'name' in cls.symbols:
             # visitor.logger.debug('insertToString with name', cls, basecls, clsname, thisptr)
             expr = ast.BinaryOp(
                 '%', ast.makeLiteral('%s(name=%s,id=%s)'),
                 ast.TupleLiteral(
                     [clsname, ast.Identifier('name'), thisptr]))
         else:
             # visitor.logger.debug('insertToString without name', cls, basecls, clsname, thisptr)
             expr = ast.BinaryOp('%', ast.makeLiteral('%s(id=%s)'),
                                 ast.TupleLiteral([clsname, thisptr]))
         func = ast.FuncDef([], name,
                            ast.FuncSpec([],
                                         ast.makePrimitiveType('string')),
                            ast.StatementBody([ast.Return(expr)]))
         # visitor.logger.debug('insertFunc ok', name, cls, basecls, cls.primaryVars, func)
         cls.definitions.append(func)
         func.setOwner(cls)
         visitor.visitNewItem(func)
Exemple #2
0
 def generateSimpleFieldCall(self, cls, basecls, basefunc, field,
                             invokeFuncName):
     callinfo = ast.Call(
         ast.AttrRef(ast.Identifier(field.name), invokeFuncName),
         [ast.Identifier(param.name) for param in basefunc.spec.params])
     # teststmts = [ast.CallStatement(ast.Call(ast.Identifier('println'), [ast.makeLiteral('GenerateTreeFunc check ' + basefunc.name + ' ' + field.name),
     #             ast.Identifier(field.name),
     #             ast.Call(ast.Identifier('toString'), [])]))]
     teststmts = []
     isStatement = basefunc.spec.returnType is None or (
         isinstance(basefunc.spec.returnType, ast.UserType)
         and basefunc.spec.returnType.fullpath == 'void')
     if isStatement:
         body = ast.StatementBody([
             # ast.Call(ast.Identifier('println'), [ast.makeLiteral('GenerateTreeFunc ' + basefunc.name + ' ' + field.name),
             #     ast.Call(ast.AttrRef(ast.Identifier(field.name), 'toString'), []),
             #     ast.Call(ast.Identifier('toString'), [])]),
             callinfo
         ])
         branch = ast.IfBranch(
             ast.BinaryOp('!=', ast.Identifier(field.name), ast.Nil()),
             body)
         return ast.StatementBody(teststmts +
                                  [ast.IfStatement([branch], None)])
     return ast.IfElseExpr(
         ast.BinaryOp('!=', ast.Identifier(field.name), ast.Nil()),
         callinfo, ast.Nil())
Exemple #3
0
 def led(self, left, token):
     # Cleaner code here
     if isinstance(
             token,
         (tokens.PLUS, tokens.MINUS, tokens.ASTERISK, tokens.SLASH)):
         return ast.BinaryOp(token, left, self.expr(self.bp(token)))
     if isinstance(token, (tokens.EQ, tokens.NEQ, tokens.LT, tokens.GT,
                           tokens.LTE, tokens.GTE)):
         return ast.BinaryOp(token, left, self.expr(self.bp(token)))
     else:
         raise ParserError(f"No infix parse function found for {token}")
Exemple #4
0
 def vUnaryOp(self, node):
     if node.oper == '++':
         if node.right.resolveType().type == 'int':
             id = 'Increment'
             if node.pre:
                 id = 'pre' + id
             else:
                 id = 'post' + id
             if node.isNodeStatement():
                 id = 'p' + id
             func = ast.FunctionCall(id,
                                     ast.ActualParametersList(node.right))
             func.symtab = node.symtab
             if node.isNodeStatement():
                 func.isStatement = True
             self.visit(func)
         else:
             binaryOp = ast.BinaryOp(node.right, '+', ast.IntLiteral(1))
             binaryOp.symtab = node.symtab
             assignment = ast.AssignmentStatement(node.right, '=', binaryOp)
             assignment.symtab = node.symtab
             self.visit(assignment)
     elif node.oper == '--':
         if node.right.resolveType().isInt():
             id = 'Decrement'
             if node.pre:
                 id = 'pre' + id
             else:
                 id = 'post' + id
             if node.isNodeStatement():
                 id = 'p' + id
             func = ast.FunctionCall(id,
                                     ast.ActualParametersList(node.right))
             func.symtab = node.symtab
             if node.isNodeStatement():
                 func.isStatement = True
             self.visit(func)
         else:
             binaryOp = ast.BinaryOp(node.right, '-', ast.IntLiteral(1))
             binaryOp.symtab = node.symtab
             assignment = ast.AssignmentStatement(node.right, '=', binaryOp)
             assignment.symtab = node.symtab
             self.visit(assignment)
         #binaryOp = ast.BinaryOp(node.right, '-', ast.IntLiteral(1))
         #binaryOp.symtab = node.symtab
         #assignment = ast.AssignmentStatement(node.right, '=', binaryOp)
         #assignment.symtab = node.symtab
         #self.visit(assignment)
     else:
         self.w(self.t[node.oper])
         self.visit(node.right)
Exemple #5
0
 def resolveName_StringEvaluation(self, se):
     # self.logger.debug('resolveName_StringEvaluation convert', se.literal)
     text, exprs = convert_string_literal(se.literal.value)
     if len(exprs) == 0:
         return
     # self.logger.debug('resolveName_StringEvaluation convert', text, exprs)
     formatstr = ast.StringLiteral(text)
     if len(exprs) == 1:
         se.evaluation = ast.BinaryOp("%", formatstr, exprs[0])
     else:
         se.evaluation = ast.BinaryOp("%", formatstr, TupleLiteral(exprs))
     se.evaluation.setOwner(se)
     self.visitNewItem(se.evaluation)
     se.evaluation.visit(self)
Exemple #6
0
 def doCondition(self, node, cond):
     if not node.cond.resolveType().isBool():
         newcond = ast.BinaryOp(node.cond, '!=', ast.IntLiteral('0'))
         newcond.symtab = node.symtab
         self.visit(newcond)
     else:
         self.visit(node.cond)
Exemple #7
0
 def p_binary_expression(self, p):
     """ binary_expression   : cast_expression
                             | binary_expression TIMES binary_expression
                             | binary_expression DIVIDE binary_expression
                             | binary_expression MOD binary_expression
                             | binary_expression PLUS binary_expression
                             | binary_expression MINUS binary_expression
                             | binary_expression RSHIFT binary_expression
                             | binary_expression LSHIFT binary_expression
                             | binary_expression LT binary_expression
                             | binary_expression LE binary_expression
                             | binary_expression GE binary_expression
                             | binary_expression GT binary_expression
                             | binary_expression EQ binary_expression
                             | binary_expression NE binary_expression
                             | binary_expression AND binary_expression
                             | binary_expression OR binary_expression
                             | binary_expression XOR binary_expression
                             | binary_expression LAND binary_expression
                             | binary_expression LOR binary_expression
     """
     if len(p) == 2:
         p[0] = p[1]
     else:
         p[0] = ast.BinaryOp(p[2], p[1], p[3])
Exemple #8
0
 def vAssignmentStatement(self, node):
     if isinstance(
             node.expr,
             ast.Constructor) and node.expr.type.resolveType().isVector():
         self.w('New')
         self.w('(')
         self.visit(node.lval)
         cons = node.expr
         while isinstance(cons, ast.Constructor):
             self.w(',')
             #print cons.params
             self.visit(cons.params.children[0])
             if len(cons.params.children) == 1:
                 cons = None
                 break
             else:
                 cons = cons.params.children[1]
         if cons != None:
             print '****************Need to initialize******************'
         self.w(')')
     elif isinstance(node.expr, ast.AssignmentStatement):
         self.visit(node.expr)
         self.p(';')
         tmp = node.expr
         if isinstance(node.expr.lval, str):
             node.expr = ast.Identifier(node.expr.lval)
         else:
             node.expr = node.expr.lval
         node.expr.symtab = node.symtab
         self.visit(node)
         node.expr = tmp
     else:
         ident = node.lval
         ident.symtab = node.symtab
         oldexpr = node.expr
         if node.operator != '=':
             node.expr = ast.BinaryOp(
                 ident, self.assignmentOperators[node.operator],
                 ast.Parenthesis(node.expr))
             node.expr.symtab = node.symtab
         tpe_ident = ident.resolveType().type
         tpe_expr = node.expr.resolveType().type
         #if isinstance(ident.resolveType(), ast.StructType):
         #print ident.resolveType().id
         #print tpe_ident
         #if isinstance(node.expr.resolveType().resolveType(), ast.StructType):
         #print node.expr.resolveType().resolveType().id
         #print tpe_expr
         if tpe_ident != tpe_expr and not (
             (tpe_ident == 'float' and tpe_expr == 'double') or
             (tpe_ident == 'double' and tpe_expr == 'float')):
             node.expr = ast.CastExpression(ast.Type(tpe_ident), node.expr)
             node.expr.symtab = node.symtab
         self.visit(node.lval)
         self.w(':=')
         self.visit(node.expr)
         node.expr = oldexpr
Exemple #9
0
    def visitUnaryOp(self, node):
        # logical operators don't exist in LLVM
        if node.op == '!':
            eq = ast.Operator.get('==')
            false = self.makebool(False)
            return self.visit(ast.BinaryOp(node.value, eq, false).at(node))

        if node.op == '-':
            return self.builder.neg(self.visit(node.value))

        assert node.op == '~'
        return self.builder.not_(self.visit(node.value))
def p_binop(p):
    '''expr : expr PLUS expr
            | expr MINUS expr
            | expr TIMES expr
            | expr DIVIDE expr
            | expr MODULO expr
            | expr EQ expr
            | expr NE expr
            | expr LT expr
            | expr GT expr
            | expr LE expr
            | expr GE expr
            | expr AND expr
            | expr OR expr'''
    p[0] = ast.BinaryOp(p[1], ast.Operator.get(p[2]), p[3]).at(loc(p))
Exemple #11
0
 def generateInitializeOwnerCall(self, cls, basecls, basefunc, field):
     # print('generateInitializeOwnerCall', basefunc.name, cls, field, basefunc)
     # msgstmt = ast.Call(ast.Identifier('println'), [ast.makeLiteral('generate initializeOwner start ' + field.name),
     #         ast.Identifier(field.name),
     #         ast.Call(ast.Identifier('toString'), [])])
     body = ast.StatementBody([
         # ast.Call(ast.Identifier('println'), [ast.makeLiteral('generate initializeOwner ' + field.name),
         #     ast.Identifier(field.name),
         #     ast.Call(ast.Identifier('toString'), [])]),
         ast.Call(ast.AttrRef(ast.Identifier(field.name), 'setOwner'),
                  [ast.This()]),
         self.generateSimpleFieldCall(cls, basecls, basefunc, field,
                                      'initializeOwner')
     ])
     branch = ast.IfBranch(
         ast.BinaryOp('!=', ast.Identifier(field.name), ast.Nil()), body)
     # return ast.StatementBody([msgstmt, ast.IfStatement([branch], None)])
     return ast.IfStatement([branch], None)
Exemple #12
0
 def p_binary_expression(self, p):
     """ binary_expression   : cast_expression
                             | binary_expression TIMES binary_expression
                             | binary_expression DIVIDE binary_expression
                             | binary_expression MOD binary_expression
                             | binary_expression PLUS binary_expression
                             | binary_expression MINUS binary_expression
                             | binary_expression LT binary_expression
                             | binary_expression LTE binary_expression
                             | binary_expression GT binary_expression
                             | binary_expression GTE binary_expression
                             | binary_expression EQUALS binary_expression
                             | binary_expression NE binary_expression
                             | binary_expression AND binary_expression
                             | binary_expression OR binary_expression
     """
     p[0] = p[1] if len(p) == 2 else ast.BinaryOp(p[2], p[1], p[3],
                                                  p[1].coord)
Exemple #13
0
 def p_expr(self, p):
     """
     expr :  cast_expression
             | expr PLUS expr
             | expr MINUS expr
             | expr TIMES expr
             | expr DIVIDE expr
             | expr EQUALS expr
             | expr MOD expr
             | expr GT expr
             | expr GET expr
             | expr LT expr
             | expr LET expr
             | expr DIFF expr
             | expr AND expr
             | expr OR expr
     """
     p[0] = (
         (p[1]) if len(p) == 2 else ast.BinaryOp(p[2], p[1], p[3], coord=p[1].coord)
     )
Exemple #14
0
 def vCastExpression(self, node):
     tpe = node.expression.resolveType()
     if tpe.isInt() and node.type.isFloatingPoint():
         self.w('castint2%s(' % node.type.type)
         self.visit(node.expression)
         self.w(')')
     elif node.type.resolveType().isInt() and tpe.isFloatingPoint():
         self.w('cast%s2int(' % tpe.type)
         self.visit(node.expression)
         self.w(')')
     elif node.type.resolveType().isString():
         self.visit(node.expression)
     elif node.type.resolveType().isBool() and tpe.isInt():
         op = ast.BinaryOp(node.expression, '!=', ast.IntLiteral('0'))
         op.symtab = node.symtab
         op.right.symtab = node.symtab
         self.visit(op)
     else:
         self.visit(node.type.resolveType())
         self.w('(')
         self.visit(node.expression)
         self.w(')')
Exemple #15
0
def get_random_arith_op():
    rand_int = get_rand_int(1, 5)
    return ast.BinaryOp(rand_int)
Exemple #16
0
def p_lor_expression_02(t):
    '''
		lor_expression : lor_expression LOR land_expression
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #17
0
def p_or_expression_02(t):
    '''
		or_expression : or_expression OR xor_expression
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #18
0
def p_xor_expression_02(t):
    '''
		xor_expression : xor_expression XOR and_expression
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #19
0
def p_and_expression_02(t):
    '''
		and_expression : and_expression AND equality_expression
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #20
0
def p_equality_expression_02(t):
    '''
		equality_expression : equality_expression equality_operator relational_expression
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #21
0
def p_relational_expression_02(t):
    '''
		relational_expression : relational_expression relational_operator additive_expression
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #22
0
def p_additive_expression_02(t):
    '''
		additive_expression : additive_expression additive_operator multiplicative_expression	
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #23
0
def p_multiplicative_expression_02(t):
    '''
		multiplicative_expression : multiplicative_expression multiplicative_operator unary_expression
	'''
    t[0] = ast.BinaryOp(t[1], t[2], t[3])
Exemple #24
0
def expression_binop(s):
    return ast.BinaryOp(s[1].getstr(), s[0], s[2])