-
Notifications
You must be signed in to change notification settings - Fork 0
/
FarmExpr.g4
77 lines (58 loc) · 1.44 KB
/
FarmExpr.g4
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
grammar FarmExpr;
func: 'def' NAME '(' (parameter)? (',' parameter)* ')' ('->' type)? '{' prog '}' ;
parameter: NAME ':' type ;
// A program is a bunch of statements
prog: (stmt | func)* ;
stmt: decl_stmt
| if_stmt
| expr_stmt
| assign_stmt
| loop_stmt
| return_stmt
;
// Declarations
decl_stmt: type NAME ('=' (expr | pairs) )? ';' ;
// Expression, they evaluate to a value
expr_stmt: expr ';' ;
// Assign the evaluated value to a variable
assign_stmt: NAME '=' expr ';' ;
// If statement
if_stmt: 'if' expr '{' prog '}' ('else' '{' prog '}')? ;
// Loop statement
loop_stmt: 'for' NAME 'in' NAME '{' prog '}';
// Final return of function
return_stmt: 'return' expr ';' ;
// Argument to function call
args: expr (',' expr)* ;
pairs: '[' pair (',' pair)* ']' ;
pair: NAME ':' expr ;
// Types
type: 'Num'
| 'Bool'
| 'Farm'
| 'Crop'
;
// Function call
call_expr: NAME '(' args? ')' ;
expr: '(' expr ')'
| expr op=( 'and' | 'or' ) expr
| expr op=('*'|'/') expr
| expr op=('+'|'-') expr
| expr op=( '!=' | '==' | '>=' | '<=' | '<' | '>' ) expr
| call_expr
| NAME '.' call_expr
| BOOL
| INT
| FLOAT
| NAME
| STRING
;
// Tokens
END : ';' ;
INT : [0-9]+ ;
FLOAT: [0-9]+ '.' [0-9]+ ;
BOOL : 'true' | 'false' ;
STRING: '"' ( ~["\\] | '\\' . )* '"' ;
NAME : [a-zA-Z_][a-zA-Z_0-9]*;
WS : [ \t\r\n]+ -> skip ;
LINE_COMMENT : '//' ~[\r\n]* -> skip ;