Esempio n. 1
0
def ParameterDeclaratorTest():
    k = VariableDeclaration(specifiers.chaR,
                            VariableDeclarator(Identifier('a', None, False)))
    l = VariableDeclaration(specifiers.chaR,
                            VariableDeclarator(Identifier('b', None, False)))
    r = ParameterDeclarator([k, l])
    return r
Esempio n. 2
0
def ArrayAccessTest():
    a = ArrayAccess(Identifier('k', None, False),
                    [Identifier(k, None, False) for k in ['a', 'b', 'c']])
    print(a)
    b = ArrayAccess(Identifier('k', None, False), Identifier('i', None, False))
    print(b)
    return b
Esempio n. 3
0
def AccessExpressionTest3():
    una_exp1 = UnaExp(unaryOperator.DEREFERENCE, Identifier('b', None, False))
    una_exp1.setParens(True)
    binary_exp1 = BinExp(Identifier('a', None, False), binaryOperator.ADD,
                         una_exp1)
    binary_exp1.setParens(True)
    return UnaExp(
        unaryOperator.DEREFERENCE,
        AccessExpression(binary_exp1, accessOperator.ARROW,
                         Identifier('c', None, False)).setParens(True))
Esempio n. 4
0
def ForLoopTest2(symtab):
    # i = 0
    init = AssignmentExpression(Identifier('i', None, False),
                                assignmentOperator.EQUAL, IntegerLiteral(0))
    # i++
    step = UnaryExpression(unaryOperator.POST_INCREMENT,
                           Identifier('i', None, False))
    # i < 100
    condition = ConditionalExpression(Identifier('i', None, False),
                                      conditionalOperator.COMPARE_LE,
                                      IntegerLiteral(100))
    # A body for the for loop
    body = CompoundStatement()
    # a variable declaration: inT y
    decl1 = DeclarationStatement(
        VariableDeclaration(
            specifiers.inT,
            VariableDeclarator(Identifier('y', None, False, None, False))))
    body.addStatement(decl1)
    # identifiers a, b
    id1 = Identifier('a', None, False)
    id2 = Identifier('y', None, False)
    as1 = ExpressionStatement(
        AssignmentExpression(id2, assignmentOperator.EQUAL,
                             Identifier('i', None, False)))
    as2 = ExpressionStatement(
        AssignmentExpression(copy.deepcopy(id1), assignmentOperator.EQUAL,
                             id2))
    body.addStatement(as1)
    body.addStatement(as2)
    forloop = ForLoop(init, condition, step, body)
    return forloop
Esempio n. 5
0
def CompoundStatementTest(parent):
    id1 = Identifier('a', parent, False)
    id2 = Identifier('b', parent, False)
    binexp1 = BinaryExpression(id1, binaryOperator.ADD, id2)
    binexp2 = BinaryExpression(id1, binaryOperator.ADD, id2)
    binexp3 = BinaryExpression(id1, binaryOperator.ADD, id2)
    decl1 = DeclarationStatement(
        VariableDeclaration(specifiers.int8,
                            VariableDeclarator(Identifier('y', parent,
                                                          False))))
    Y = decl1
    expstmt1 = ExpressionStatement(binexp1)
    expstmt2 = ExpressionStatement(binexp2)
    expstmt3 = ExpressionStatement(binexp3)
    compstmt = CompoundStatement()
    compstmt.addStatement(decl1)
    compstmt.addStatementAfter(decl1, expstmt1)
    print(compstmt)
    k = CompoundStatement()
    decl1 = DeclarationStatement(
        VariableDeclaration(
            specifiers.int8,
            VariableDeclarator(Identifier('x', compstmt, False))))
    k.addStatement(decl1)
    k.addStatement(expstmt2)
    compstmt.addStatement(k)
    l = CompoundStatement()
    decl1 = DeclarationStatement(
        VariableDeclaration(
            specifiers.int8,
            VariableDeclarator(Identifier('z', compstmt, False))))
    l.addStatement(decl1)
    l.addStatement(expstmt2)
    k.addStatement(l)
    compstmt.addStatement(expstmt3)
    expstmt1.detach()
    print(('next compstmt:\n', compstmt))
    print('symtabl:')
    print(('parent symtabl:', k.getParentTables()))
    print(('symbol look up:',
           k.findSymbol(Y.getDeclaration().getDeclaredSymbols()[0])))
    return compstmt
