Compiler 2013: An appetizer
外观
This page illustrates a complete process of a toy compiler as a tutorial. The source code is available at https://bitbucket.org/xjia/appetizer
Example 1
int main() { int a; int b; int c; int max; a = 10; b = 10 * 3; c = 10 + 10; max = a; if (b > max) { max = b; } if (c > max) { max = c; } return max; }
The result is 30.
Example 2
int main() { int a; int b; a = 0; b = 10; { int b; b = 20; a = a + b; } return a; }
The result is 20.
Example 3
int main() { int a; a = 10; if (a > 0) return a; return 0; }
The result is 10.
Grammar
The ANTLR grammar is given as follows.
grammar Appetizer; program : 'int' ID '(' ')' block ; block : '{' decl* stmt* '}' ; decl : 'int' ID ';' ; stmt : 'if' '(' expr ')' stmt | 'return' expr ';' | expr ';' | block ; expr : expr ('*'|'/') expr | expr ('+'|'-') expr | expr ('=='|'!='|'>'|'>='|'<'|'<=') expr | expr '=' expr | ID | NUM | '(' expr ')' ; ID : [a-z]+ ; NUM : [0-9]+ ; WS : [ \t\f\r\n]+ -> skip ;
Functions and arrays are not allowed.
Comments are nested, and enclosed with /*
and */
.
In this tutorial, we use JFlex for lexing and CUP for parsing.