abouttreesummaryrefslogcommitdiff
path: root/Toc.g4
blob: 631e2c3d2123e69fa2c124969b43d1c8e48ee9a4 (plain)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
grammar Toc;

prog: (decl)+ EOF;

decl: varDecl
    | funcDecl
    | structDecl
    ;

varDecl:  'var' var;
var:  varName (':' type) ('=' expr)?;
varInit:  varName (':' type) ('=' expr);

type: typeName (typeModifier)*;
typeModifier: '*' | '[' NUMBER? ']';


funcDecl: 'func' func;
func: funcName '(' parameter ')' (':' type) body;
parameter: (var (',' var)*)?;

body: '{' stmt* '}';


structDecl: 'struct' structName '{' structMember* '}';
structMember: structVar | structMethod;
structVar: var;
structMethod: func;


stmt: varDecl
    | ifStmt
    | switchStmt
    | forStmt
    | whileStmt
    | assignStmt
    | returnStmt
    | expr;

ifStmt: 'if' expr body ('else' 'if' expr body)* ('else' body)?;

switchStmt: 'switch' identifierExpr switchBody;
switchBody: '{' ('case' expr body)* '}';

forStmt: 'for' (varInit | assignStmt) ',' expr ',' expr body;

whileStmt: 'while' expr body;

assignStmt: identifierExpr '=' expr;

returnStmt: 'return' expr;

expr: funcExpr
    | litExpr
    | identifierExpr
    | parenExpr
    | accessExpr
    | opExpr;

/* op */
nonOpExpr: funcExpr
         | litExpr
         | identifierExpr
         | parenExpr
         | accessExpr;

/* lit access op */
nonAccessExpr: funcExpr
             | identifierExpr
             | parenExpr;

funcExpr: funcName '(' (expr (',' expr)*)? ')';

opExpr: binaryOp | prefixOp | postfixOp | ternaryOp;
binaryOp: nonOpExpr BINARY_OP nonOpExpr (BINARY_OP nonOpExpr)*;
prefixOp: PREFIX_OP nonOpExpr;
postfixOp: nonOpExpr POSTFIX_OP;
ternaryOp: nonOpExpr '?' expr ':' expr;

identifierExpr: varName;

litExpr: INT_LIT | DECIMAL_LIT | STRING_LIT | BOOL_LIT;

accessExpr: nonAccessExpr ((('.' | '->') identifierExpr) | ('[' expr ']'))+;

parenExpr: '(' expr ')';

funcName: NAME;
varName: NAME;
typeName: NAME;
structName: NAME;


POSTFIX_OP:
    '++' | '--';
PREFIX_OP:
    [+!~&*-] | POSTFIX_OP;
BINARY_OP:
    [+*/%&<|^>-] |
    '==' | '!=' | '<=' | '>=' | '<'  | '>' |
    '<<' | '>>' | '||' | '&&' | '&=' | '|=' | '^=' |
    '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=';

INT_LIT: ('+' | '-')? [0-9]+;
DECIMAL_LIT: ('+' | '-')* [0-9]+ '.' [0-9]+;
STRING_LIT: '"' [^"]* '"';
BOOL_LIT: 'true' | 'false';

NAME: ([a-z] | [A-Z] | [0-9])+;
WS: [ \t\r\n]+ -> skip;
NEWLINE: [\r\n]+;
NUMBER: [0-9]+;