Esempio n. 6
0
def NestedDeclaratorTest():
    from hir.Identifier import Identifier
    from hir.PointerSpecifier import PointerSpecifier
    from hir.ArraySpecifier import ArraySpecifier
    from hir.VariableDeclarator import VariableDeclarator
    from hir.ParameterDeclarator import ParameterDeclaratorTest
    from hir.VariableDeclaration import VariableDeclaration
    from hir.DeclarationStatement import DeclarationStatement

    ns = VariableDeclarator(Identifier('a', None, False), None,
                            PointerSpecifier([CONST]))

    k = VariableDeclaration(DOUBLE,
                            VariableDeclarator(Identifier('xyz', None, False)))

    ns = NestedDeclarator(ns, None, None, [k])
    ns = VariableDeclarator(ns, ArraySpecifier([3]))
    ns = VariableDeclarator(ns, None, PointerSpecifier())
    ns = DeclarationStatement(VariableDeclaration(INT, ns))
    return ns
Esempio n. 7
0
def StructDeclarationTest():
    from hir.VariableDeclarator import VariableDeclarator
    from hir.VariableDeclaration import VariableDeclaration
    from hir.Keyword import specifiers

    k = VariableDeclaration(specifiers.int8,
                            VariableDeclarator(Identifier('y', None, False)))
    s = DeclarationStatement(k)
    id1 = Identifier('a', None, False)
    struct_dec = StructDeclaration(id1)
    struct_dec.add_field(s)
    k = VariableDeclaration(specifiers.int8,
                            VariableDeclarator(Identifier('x', None, False)))
    s = DeclarationStatement(k)
    struct_dec.add_field(s)

    print(struct_dec.getDeclaredSymbols())
    # id2 = Identifier('b', None, False)
    # struct_dec1 = StructDeclaration(id2)
    # struct_dec1.add_field(struct_dec)
    return struct_dec
Esempio n. 8
0
def IfStatementTest():
    import copy
    control = ConditionalExpression(Identifier('a', None, False),
                                    conditionalOperator.COMPARE_GT,
                                    IntegerLiteral(0))
    assignexp1 = AssignmentExpression(Identifier('a', None, False),
                                      assignmentOperator.ADD,
                                      Identifier('b', None, False))
    assignStmt1 = ExpressionStatement(assignexp1)
    decl1 = DeclarationStatement(
        VariableDeclaration(specifiers.inT,
                            VariableDeclarator(Identifier('y', None, False))))
    body = CompoundStatement()
    body.addStatement(decl1)
    copy_ifbody = copy.deepcopy(body)
    body.addStatement(assignStmt1)
    assignStmt2 = copy.deepcopy(assignStmt1)
    copy_ifbody.addStatement(assignStmt2)
    ifconstruct = IfStatement(control, body)
    control = ConditionalExpression(Identifier('a', None, False),
                                    conditionalOperator.COMPARE_LT,
                                    IntegerLiteral(0))
    ifconstruct = IfStatement(control, copy_ifbody, ifconstruct)
    return ifconstruct
Esempio n. 9
0
def ForLoopTest(parent=None):
    doTest = False
    if parent is not None:
        doTest = True


# i = 0
    init = AssignmentExpression(Identifier('i', parent, doTest),
                                assignmentOperator.EQUAL, IntegerLiteral(0))
    # i++
    step = UnaryExpression(unaryOperator.POST_INCREMENT,
                           Identifier('i', parent, False))
    # i < 100
    condition = ConditionalExpression(Identifier('i', parent, doTest),
                                      conditionalOperator.COMPARE_LE,
                                      IntegerLiteral(100))
    # A body for the for loop
    body = CompoundStatement()
    # a variable declaration: inT y
    decl1 = DeclarationStatement(
        VariableDeclaration(specifiers.inT,
                            VariableDeclarator(Identifier('y', body, doTest))))
    body.addStatement(decl1)
    # identifiers a, b
    id1 = Identifier('a', parent, doTest)
    id2 = Identifier('y', parent, doTest)
    # assignment expression, a += b, a = b, a %= b
    args1 = id1, assignmentOperator.ADD, id2
    args2 = copy.deepcopy(id1), assignmentOperator.EQUAL, copy.deepcopy(id2)
    args3 = copy.deepcopy(id1), assignmentOperator.MODULUS, copy.deepcopy(id2)
    args4 = copy.deepcopy(args3)
    assignments = [
        AssignmentExpression(*k) for k in [args1, args2, args3, args4]
    ]
    r = list(map(ExpressionStatement, assignments))
    # adding the statements to the body of the ForLoop
    list(map(body.addStatement, r))
    body.addStatement(IfStatementTest())
    forloop = ForLoop(init, condition, step, body)
    return forloop
