예제 #1
0
    def visit_If(self, ast_if: If):
        if_node = IfNode()
        # coord = coordinate(ast_if.col_offset, ast_if.lineno)
        # self.set_coordinate(if_node, coord)
        # condition
        if_node.condition = self.visit(ast_if.test)

        # convert pyc true statement to list
        if type(ast_if.body) is not list:
            ast_if.body = [ast_if.body]

        self.parent = if_node.true_stmt
        for child in ast_if.body or []:
            child_node = self.visit(child)
            if child_node:
                if type(child_node) is list:
                    if_node.true_stmt.extend(child_node)
                else:
                    if_node.true_stmt.append(child_node)

        # convert pyc false statement to list
        if ast_if.orelse:
            if type(ast_if.orelse) is not list:
                ast_if.orelse = [ast_if.orelse]

            self.parent = if_node.false_stmt
            for child in ast_if.orelse or []:
                child_node = self.visit(child)
                if child_node:
                    if type(child_node) is list:
                        if_node.false_stmt.extend(child_node)
                    else:
                        if_node.false_stmt.append(child_node)
        return if_node
    def compile_ifnode(self, srcnode, parent):
        comparison = get_comparison('{}'.format(srcnode.test))
        if_ = If(test=comparison, body=[], orelse=[])
        parent.body.append(self.annotate_runtime_errors(if_, srcnode))
        for item in srcnode.children:
            self._compile(item, if_)

        if srcnode.else_:
            m = Module(body=[])
            for item in srcnode.else_.children:
                self._compile(item, m)
            if_.orelse = m.body

        if if_.body == []:
            if_.body = [Pass()]
    def compile_choosenode(self, srcnode, parent):
        if srcnode.test is None or srcnode.test.strip() == '':
            srcnode.test = 'True'

        choosevar = self.unique_id('choose')
        chooseflag = self.unique_id('chosen')

        parent.body.append(self.annotate_runtime_errors(
            parse_and_strip(u'{} = False\n'
                            u'{} = {}\n'.format(chooseflag,
                                                choosevar,
                                                srcnode.test)),
            srcnode))

        for item in srcnode.children:
            if isinstance(item, im.WhenNode):
                comparison = get_comparison(u'{} is False and {} == ({})'
                                            .format(chooseflag,
                                                    choosevar,
                                                    item.test))
                if_ = If(test=comparison, body=[], orelse=[])
                if_.body.extend(
                    parse_and_strip('{} = True'.format(chooseflag)))
                set_pos(if_, item)
                parent.body.append(self.annotate_runtime_errors(if_, srcnode))
                for sub in item.children:
                    self._compile(sub, if_)

            elif isinstance(item, im.OtherwiseNode):
                comparison = get_comparison('{} is False'.format(chooseflag))
                if_ = If(test=comparison, body=[], orelse=[])
                set_pos(if_, item)
                parent.body.append(if_)
                for sub in item.children:
                    self._compile(sub, if_)
                if if_.body == []:
                    if_.body = [Pass()]
            else:
                self._compile(item, parent)
예제 #4
0
def parseIfStatement(parser):
    parser.check(lexeme=keywords['IF'])
    lineo = parser.currentToken[2]
    parser.next(lexeme='(')
    parser.next()
    predicate = parsePredicate(parser)
    parser.check(lexeme=')')
    parser.next()
    stm = parseStatement(parser)
    elsestm = ""
    if parser.matchLexeme(keywords['ELSE']):
        parser.next()
        elsestm = parseStatement(parser)

    ifstm = If(predicate, stm, elsestm, lineo=lineo)
    return ifstm
예제 #5
0
    def handle_when(self, when, *others):
        test, body = when.get_source_expressions()
        if others:
            if others[0].__class__.__name__ == "When":
                orelse = [self.handle_when(*others)]
            else:
                # Can we ever have other expressions after the default?
                orelse = [
                    Return(value=self.build_expression(others[0]), **self.file)
                ]
        else:
            orelse = []

        return If(
            test=self.build_expression(test),
            body=[Return(value=self.build_expression(body), **self.file)],
            orelse=orelse,
            **self.file,
        )
