def _factor(self): """Matches based on the rule: factor -> unary ( ( / | * ) unary)*""" expr = self._unary() while self._match(scanner.TokenType.SLASH, scanner.TokenType.STAR): operator = self._previous() right = self._unary() expr = grammar.Binary(expr, operator, right) return expr
def _term(self): """Matches based on the rule: term -> factor ( ( - | + ) factor)*""" expr = self._factor() while self._match(scanner.TokenType.MINUS, scanner.TokenType.PLUS): operator = self._previous() right = self._factor() expr = grammar.Binary(expr, operator, right) return expr
def _comparison(self): """Matches based on the rule: comparison -> term ( ( > | >= | < | <= ) term)*""" expr = self._term() while self._match(TokenType.GREATER, TokenType.GREATER_EQUAL, TokenType.LESS, TokenType.LESS_EQUAL): operator = self._previous() right = self._term() expr = grammar.Binary(expr, operator, right) return expr
def _equality(self): """Matches based on the rule: equality -> comparison ( ( != | == ) comparison)*""" expr = self._comparison() # An Equality expression can match either a comparison # or comparison ((!= | ==) comparison)* while self._match(TokenType.BANG_EQUAL, TokenType.EQUAL_EQUAL): operator = self._previous() right = self._comparison() expr = grammar.Binary(expr, operator, right) return expr
return self.parenthesize(expr.operator.lexeme, expr.left, expr.right) def visitGrouping(self, expr): return self.parenthesize("group", expr.expression) def visitLiteral(self, expr): return str(expr.value) def visitUnary(self, expr): return self.parenthesize(expr.operator.lexeme, expr.right) def parenthesize(self, name, *exprs): string = "(" + name for expr in exprs: string += " " string += expr.accept(self) string += ")" return string if __name__ == "__main__": expression = grammar.Binary( grammar.Unary(scanner.Token(scanner.TokenType.MINUS, "-", None, 1), Literal(123)), scanner.Token(scanner.TokenType.STAR, "*", None, 1), grammar.Grouping(grammar.Literal(45.67))) print(AstPrinter().printast(expression))