1. Lexer
github:compile/src/lexer
java实现一个词法分析器,参考link可以识别加法与乘法中的token。
| token | 种别码 |
|---|---|
| EOI | 0 |
| SEMI(;) | 1 |
| PLUS(+) | 2 |
| TIMES(*) | 3 |
| LP( ( ) | 4 |
| RP( ) ) | 5 |
| NUM | 6 |
| INT | 7 |
| EQ( =) | 8 |
| ID | 9 |
运行src/lexer
input:
int a = 1 ;
int b = a + 1;
end
output:
实现思路就是根据那个表,用switch…case…框架和最长匹配原则实现了词法分析。
2.parse
Grammar:
statements -> expression ;
| expression ; statements
expression -> term
|term + expression
term -> factor
| factor * term
factor -> NUM_OR_ID
| LP expression RP
github:compile/src/lexer
语法太过简单,用递归下降算法可得:
input:
1+2+3
end
output
input :
213+123+23989+4546;
34545*233+8980;
end
output: