Esempio n. 1
0
    def _function_definition(self):
        """Function definition rule.

        function_definition -> 'def' ID '(' (ID (',' ID)*)? ')' slist
        """
        self._match(tokens.DEF)

        node = AST(tokens.FUNC_DEF)
        id_token = self._lookahead_token(0)
        node.add_child(AST(id_token))

        func_symbol = FunctionSymbol(id_token.text, self.current_scope)
        func_symbol.scope = self.current_scope
        self.current_scope.define(func_symbol)
        self.current_scope = func_symbol

        self._match(tokens.ID)
        self._match(tokens.LPAREN)

        if self._lookahead_type(0) == tokens.ID:
            node.add_child(AST(self._lookahead_token(0)))

            variable_symbol = VariableSymbol(self._lookahead_token(0).text)
            variable_symbol.scope = self.current_scope
            self.current_scope.define(variable_symbol)

            self._match(tokens.ID)

            while self._lookahead_type(0) == tokens.COMMA:
                self._match(tokens.COMMA)
                node.add_child(AST(self._lookahead_token(0)))

                variable_symbol = VariableSymbol(self._lookahead_token(0).text)
                self.current_scope.define(variable_symbol)
                variable_symbol.scope = self.current_scope

                self._match(tokens.ID)

        self._match(tokens.RPAREN)

        self.current_scope = LocalScope(self.current_scope)

        block_ast = self._slist()
        func_symbol.block_ast = block_ast
        node.add_child(block_ast)

        # pop LocalScope
        self.current_scope = self.current_scope.get_enclosing_scope()

        # pop FunctionSymbol
        self.current_scope = self.current_scope.get_enclosing_scope()

        return node
Esempio n. 2
0
    def _assign(self):
        """Assign rule.

        assign -> ID '=' expr
        """
        node = AST(tokens.ASSIGN)
        node.add_child(AST(self._lookahead_token(0)))

        variable_symbol = VariableSymbol(self._lookahead_token(0).text)
        variable_symbol.scope = self.current_scope
        self.current_scope.define(variable_symbol)

        self._match(tokens.ID)
        self._match(tokens.ASSIGN)
        node.add_child(self._expr())

        return node