예제 #6
0
파일: parse.py 프로젝트: milad621/cse210A
 def command(self):
     """ c ::=
     skip
     | x := e
     | if b then c1 else c2
     | while b do c
     """
     if self.current_token.type == '{':
         self.eat('{')
         c = self.comma_command()
         self.eat('}')
         return c
     if self.current_token.type == 'skip':
         self.eat('skip')
         return Skip()
     if self.current_token.type == 'if':
         self.eat('if')
         b = self.b_or()
         self.eat('then')
         c1 = self.comma_command()
         self.eat('else')
         c2 = self.comma_command()
         return If(b, c1, c2)
     if self.current_token.type == 'while':
         # print("current token:", self.current_token.type, self.current_token.value)
         self.eat('while')
         # print("current token:", self.current_token.type, self.current_token.value)
         b = self.b_or()
         # print(b, b.token, b.value)
         # print("current token:", self.current_token.type, self.current_token.value)
         self.eat('do')
         # print("current token:", self.current_token.type, self.current_token.value)
         c = self.command()
         # print(c)
         # print("current token:", self.current_token.type, self.current_token.value)
         return While(b, c)
     if self.current_token.type == VAR:
         x = Var(self.current_token.value)
         self.eat(VAR)
         self.eat(':=')
         e = self.aexp()
         return Assign(x, e)
예제 #7
0
    def register_binding(withstmt, mode, kind):
        assert mode in ("block", "expr")
        assert kind in ("barename", "template")
        ctxmanager = withstmt.items[0].context_expr
        optvars = withstmt.items[0].optional_vars
        if not optvars:
            assert False, "'with {}:': expected an as-part".format(
                mode)  # pragma: no cover
        if type(optvars) is not Name:
            assert False, "'with {}:': expected exactly one name in the as-part".format(
                mode)  # pragma: no cover

        name = optvars.id
        if name in names_seen:
            assert False, "duplicate '{}'; as-parts in the same let_syntax block must be unique".format(
                name)  # pragma: no cover

        if kind == "template":
            _, args = _analyze_lhs(
                ctxmanager
            )  # syntactic limitation, can't place formal parameter list on the as-part
        else:  # kind == "barename":
            args = []

        if mode == "block":
            value = If(
                test=Num(n=1),  # TODO: Python 3.8+: ast.Constant, no ast.Num
                body=withstmt.body,
                orelse=[],
                lineno=stmt.lineno,
                col_offset=stmt.col_offset)
        else:  # mode == "expr":
            if len(withstmt.body) != 1:
                assert False, "'with expr:' expected a one-item body (use a do[] if need more)"  # pragma: no cover
            theexpr = withstmt.body[0]
            if type(theexpr) is not Expr:
                assert False, "'with expr:' expected an expression body, got a statement"  # pragma: no cover
            value = theexpr.value  # discard Expr wrapper in definition
        names_seen.add(name)
        target = templates if args else barenames
        target.append((name, args, value, mode))
예제 #8
0
    def visit_If(self, node: ast.If) -> str:
        body_vars: Set[str] = set(
            [get_id(v) for v in node.scopes[-1].body_vars])
        orelse_vars: Set[str] = set(
            [get_id(v) for v in node.scopes[-1].orelse_vars])
        node.common_vars = body_vars.intersection(orelse_vars)

        body: str = "\n".join([
            self.indent(self.visit(child), level=node.level + 1)
            for child in node.body
        ])
        orelse: str = "\n".join([
            self.indent(self.visit(child), level=node.level + 1)
            for child in node.orelse
        ])
        test: str = self.visit(node.test)
        if node.orelse:
            orelse = self.indent(f"else {{\n{orelse}\n}}", level=node.level)
        else:
            orelse = ""
        return f"if {test} {{\n{body}\n}}\n{orelse}"
예제 #9
0
파일: Parser.py 프로젝트: vinayakvivek/aplc
 def p_if_statement(self, p):
     '''if_statement : IF LPAREN logical_expression RPAREN block_statement %prec IFX'''
     p[0] = If(p[3], p[5], None)