-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnnamedLanguage.g
554 lines (467 loc) · 16.9 KB
/
UnnamedLanguage.g
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
grammar UnnamedLanguage;
@header
{
import ast.*;
import type.*;
}
@members
{
protected void mismatch (IntStream input, int ttype, BitSet follow) throws RecognitionException
{
throw new MismatchedTokenException(ttype, input);
}
public Object recoverFromMismatchedSet (IntStream input, RecognitionException e, BitSet follow)
throws RecognitionException
{
reportError(e);
throw e;
}
}
@rulecatch {
catch (RecognitionException ex) {
reportError(ex);
throw ex;
}
}
// Starting production
program returns [Program programNode]
@init {
List<Function> functions = new ArrayList<Function>();
}
: (f = function { functions.add(f); })+
{
programNode = new Program(functions);
}
EOF
;
function returns [Function functionNode]
: decl=functionDecl body=functionBody
{
functionNode = new Function(decl, body);
}
;
functionDecl returns [FunctionDecl declNode]
: typeNode = compoundType
idNode = identifier
OPEN_PAREN
formalsList = formalParameters
CLOSE_PAREN
{ declNode = new FunctionDecl(typeNode, idNode, formalsList); }
;
formalParameters returns [List<FormalParameter> formalNodes]
@init {
formalNodes = new ArrayList<FormalParameter>();
}
: firstParamNode = formalParameter { formalNodes.add(firstParamNode); }
(paramNode = moreFormals { formalNodes.add(paramNode); } ) *
| // Can be empty
;
moreFormals returns [FormalParameter paramNode]
: COMMA node = formalParameter
{
paramNode = node;
}
;
formalParameter returns [FormalParameter formalParamNode]
: compoundTypeNode = compoundType
idNode = identifier
{
formalParamNode = new FormalParameter(compoundTypeNode, idNode);
}
;
functionBody returns [FunctionBody bodyNode]
@init {
List<VariableDeclaration> varDecls = new ArrayList<VariableDeclaration>();
List<Statement> stmts = new ArrayList<Statement>();
}
: OPEN_BRACE
(declNode = varDecl {varDecls.add(declNode);} )*
(stmtNode = statement
{
if (stmtNode != null) {
stmts.add(stmtNode);
}
}
)*
CLOSE_BRACE
{
int line = $OPEN_BRACE.line;
int offset = $OPEN_BRACE.pos;
bodyNode = new FunctionBody(line, offset, varDecls, stmts);
}
;
varDecl returns [VariableDeclaration varDeclNode]
: typeNode = compoundType idNode = identifier SEMICOLON {
varDeclNode = new VariableDeclaration(typeNode, idNode);
}
;
compoundType returns [TypeNode typeNode]
: simpleNode = type { typeNode = simpleNode; }
| simpleNode = type OPEN_BRACKET size = intLiteral CLOSE_BRACKET {
// Pull out the simple type from the type and make an array type instead.
ArrayType arrayType = new ArrayType(size.value, simpleNode.getSimpleType());
typeNode = new ArrayTypeNode(simpleNode.line, simpleNode.offset, arrayType);
}
;
statement returns [Statement stmtNode]
options {
backtrack=true; // Necessary to prevent recursion errors
}
: SEMICOLON
| expNode = expression SEMICOLON { stmtNode = new ExpressionStatement(expNode); }
| ifStmtNode = ifElseStatement { stmtNode = ifStmtNode; }
| whileNode = whileStatement { stmtNode = whileNode; }
| printNode = printStatement { stmtNode = printNode; }
| printlnNode = printlnStatement { stmtNode = printlnNode; }
| returnStmtNode = returnStatement { stmtNode = returnStmtNode; }
| assignStmtNode = assignmentStatement { stmtNode = assignStmtNode; }
| arrayAssignStmtNode = arrayAssignmentStatement { stmtNode = arrayAssignStmtNode; }
;
ifElseStatement returns [IfStatement ifStmtNode]
: IF OPEN_PAREN expNode = expression CLOSE_PAREN ifBlockNode = block (ELSE elseBlockNode = block)?
{
int line = $IF.line, offset = $IF.pos;
if (elseBlockNode != null) {
ifStmtNode = new IfStatement(line, offset, expNode, ifBlockNode, elseBlockNode);
}
else {
ifStmtNode = new IfStatement(line, offset, expNode, ifBlockNode);
}
}
;
whileStatement returns [WhileStatement whileNode]
: WHILE OPEN_PAREN expNode = expression CLOSE_PAREN blockNode = block
{
int line = $WHILE.line, offset = $WHILE.pos;
whileNode = new WhileStatement(line, offset, expNode, blockNode);
}
;
printStatement returns [PrintStatement printStmtNode]
: PRINT expNode = expression SEMICOLON
{
int line = $PRINT.line, offset = $PRINT.pos;
printStmtNode = new PrintStatement(line, offset, expNode);
}
;
printlnStatement returns [PrintlnStatement printlnNode]
: PRINTLN expNode = expression SEMICOLON
{
int line = $PRINTLN.line, offset = $PRINTLN.pos;
printlnNode = new PrintlnStatement(line, offset, expNode);
}
;
returnStatement returns [ReturnStatement returnStmtNode]
: RETURN expNode = expression? SEMICOLON
{
int line = $RETURN.line, offset = $RETURN.pos;
if (expNode == null) {
returnStmtNode = new ReturnStatement(line, offset);
}
else {
returnStmtNode = new ReturnStatement(line, offset, expNode);
}
}
;
assignmentStatement returns [AssignmentStatement assignStmtNode]
: idNode = identifier EQUAL_ASSIGNMENT expNode = expression SEMICOLON
{
assignStmtNode = new AssignmentStatement(idNode, expNode);
}
;
arrayAssignmentStatement returns [ArrayAssignmentStatement arrayAssignStmtNode]
: arrayIdNode = identifier OPEN_BRACKET indexExpNode = expression CLOSE_BRACKET
EQUAL_ASSIGNMENT valueExpNode = expression SEMICOLON
{
arrayAssignStmtNode = new ArrayAssignmentStatement(arrayIdNode, indexExpNode, valueExpNode);
}
;
block returns [Block blockNode]
@init {
List<Statement> statements = new ArrayList<Statement>();
}
: OPEN_BRACE (stmtNode = statement
{
if (stmtNode != null) {
statements.add(stmtNode);
}
}
) * CLOSE_BRACE
{
int line = $OPEN_BRACE.line, offset = $OPEN_BRACE.pos;
blockNode = new Block(line, offset, statements);
}
;
// We nest expressions which use binary operators in increasing order
// of precedence to enforce precedence rules and prevent left-recursion
// issues.
expression returns [Expression exprNode]
: lhs = lessThanExpression {exprNode = lhs;}
(
eq = EQUAL_COMPARISON nextOperand = lessThanExpression {
exprNode = new EqualityExpression($eq.line, $eq.pos, exprNode, nextOperand);
}
)*
;
lessThanExpression returns [Expression exprNode]
: left = plusMinusExpression { exprNode = left; }
(
lt = LESS_THAN nextOperand = plusMinusExpression {
exprNode = new LessThanExpression($lt.line, $lt.pos, exprNode, nextOperand);
}
)*
;
plusMinusExpression returns [Expression exprNode]
: left = multExpression { exprNode = left; }
(
(plusToken = PLUS | minusToken = MINUS)
nextOperand = multExpression {
// Only one of the token variables should have a value.
assert (plusToken == null) != (minusToken == null);
// Determine the position of the operator and create a new node for
// the most recently parsed operator.
int line, offset;
if (plusToken != null) {
line = $plusToken.line;
offset = $plusToken.pos;
exprNode = new AddExpression(line, offset, exprNode, nextOperand);
}
else {
line = $minusToken.line;
offset = $minusToken.pos;
exprNode = new SubtractExpression(line, offset, exprNode, nextOperand);
}
// Clear both token references
plusToken = null;
minusToken = null;
}
)*
;
multExpression returns [Expression exprNode]
: left = expressionAtom {
// If there is no operator, just pass the node up to the next level.
exprNode = left;
}
(
MULTIPLY nextOperand = expressionAtom {
// Each time we find an operator, make a new binary node with the
// last one as the left child.
int line = $MULTIPLY.line;
int offset = $MULTIPLY.pos;
exprNode = new MultiplyExpression(line, offset, exprNode, nextOperand);
}
)*
;
expressionAtom returns [Expression exprNode]
: arrayRefNode = arrayReference {exprNode = arrayRefNode;}
| funcCallNode = functionCall {exprNode = funcCallNode;}
| idNode = identifier {exprNode = idNode;}
| litExprNode = literal {exprNode = litExprNode;}
| OPEN_PAREN e = expression CLOSE_PAREN {exprNode = new ParenExpression($OPEN_PAREN.line, $OPEN_PAREN.pos, e);}
;
functionCall returns [FunctionCall funcCallNode]
: idNode = identifier OPEN_PAREN exprList = expressionList CLOSE_PAREN {
funcCallNode = new FunctionCall(idNode, exprList);
}
;
expressionList returns [List<Expression> expressions]
@init {
expressions = new ArrayList<Expression>();
}
: firstExprNode = expression {expressions.add(firstExprNode); }
(
subsequentExprNode = exprMore {expressions.add(subsequentExprNode);}
)*
| // Can be empty
;
arrayReference returns [Expression arrayRefNode]
: id = identifier OPEN_BRACKET indexExpNode = expression CLOSE_BRACKET
{
arrayRefNode = new ArrayReference(id, indexExpNode);
}
;
exprMore returns [Expression exprNode]
: COMMA e = expression {exprNode = e;}
;
literal returns [Expression exprNode]
: s = stringLiteral {exprNode = s;}
| i = intLiteral {exprNode = i;}
| f = floatLiteral {exprNode = f;}
| c = charLiteral {exprNode = c;}
| b = booleanLiteral {exprNode = b;}
;
stringLiteral returns [StringLiteral stringLiteralNode]
: STRING_CONSTANT {
int line=$STRING_CONSTANT.line, offset=$STRING_CONSTANT.pos;
// Remove the outer quotes from the string for storage
String quotedText = $STRING_CONSTANT.text;
assert (quotedText.length() >= 2);
String rawText = quotedText.substring(1, quotedText.length() - 1);
stringLiteralNode = new StringLiteral(line, offset, rawText);
}
;
intLiteral returns [IntLiteral intLiteralNode]
: INTEGER_CONSTANT {
int line=$INTEGER_CONSTANT.line, offset=$INTEGER_CONSTANT.pos;
String valueText = $INTEGER_CONSTANT.text;
int value = Integer.parseInt(valueText);
intLiteralNode = new IntLiteral(line, offset, value);
}
;
floatLiteral returns [FloatLiteral floatLiteralNode]
: FLOAT_CONSTANT {
int line=$FLOAT_CONSTANT.line, offset=$FLOAT_CONSTANT.pos;
String valueText = $FLOAT_CONSTANT.text;
float value = Float.parseFloat(valueText);
floatLiteralNode = new FloatLiteral(line, offset, value);
}
;
charLiteral returns [CharacterLiteral charLiteralNode]
: CHARACTER_CONSTANT {
int line=$CHARACTER_CONSTANT.line, offset=$CHARACTER_CONSTANT.pos;
String valueText = $CHARACTER_CONSTANT.text;
assert valueText.length() == 3;
char value = valueText.charAt(1);
charLiteralNode = new CharacterLiteral(line, offset, value);
}
;
booleanLiteral returns [BooleanLiteral boolLiteralNode]
: TRUE { boolLiteralNode = new BooleanLiteral($TRUE.line, $TRUE.pos, true); }
| FALSE { boolLiteralNode = new BooleanLiteral($FALSE.line, $FALSE.pos, false); }
;
identifier returns [Identifier idNode]
: ID { idNode = new Identifier($ID.text, $ID.line, $ID.pos); }
;
type returns [SimpleTypeNode t]
: TYPE
{
SimpleType simpleType;
switch($TYPE.text) {
case "void":
simpleType = VoidType.INSTANCE;
break;
case "boolean":
simpleType = BooleanType.INSTANCE;
break;
case "int":
simpleType = IntegerType.INSTANCE;
break;
case "float":
simpleType = FloatType.INSTANCE;
break;
case "char":
simpleType = CharacterType.INSTANCE;
break;
case "string":
simpleType = StringType.INSTANCE;
break;
default:
throw new IllegalStateException("Cannot find corresponding type for '" + $TYPE.text + "'");
}
t = new SimpleTypeNode($TYPE.line, $TYPE.pos, simpleType);
}
;
/* Lexer */
// Punctuation
OPEN_PAREN
: '('
;
CLOSE_PAREN
: ')'
;
OPEN_BRACE
: '{'
;
CLOSE_BRACE
: '}'
;
OPEN_BRACKET
: '['
;
CLOSE_BRACKET
: ']'
;
COMMA
: ','
;
SEMICOLON
: ';'
;
EQUAL_ASSIGNMENT
: '='
;
// Operators
EQUAL_COMPARISON
: '=='
;
LESS_THAN
: '<'
;
PLUS
: '+'
;
MINUS
: '-'
;
MULTIPLY
: '*'
;
// Keywords
IF : 'if'
;
ELSE : 'else'
;
WHILE : 'while'
;
PRINT : 'print'
;
PRINTLN : 'println'
;
RETURN : 'return'
;
TRUE : 'true'
;
FALSE : 'false'
;
// Type definitions
TYPE :
'int' |
'float' |
'char' |
'string' |
'boolean' |
'void'
;
// Literal values
INTEGER_CONSTANT
// Note that this allows leading 0's
: DIGIT_FRAGMENT DIGIT_FRAGMENT*
;
FLOAT_CONSTANT
// Note that this allows leading 0's
: DIGIT_FRAGMENT DIGIT_FRAGMENT* '.' DIGIT_FRAGMENT+
;
fragment DIGIT_FRAGMENT
: '0'..'9'
;
STRING_CONSTANT
: '"' CHARACTER_FRAGMENT+ '"' // We do not allow empty strings.
;
CHARACTER_CONSTANT
: '\'' CHARACTER_FRAGMENT '\''
;
fragment CHARACTER_FRAGMENT
: ('a'..'z' | 'A'..'Z' | '0'..'9' | '!' | '_' | ',' | '.' | ':' | '{' | '}' | ' ')
;
/*
* An identifier, shown as id in the grammar, is a sequence
* of letters, digits and the underscore character. An
* identifier cannot start with a digit.
*/
ID : ('a'..'z' | 'A'..'Z' | '_')('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*
;
// These lines match whitespace and comments (and ignore them).
// Ensure they come after all other lexical rules.
WS : ( '\t' | ' ' | ('\r' | '\n') )+ { $channel = HIDDEN;}
;
COMMENT : '//' ~('\r' | '\n')* ('\r' | '\n') { $channel = HIDDEN;}
;