Esempio n. 10
0
def UnaryExpressionTest():
    from hir.Operator import unaryOperator
    from hir.Identifier import Identifier
    a = Identifier('a', None)
    b = UnaryExpression(unaryOperator.POST_DECREMENT, a)
    return b
Esempio n. 11
0
    def __repr__(self):
        """Call to print the UnaryExpression Infix. 
() are added if specified.
Except for unaryOperator.POST_INCREMENT 
and unaryOperator.POST_DECREMENT, 
the rest of the unary operators 
precede the expression child."""
        if (self._op == unaryOperator.POST_INCREMENT) or (self._op == unaryOperator.POST_DECREMENT):
            retval = repr(self.getChild(0)) + repr(self._op)
        else:
            retval = repr(self._op) + repr(self.getChild(0))
        if self.getParens():
            retval = '(' + retval + ')'
        return retval
    __str__ = __repr__


def UnaryExpressionTest():
    from hir.Operator import unaryOperator
    from hir.Identifier import Identifier
    a = Identifier('a', None)
    b = UnaryExpression(unaryOperator.POST_DECREMENT, a)
    return b


if __name__ == '__main__':
    from hir.Identifier import Identifier
    exp = Identifier('a', None, False)
    unary_exp = UnaryExpression(unaryOperator.POST_DECREMENT, exp)
    print((repr(unary_exp)))
Esempio n. 12
0
from hir.Identifier import Identifier
from hir.BinaryExpression import BinaryExpression
from hir.Operator import conditionalOperator


class ConditionalExpression(BinaryExpression):
    """Conditional Expression works on any 
sequence with three args, true_expr, uop, false_expr. 
Except for a differentiating class type, and 
operator from hir.he conditional operators group, 
instances hold same data as BinaryExpression 
instances."""
    def __init__(self, *args):
        true_expr, uop, false_expr = args
        BinaryExpression.__init__(self, true_expr, uop, false_expr)


if __name__ == '__main__':
    exp1 = Identifier('a', None, False)
    exp2 = Identifier('b', None, False)
    cond_exp = ConditionalExpression(exp1, conditionalOperator.COMPARE_EQ,
                                     exp2)
    print((repr(cond_exp)))
Esempio n. 13
0
        print('New set state for ProcedureDeclarator')
        for k, v in list(statedict.items()):
            setattr(self, k, v)

    def get_symbol(self):
        return self.getChildren()[0].get_symbol()


if __name__ == '__main__':
    from hir.Identifier import Identifier
    from hir.Keyword import specifiers
    from hir.VariableDeclaration import VariableDeclaration
    from hir.VariableDeclarator import VariableDeclarator
    from hir.Declaration import Declaration
    from hir.DeclarationStatement import DeclarationStatement
    k = ProcedureDeclarator(Identifier(
        'proc_name', None, False), [specifiers.int8], [
            VariableDeclaration(
                specifiers.int8,
                VariableDeclarator(Identifier('x', None, False))),
            specifiers.inT
        ])
    print(k)
    l = Declaration()
    l.setChild(0, k)
    print(l)
    r = DeclarationStatement(l)
    print(r)
    from Traversable import get_symbols
    symlis = []
    get_symbols(r, symlis)
    print(symlis)
Esempio n. 14
0
        """Returns the results of self.items() call 
when called by pickle or copy"""
        return dict(self.items())

    def __setstate__(self, statedict):
        """Blindly sets state based on the items like statedict"""
        for k, v in list(statedict.items()):
            setattr(self, k, v)


