def for_statement(self): self.consume(TokenType.LEFT_PAREN, "Expect '(' after 'for'.") # initializer = None if self.match(TokenType.SEMICOLON): initializer = None elif self.match(TokenType.VAR): initializer = self.var_declaration() else: initializer = self.expression_statement() condition = None if not self.check(TokenType.SEMICOLON): condition = self.expression() self.consume(TokenType.SEMICOLON, "Expect ';' after loop condition.") increment = None if not self.check(TokenType.RIGHT_PAREN): increment = self.expression() self.consume(TokenType.RIGHT_PAREN, "Expect ')' after for clauses.") body = self.statement() if increment is not None: body = Stmt.Block([body, Stmt.Expression(increment)]) condition = SyntaxTree.Literal( True) if condition is None else condition body = Stmt.While(condition, body) if initializer is not None: body = Stmt.Block([initializer, body]) return body
def while_statement(self): self.consume(TokenType.LEFT_PAREN, "Expect '(' after 'while'.") condition = self.expression() self.consume(TokenType.RIGHT_PAREN, "Expect ')' after condition.") body = self.statement() return Stmt.While(condition, body)