-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.lark
77 lines (61 loc) · 2.34 KB
/
grammar.lark
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
?program: statement+ //1 o inf statement
// The ?<rule> is important to shape the tree and reduce the
// number of children for single father if they is useful
?statement: declaration
| bool_logic
| if_stmt
| for_stmnt
| "Printf" "(" (expression | bool_logic) ")" -> printf
// Variable declarations and assignment
?declaration: "var" ident_list (DATA_TYPE "=" expression_list | "=" expression_list) -> assignment // Typed or not
| ident_list ":=" expression_list -> short_assignment // x := 2 || x,y,z := 2,3,4
| ident_list ":=" array_type "{" expression_list "}" -> array_assignment // x := [4]int{1,2,3,4}
// Data types
DATA_TYPE: "int" | "string" | "bool"
ident_list : IDENTIFIER ("," IDENTIFIER)*
expression_list : expression ("," expression)*
array_type : "[" NUMBER "]" DATA_TYPE
?bool_logic: relation
| "(" bool_logic ")"
| bool_logic "&&" bool_logic -> bool_and
| bool_logic "||" bool_logic -> bool_or
| "!" bool_logic -> bool_not
?relation: "(" relation ")"
| expression "<" expression -> less
| expression ">" expression -> great
| expression ">=" expression -> great_eq
| expression "<=" expression -> less_eq
| expression "==" expression -> equal
| expression "!=" expression -> not_equal
?expression: "(" expression ")"
| term
| addition
| subtraction
term: "(" term ")"
| factor
| "(" addition ")"
| "(" subtraction ")"
| multiplication
| division
factor: NUMBER
| IDENTIFIER
| STRING
| IDENTIFIER "[" expression "]" -> index
| "Scanf" "(" expression ")" -> scanf
addition : expression "+" expression
subtraction : expression "-" expression
multiplication : term "*" term
division : term "/" term
block_statement: "{" statement+ "}"
// If Statement
if_stmt: "if" bool_logic block_statement ("else" (if_stmt|block_statement))?
// For Statement
for_stmnt: "for" bool_logic block_statement -> while_loop
| "for" declaration ";" bool_logic ";" IDENTIFIER "++" block_statement -> for_loop
// String type, enclosed by double quotes (ex. "ciao")
STRING: /".*"/
// Import terminals from common library
%import common.CNAME -> IDENTIFIER
%import common.NUMBER
%import common.WS
%ignore WS