def for_statement(self): self._consume(TokenType.LEFT_PAREN, "Expect '(' after 'for'.") if self._match([TokenType.SEMICOLON]): initializer = None elif self._match([TokenType.VAR]): initializer = self.var_declaration() else: initializer = self.expression() condition = Expr.Literal(True) if not self._check(TokenType.SEMICOLON): condition = self.expression() self._consume(TokenType.SEMICOLON, "Expect ';' after loop condition.") incrementor = None if not self._check(TokenType.RIGHT_PAREN): incrementor = self.expression() self._consume(TokenType.RIGHT_PAREN, "Expect ') after for clauses.") body = self.statement() # Lox Code - `for (var a = 0; a < 3; a = a + 1) print a;` # is ~transalated~ desugared into: # { // This additional Block limits the scope # var a = 0; # while (a < 3){ # print a; # a = a + 1; # } # } if incrementor != None: body = Stmt.Block([body, incrementor]) body = Stmt.While(condition, body) if initializer != 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)