学习记录:用 Go 自制解释器 Monkey

词法分析

TDD:测试驱动开发

先写测试用例,再进行词法分析逻辑的完善。

语法分析

递归下降语法分析伪代码

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()
}
递归下降分析法

let x=5

let stmt AST structure

return 5

return stmt AST structue

普拉特解析


学习记录:用 Go 自制解释器 Monkey
https://hedon.top/2024/05/12/monkey-language/
Author
Hedon Wang
Posted on
2024-05-12
Licensed under