if __name__ == '__main__':
    from hir.VariableDeclarator import VariableDeclarator
    from hir.Identifier import Identifier
    from hir.Keyword import specifiers
# Test1: (meant to work)
    decl = VariableDeclarator(Identifier('x', None, False))
    spec = specifiers.int16
    vardecl = VariableDeclaration(spec, decl)
    print(('test1: ' + repr(vardecl)))
# Test2: (meant to work):
#decl = decl
# spec = list of Specifier
    decl = VariableDeclarator(Identifier('y', None, False))
    spec = [specifiers.Global, specifiers.int16]
    vardecl = VariableDeclaration(spec, decl)
    print(('test 2: ' + repr(vardecl)))
# Test3: (meant to work)
# decl == list of declarator
# spec == Specifier
    spec = specifiers.int16
    decl = [VariableDeclarator(Identifier('z', None, False)),
Esempio n. 15
0
        return dict(self.items())

    def __setstate__(self, statedict):
        """Blindly calls setattr with entried from hir. 
__getstate__ like string->attr dict"""
        for k, v in list(statedict.items()):
            setattr(self, k, v)


def BinaryExpressionTest():
    return BinaryExpression(Identifier('a', None, False),
                            binaryOperator.SUBTRACT, Identifier('b', None, False))


if __name__ == '__main__':
    binary_exp1 = BinaryExpression(Identifier('a', None, False),
                                   binaryOperator.SUBTRACT, Identifier('b', None, False))
    binary_exp1.setParens(True)
    binary_exp2 = BinaryExpression(Identifier('a', None, False),
                                   binaryOperator.SUBTRACT, Identifier('b', None, False))
    binary_exp2.setParens(False)
    binary_exp3 = BinaryExpression(
        binary_exp1, binaryOperator.ADD, binary_exp2)
    print((repr(binary_exp3)))
    binary_exp3.setParens(True)
    print('for pickle r')
    r = pickle.loads(pickle.dumps(binary_exp3, 2))
    for k in bfsItr(r):
        print(('next: <%d,%s,%s>' % (id(k), str(type(k)), k)))
    print('for copy l of pickle r')
    import copy
Esempio n. 16
0
File: Case.py Progetto: qram9/c_ast
def CaseTest():
    c = Case(Identifier('a', None, False))
    return c
Esempio n. 17
0
        return 'Invalid Return Type:(%s) for ReturnStatement, expecting Expression' % (
            value)


class ReturnStatement(Statement):
    __slots__ = ()

    def __init__(self, retvalue=None):
        self.initialize()
        if retvalue:
            if isinstance(retvalue, Expression):
                self.setNumChildren(1)
                self.setChild(0, retvalue)
            else:
                raise InvalidReturnTypeError(str(type(retvalue)))

    def __repr__(self):
        if len(self.getChildren()) == 0:
            return 'return;'
        else:
            retval = 'return '
            retval += repr(self.getChild(0))
            retval += ';'
            return retval


if __name__ == '__main__':
    from hir.Identifier import Identifier
    print(ReturnStatement())
    print(ReturnStatement(Identifier('k', None, False)))
Esempio n. 18
0
def ExpressionStatementTest():
    return ExpressionStatement(
        AssignmentExpression(Identifier('a', None, False),
                             assignmentOperator.ADD, Identifier('b', None, False)))
Esempio n. 19
0
                for k, v in list(supitems.items()):
                    items[k] = v
        return dict(items)

    def __getstate__(self):
        """Returns a dict representing the contents of 
this ExpressionStatement object and its base classes 
instances' contents. Uses the items() function.
Contents added here is _expr"""
        return dict(self.items())

    def __setstate__(self, statedict):
        """Blindly calls setattr with entried from hir. 
__getstate__ like string->attr dict"""
        for k, v in list(statedict.items()):
            setattr(self, k, v)


def ExpressionStatementTest():
    return ExpressionStatement(
        AssignmentExpression(Identifier('a', None, False),
                             assignmentOperator.ADD, Identifier('b', None, False)))


if __name__ == '__main__':
    id1 = Identifier('a', None, False)
    id2 = Identifier('b', None, False)
    binexp = BinaryExpression(id1, binaryOperator.ADD, id2)
    expstmt = ExpressionStatement(binexp)
    print(expstmt)
Esempio n. 20
0
def FunctionCallTest():
    k = FunctionCall(Identifier('fun', None, False))
    print(k)
    args = [Identifier('a', None, False), Identifier('b', None, False)]
    k = FunctionCall(Identifier('fun', None, False), args)
    print(k)
Esempio n. 21
0
            raise InvalidBodyException(type(body))
        self.setChild(1, body)

    def __repr__(self):
        """Returns a string representation of the contents 
of the do loop object (Example: 'do {...} while(...)' 
). Currently the returned string is in AnsiC. 
Change this function to return different a representation."""

        retval = 'do ' + repr(self.getChild(1)) + ' while ('
        retval += repr(self.getChild(0)) + ')'
        return retval


if __name__ == '__main__':
    control = ConditionalExpression(Identifier('a', None, False),
                                    conditionalOperator.COMPARE_EQ,
                                    Identifier('a', None, False))
    assignexp1 = AssignmentExpression(Identifier('a', None, False),
                                      assignmentOperator.ADD,
                                      Identifier('b', None, False))
    assignStmt = ExpressionStatement(assignexp1)
    decl1 = DeclarationStatement(
        VariableDeclaration(specifiers.int8,
                            VariableDeclarator(Identifier('y', None, False))))
    body = CompoundStatement()
    body.addStatement(decl1)
    body.addStatement(assignStmt)
    doloop = DoLoop(control, body)
    print(doloop)
Esempio n. 22
0
def AssignmentExpressionTest():
    return AssignmentExpression(Identifier('a', None, False),
                                assignmentOperator.ADD,
                                Identifier('b', None, False))
Esempio n. 23
0
given Declaration: can be either VariableDeclaration or
ProcedureDeclaration. Raises Exception if not either type"""
        Statement.__init__(self)
        self.setNumChildren(1)
        if not isinstance(exp, Declaration):
            raise NotADeclarationError('Type: (%s)' % (type(exp)))
        self.setChild(0, exp)
        exp.setParent(self)

    def getDeclaration(self):
        """Returns the declaration associated with this
DeclarationStatement."""
        return self.getChild(0)

    def __repr__(self):
        retval = repr(self.getDeclaration()) + ';'
        return retval
    __str__ = __repr__


if __name__ == '__main__':
    k = VariableDeclaration(specifiers.int8,
                            VariableDeclarator(Identifier('y', None, False)))
    s = DeclarationStatement(k)
    print((repr(s)))
    from hir.StructDeclaration import StructDeclaration, StructDeclarationTest
    s = DeclarationStatement(StructDeclarationTest())
    print(s)
    s = DeclarationStatement(StructDeclaration(Identifier('s', None, False)))
    print(s)
Esempio n. 24
0
                supitems = k.items(self)
                for k, v in list(supitems.items()):
                    items[k] = v
        return dict(items)

    def __getstate__(self):
        """Returns the results of self.items() call 
when called by pickle or copy"""
        return dict(self.items())

    def __setstate__(self, statedict):
        """Blindly sets state based on the items like statedict"""
        for k, v in list(statedict.items()):
            setattr(self, k, v)

    def get_symbol(self):
        ch = self.getChildren()
        return ch[0].get_symbol()


if __name__ == '__main__':
    from hir.Identifier import Identifier
    from hir.ArraySpecifier import ArraySpecifierTest
    from hir.Keyword import CONST, VOLATILE, RESTRICT
    print((VariableDeclarator(Identifier('a', None, False),
                              ArraySpecifierTest())))
    print((VariableDeclarator(Identifier('a', None, False),
                              ArraySpecifierTest(),
                              PointerSpecifier([CONST,
                                                RESTRICT, VOLATILE]))))
Esempio n. 25
0
def BinaryExpressionTest():
    return BinaryExpression(Identifier('a', None, False),
                            binaryOperator.SUBTRACT, Identifier('b', None, False))
Esempio n. 26
0
def AccessExpressionTest2():
    return AccessExpression(Identifier('a', None, False), accessOperator.ARROW,
                            Identifier('b', None, False))