]> gitweb.ps.run Git - toc/blob - Toc.g4
complete grammar
[toc] / Toc.g4
1 grammar Toc;\r
2 \r
3 prog: (decl)+ EOF;\r
4 \r
5 decl: varDecl\r
6     | funcDecl\r
7     | structDecl\r
8     ;\r
9 \r
10 varDecl:  'var' var;\r
11 var:  varName (':' type) ('=' expr)?;\r
12 varInit:  varName (':' type) ('=' expr);\r
13 \r
14 type: typeName (typeModifier)*;\r
15 typeModifier: '*' | '[' NUMBER? ']';\r
16 \r
17 \r
18 funcDecl: 'func' func;\r
19 func: funcName '(' parameter ')' (':' type) body;\r
20 parameter: (var (',' var)*)?;\r
21 \r
22 body: '{' stmt* '}';\r
23 \r
24 \r
25 structDecl: 'struct' structName '{' structMember* '}';\r
26 structMember: structVar | structMethod;\r
27 structVar: var;\r
28 structMethod: func;\r
29 \r
30 \r
31 stmt: varDecl\r
32     | ifStmt\r
33     | switchStmt\r
34     | forStmt\r
35     | whileStmt\r
36     | assignStmt\r
37     | returnStmt\r
38     | expr;\r
39 \r
40 ifStmt: 'if' expr body ('else' 'if' expr body)* ('else' body)?;\r
41 \r
42 switchStmt: 'switch' identifierExpr switchBody;\r
43 switchBody: '{' ('case' expr body)* '}';\r
44 \r
45 forStmt: 'for' (varInit | assignStmt) ',' expr ',' expr body;\r
46 \r
47 whileStmt: 'while' expr body;\r
48 \r
49 assignStmt: identifierExpr '=' expr;\r
50 \r
51 returnStmt: 'return' expr;\r
52 \r
53 expr: funcExpr\r
54     | litExpr\r
55     | identifierExpr\r
56     | parenExpr\r
57     | accessExpr\r
58     | opExpr;\r
59 \r
60 /* op */\r
61 nonOpExpr: funcExpr\r
62          | litExpr\r
63          | identifierExpr\r
64          | parenExpr\r
65          | accessExpr;\r
66 \r
67 /* lit access op */\r
68 nonAccessExpr: funcExpr\r
69              | identifierExpr\r
70              | parenExpr;\r
71 \r
72 funcExpr: funcName '(' (expr (',' expr)*)? ')';\r
73 \r
74 opExpr: binaryOp | prefixOp | postfixOp | ternaryOp;\r
75 binaryOp: nonOpExpr BINARY_OP nonOpExpr (BINARY_OP nonOpExpr)*;\r
76 prefixOp: PREFIX_OP nonOpExpr;\r
77 postfixOp: nonOpExpr POSTFIX_OP;\r
78 ternaryOp: nonOpExpr '?' expr ':' expr;\r
79 \r
80 identifierExpr: varName;\r
81 \r
82 litExpr: INT_LIT | DECIMAL_LIT | STRING_LIT | BOOL_LIT;\r
83 \r
84 accessExpr: nonAccessExpr ((('.' | '->') identifierExpr) | ('[' expr ']'))+;\r
85 \r
86 parenExpr: '(' expr ')';\r
87 \r
88 funcName: NAME;\r
89 varName: NAME;\r
90 typeName: NAME;\r
91 structName: NAME;\r
92 \r
93 \r
94 POSTFIX_OP:\r
95     '++' | '--';\r
96 PREFIX_OP:\r
97     [+!~&*-] | POSTFIX_OP;\r
98 BINARY_OP:\r
99     [+*/%&<|^>-] |\r
100     '==' | '!=' | '<=' | '>=' | '<'  | '>' |\r
101     '<<' | '>>' | '||' | '&&' | '&=' | '|=' | '^=' |\r
102     '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=';\r
103 \r
104 INT_LIT: ('+' | '-')? [0-9]+;\r
105 DECIMAL_LIT: ('+' | '-')* [0-9]+ '.' [0-9]+;\r
106 STRING_LIT: '"' [^"]* '"';\r
107 BOOL_LIT: 'true' | 'false';\r
108 \r
109 NAME: ([a-z] | [A-Z] | [0-9])+;\r
110 WS: [ \t\r\n]+ -> skip;\r
111 NEWLINE: [\r\n]+;\r
112 NUMBER: [0-9]+;\r