summaryrefslogtreecommitdiff
path: root/Homework/cs5300/p4-formatter/grammar/Cminus.g4
blob: 9538eeab39f337c005e318b0b8307b8f0cae4e8c (plain) (blame)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
grammar Cminus;

program : declaration+ ;

declaration : varDeclaration | funDeclaration ;

varDeclaration : typeSpecifier varDeclId (',' varDeclId)* ';' ;

varDeclId : ID | ID '[' NUMCONST ']' ;
 
funDeclaration : ('void' | typeSpecifier) ID '(' param? (',' param)* ')' statement ;
//funDeclaration : ('void' | typeSpecifier) ID '(' param? (',' param)* ')' compoundStatement ;

typeSpecifier : 'int' | 'bool' | 'char' ;

param : typeSpecifier paramId ;

paramId : ID | ID '[]' ;

statement : expressionStmt | compoundStmt | ifStmt
          | whileStmt | returnStmt | breakStmt ;

compoundStmt : '{' varDeclaration* statement* '}' ;

expressionStmt : expression ';' | ';' ;

ifStmt : 'if' '(' simpleExpression ')' statement
       | 'if' '(' simpleExpression ')' statement 'else' statement
       ;

whileStmt : 'while' '(' simpleExpression ')' statement ;

returnStmt : 'return' ';' | 'return' expression ';' ;

breakStmt : 'break' ';' ;

expression : mutable '=' expression
           | mutable '+=' expression | mutable '-=' expression
           | mutable '*=' expression | mutable '/=' expression
           | mutable '++' | mutable '--' | simpleExpression
           ;

simpleExpression : orExpression ;

orExpression : (andExpression '||')* andExpression ;

andExpression : (unaryRelExpression '&&')* unaryRelExpression ;

unaryRelExpression : BANG* relExpression ;

relExpression : (sumExpression relop)* sumExpression ;

relop : '<=' | '<' | '>' | '>=' | '==' | '!=' ;

sumExpression : (termExpression sumop)* termExpression ;

sumop : '+' | '-' ;

termExpression : (unaryExpression mulop)* unaryExpression ;

mulop : '*' | '/' | '%' ;

unaryExpression : unaryop* factor ;

unaryop : '-' | '*' | '?' ;

factor : immutable | mutable ;

mutable : ID | ID '[' expression ']' ;

immutable : '(' expression ')' | call | constant ;

call : ID '(' (expression ',')* expression? ')' ;

constant : NUMCONST | CHARCONST | STRINGCONST | 'true' | 'false' ;

ID : LETTER (LETTER | DIGIT)* ;
NUMCONST : DIGIT+ ;
STRINGCONST : '"' ('\\"'|~'"')*? '"' ;
CHARCONST : '"' ('\\"'|~'"') '"' ;
BANG : '!' ;

WS :  (' ' | '\t' | '\n' | '\r' | '\f')+ -> skip ;
COMMENT
  :   ( '//' ~[\r\n]* '\r'? '\n'
      | '/*' .*? '*/'
      ) -> skip
  ;

fragment LETTER : ('a'..'z' | 'A'..'Z');
fragment DIGIT  : ('0'..'9');