1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| function parseProgram() { program = newProgramASTNode() advanceTokens() for (currentToken() != EOF_TOKEN) { statement = null if (currentToken() == LET_TOKEN) { statement = parseLetStatement() } else if (currentToken() == RETURN_TOKEN) { statement = parseReturnStatement() } else if (currentToken() == IF_TOKEN) { statement = parseIfStatement() } if (statement != null) { program.Statements.push(statement) } advanceTokens() } return program } function parseLetStatement() { advanceTokens() identifier = parseIdentifier() advanceTokens() if currentToken() != EQUAL_TOKEN { parseError("no equal sign!") return null } advanceTokens() value = parseExpression() variableStatement = newVariableStatementASTNode() variableStatement.identifier = identifier variableStatement.value = value return variableStatement } function parseIdentifier() { identifier = newIdentifierASTNode() identifier.token = currentToken() return identifier } function parseExpression() { if (currentToken() == INTEGER_TOKEN) { if (nextToken() == PLUS_TOKEN) { return parseOperatorExpression() } else if (nextToken() == SEMICOLON_TOKEN) { return parseIntegerLiteral() } } else if (currentToken() == LEFT_PAREN) { return parseGroupedExpression() }
} function parseOperatorExpression() { operatorExpression = newOperatorExpression() operatorExpression.left = parseIntegerLiteral() operatorExpression.operator = currentToken() operatorExpression.right = parseExpression() return operatorExpression() }
|