跳转到内容

Compiler 2014: An appetizer

来自ACM Class Wiki

This page illustrates a complete process of a toy compiler as a tutorial. Just download the source code and try to make it compile.

Grammar

In this tutorial, we use JFlex for lexing and CUP for parsing.

If you want to use ANTLR, The ANTLR grammar is given as follows.

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 */.

Source Code

Note

  • The Makefiles are written for linux, jdk1.7.0.
  • The appetizer also shows how do we test your program.
  • The run.sh in the root directory should explain everything.
  • You can use QtSPIM or statspim to execute the .asm files. They are available in the homepage.