Skip to content

Instantly share code, notes, and snippets.

@dubik
Created June 15, 2011 06:04
Show Gist options
  • Save dubik/1026572 to your computer and use it in GitHub Desktop.
Save dubik/1026572 to your computer and use it in GitHub Desktop.
simple grammar
grammar pascalminus;
options
{
output = AST;
language = Java;
// If generating an AST (output=AST; option) or specifying a tree walker then
// also add the following line
ASTLabelType=CommonTree;
}
prog : (prog_entity)*
;
prog_entity
: func_decl
;
func_decl
: DEF ID param_list? '{' block '}' ';'
;
param_list
: '(' ID (',' ID)* ')'
;
block : stat*
;
stat : expr
| assignment
| ifstmt
| return_stmt
| for_stmt
;
for_stmt: FOR ID IN '('? range_start '..' range_end ')'? '{' block '}' ';'
| WHILE '(' boolx ')' '{' block '}' ';'
;
range_start
: (INT|ID)
;
range_end: (INT|ID)
;
return_stmt
: RETURN expr ';'
;
ifstmt : IF '(' boolx ')' '{' block '}' (ELSE '{' block '}')? ';'
;
assignment
: ID ASSIGN expr ';'
;
boolx : eqexpr (('&&' | '||') eqexpr)*
;
eqexpr : boolatom (('==' | '>' | '<' | '<=' | '>=') boolatom)*
;
boolatom: INT
| ID
| '(' boolx ')'
;
expr : multexpr (('+' | '-') multexpr)*
;
multexpr: atom (('*' | '/') atom)*
;
atom : INT
| '(' expr ')'
| ID //| ID ('(' expr_list? ')')? // Function call
;
expr_list
: expr (',' expr)*
;
BEGIN : 'begin'
;
DEF : 'def'
;
END : 'end'
;
RETURN : 'return'
;
IF : 'if'
;
ELSE : 'else'
;
FOR : 'for'
;
IN : 'in'
;
TYPE : 'type'
;
FOREACH : 'foreach'
;
WHILE : 'while'
;
BREAK : 'break'
;
CASE : 'case'
;
DEFAULT : 'default'
;
INTEGER : 'integer'
;
STRING : 'string'
;
ARRAYOF : 'arrayof'
;
ASSIGN : ':='
;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
INT : '0'..'9'+
;
WS : ( ' '
| '\t'
| ( '\r\n' // DOS
| '\r' // MAC
| '\n' // Unix
)
) {$channel=HIDDEN;}
;
def func(x) {
x := 2;
if(x == 0) {
y := 10;
};
while(y < 10) {
y := y + 1;
};
for i in 1..100 {
x := x * i;
};
return z - 10;
};
def func{
};
def func1(x, y) {
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment