-
Notifications
You must be signed in to change notification settings - Fork 0
/
S1.java
executable file
·568 lines (536 loc) · 15.1 KB
/
S1.java
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// Hand-written S1 compiler
import java.io.*;
import java.util.*;
//======================================================
class S1
{
public static void main(String[] args) throws
IOException
{
System.out.println("S1 compiler written by ...");
if (args.length != 1)
{
System.err.println("Wrong number cmd line args");
System.exit(1);
}
// set to true to debug token manager
boolean debug = false;
// build the input and output file names
String inFileName = args[0] + ".s";
String outFileName = args[0] + ".a";
// construct file objects
Scanner inFile = new Scanner(new File(inFileName));
PrintWriter outFile = new PrintWriter(outFileName);
// identify compiler/author in the output file
outFile.println("; from S1 compiler written by ...");
// construct objects that make up compiler
S1SymTab st = new S1SymTab();
S1TokenMgr tm = new S1TokenMgr(inFile, outFile, debug);
S1CodeGen cg = new S1CodeGen(outFile, st);
S1Parser parser = new S1Parser(st, tm, cg);
// parse and translate
try
{
parser.parse();
}
catch (RuntimeException e)
{
System.err.println(e.getMessage());
outFile.println(e.getMessage());
outFile.close();
System.exit(1);
}
outFile.close();
}
} // end of S1
//======================================================
interface S1Constants
{
// integers that identify token kinds
int EOF = 0;
int PRINTLN = 1;
int UNSIGNED = 2;
int ID = 3;
int ASSIGN = 4;
int SEMICOLON = 5;
int LEFTPAREN = 6;
int RIGHTPAREN = 7;
int PLUS = 8;
int MINUS = 9;
int TIMES = 10;
int ERROR = 11;
// tokenImage provides string for each token kind
String[] tokenImage =
{
"<EOF>",
"\"println\"",
"<UNSIGNED>",
"<ID>",
"\"=\"",
"\";\"",
"\"(\"",
"\")\"",
"\"+\"",
"\"-\"",
"\"*\"",
"<ERROR>"
};
} // end of S1Constants
//======================================================
class S1SymTab
{
private ArrayList<String> symbol;
//-----------------------------------------
public S1SymTab()
{
symbol = new ArrayList<String>();
}
//-----------------------------------------
public void enter(String s)
{
int index = symbol.indexOf(s);
// if s is not in symbol, then add it
if (index < 0)
symbol.add(s);
}
//-----------------------------------------
public String getSymbol(int index)
{
return symbol.get(index);
}
//-----------------------------------------
public int getSize()
{
return symbol.size();
}
} // end of S1SymTab
//======================================================
class S1TokenMgr implements S1Constants
{
private Scanner inFile;
private PrintWriter outFile;
private boolean debug;
private char currentChar;
private int currentColumnNumber;
private int currentLineNumber;
private String inputLine; // holds 1 line of input
private Token token; // holds 1 token
private StringBuffer buffer; // token image built here
//-----------------------------------------
public S1TokenMgr(Scanner inFile,
PrintWriter outFile, boolean debug)
{
this.inFile = inFile;
this.outFile = outFile;
this.debug = debug;
currentChar = '\n'; // '\n' triggers read
currentLineNumber = 0;
buffer = new StringBuffer();
}
//-----------------------------------------
public Token getNextToken()
{
// skip whitespace
while (Character.isWhitespace(currentChar))
getNextChar();
// construct token to be returned to parser
token = new Token();
token.next = null;
// save start-of-token position
token.beginLine = currentLineNumber;
token.beginColumn = currentColumnNumber;
// check for EOF
if (currentChar == EOF)
{
token.image = "<EOF>";
token.endLine = currentLineNumber;
token.endColumn = currentColumnNumber;
token.kind = EOF;
}
else // check for unsigned int
if (Character.isDigit(currentChar))
{
buffer.setLength(0); // clear buffer
do // build token image in buffer
{
buffer.append(currentChar);
token.endLine = currentLineNumber;
token.endColumn = currentColumnNumber;
getNextChar();
} while (Character.isDigit(currentChar));
// save buffer as String in token.image
token.image = buffer.toString();
token.kind = UNSIGNED;
}
else // check for identifier
if (Character.isLetter(currentChar))
{
buffer.setLength(0); // clear buffer
do // build token image in buffer
{
buffer.append(currentChar);
token.endLine = currentLineNumber;
token.endColumn = currentColumnNumber;
getNextChar();
} while (Character.isLetterOrDigit(currentChar));
// save buffer as String in token.image
token.image = buffer.toString();
// check if keyword
if (token.image.equals("println"))
token.kind = PRINTLN;
else // not a keyword so kind is ID
token.kind = ID;
}
else // process single-character token
{
switch(currentChar)
{
case '=':
token.kind = ASSIGN;
break;
case ';':
token.kind = SEMICOLON;
break;
case '(':
token.kind = LEFTPAREN;
break;
case ')':
token.kind = RIGHTPAREN;
break;
case '+':
token.kind = PLUS;
break;
case '-':
token.kind = MINUS;
break;
case '*':
token.kind = TIMES;
break;
default:
token.kind = ERROR;
break;
}
// save currentChar as String in token.image
token.image = Character.toString(currentChar);
// save end-of-token position
token.endLine = currentLineNumber;
token.endColumn = currentColumnNumber;
getNextChar(); // read beyond end of token
}
// token trace appears as comments in output file
if (debug)
outFile.printf(
"; kd=%3d bL=%3d bC=%3d eL=%3d eC=%3d im=%s%n",
token.kind, token.beginLine, token.beginColumn,
token.endLine, token.endColumn, token.image);
return token; // return token to parser
}
//-----------------------------------------
private void getNextChar()
{
if (currentChar == EOF)
return;
if (currentChar == '\n') // need next line?
{
if (inFile.hasNextLine()) // any lines left?
{
inputLine = inFile.nextLine(); // get next line
// output source line as comment
outFile.println("; " + inputLine);
inputLine = inputLine + "\n"; // mark line end
currentColumnNumber = 0;
currentLineNumber++;
}
else // at end of file
{
currentChar = EOF;
return;
}
}
// get next char from inputLine
currentChar =
inputLine.charAt(currentColumnNumber++);
// in S2, test for single-line comment goes here
}
} // end of S1TokenMgr
//======================================================
class S1Parser implements S1Constants
{
private S1SymTab st;
private S1TokenMgr tm;
private S1CodeGen cg;
private Token currentToken;
private Token previousToken;
//-----------------------------------------
public S1Parser(S1SymTab st, S1TokenMgr tm,
S1CodeGen cg)
{
this.st = st;
this.tm = tm;
this.cg = cg;
// prime currentToken with first token
currentToken = tm.getNextToken();
previousToken = null;
}
//-----------------------------------------
// Construct and return an exception that contains
// a message consisting of the image of the current
// token, its location, and the expected tokens.
//
private RuntimeException genEx(String errorMessage)
{
return new RuntimeException("Encountered \"" +
currentToken.image + "\" on line " +
currentToken.beginLine + ", column " +
currentToken.beginColumn + "." +
System.getProperty("line.separator") +
errorMessage);
}
//-----------------------------------------
// Advance currentToken to next token.
//
private void advance()
{
previousToken = currentToken;
// If next token is on token list, advance to it.
if (currentToken.next != null)
currentToken = currentToken.next;
// Otherwise, get next token from token mgr and
// put it on the list.
else
currentToken =
currentToken.next = tm.getNextToken();
}
//-----------------------------------------
// getToken(i) returns ith token without advancing
// in token stream. getToken(0) returns
// previousToken. getToken(1) returns currentToken.
// getToken(2) returns next token, and so on.
//
private Token getToken(int i)
{
if (i <= 0)
return previousToken;
Token t = currentToken;
for (int j = 1; j < i; j++) // loop to ith token
{
// if next token is on token list, move t to it
if (t.next != null)
t = t.next;
// Otherwise, get next token from token mgr and
// put it on the list.
else
t = t.next = tm.getNextToken();
}
return t;
}
//-----------------------------------------
// If the kind of the current token matches the
// expected kind, then consume advances to the next
// token. Otherwise, it throws an exception.
//
private void consume(int expected)
{
if (currentToken.kind == expected)
advance();
else
throw genEx("Expecting " + tokenImage[expected]);
}
//-----------------------------------------
public void parse()
{
program(); // program is start symbol for grammar
}
//-----------------------------------------
private void program()
{
statementList();
cg.endCode();
if (currentToken.kind != EOF) //garbage at end?
throw genEx("Expecting <EOF>");
}
//-----------------------------------------
private void statementList()
{
switch(currentToken.kind)
{
case ID:
case PRINTLN:
statement();
statementList();
break;
case EOF:
;
break;
default:
throw genEx("Expecting statement or <EOF>");
}
}
//-----------------------------------------
private void statement()
{
switch(currentToken.kind)
{
case ID:
assignmentStatement();
break;
case PRINTLN:
printlnStatement();
break;
default:
throw genEx("Expecting statement");
}
}
//-----------------------------------------
private void assignmentStatement()
{
Token t;
t = currentToken;
consume(ID);
st.enter(t.image);
cg.emitInstruction("pc", t.image);
consume(ASSIGN);
expr();
cg.emitInstruction("stav");
consume(SEMICOLON);
}
//-----------------------------------------
private void printlnStatement()
{
consume(PRINTLN);
consume(LEFTPAREN);
expr();
cg.emitInstruction("dout");
cg.emitInstruction("pc", "'\\n'");
cg.emitInstruction("aout");
consume(RIGHTPAREN);
consume(SEMICOLON);
}
//-----------------------------------------
private void expr()
{
term();
termList();
}
//-----------------------------------------
private void termList()
{
switch(currentToken.kind)
{
case PLUS:
consume(PLUS);
term();
cg.emitInstruction("add");
termList();
break;
case RIGHTPAREN:
case SEMICOLON:
;
break;
default:
throw genEx("Expecting \"+\", \")\", or \";\"");
}
}
//-----------------------------------------
private void term()
{
factor();
factorList();
}
//-----------------------------------------
private void factorList()
{
switch(currentToken.kind)
{
case TIMES:
consume(TIMES);
factor();
cg.emitInstruction("mult");
factorList();
break;
case PLUS:
case RIGHTPAREN:
case SEMICOLON:
;
break;
default:
throw genEx("Expecting op, \")\", or \";\"");
}
}
//-----------------------------------------
private void factor()
{
Token t;
switch(currentToken.kind)
{
case UNSIGNED:
t = currentToken;
consume(UNSIGNED);
cg.emitInstruction("pwc", t.image);
break;
case PLUS:
consume(PLUS);
t = currentToken;
consume(UNSIGNED);
cg.emitInstruction("pwc", t.image);
break;
case MINUS:
consume(MINUS);
t = currentToken;
consume(UNSIGNED);
cg.emitInstruction("pwc", "-" + t.image);
break;
case ID:
t = currentToken;
consume(ID);
st.enter(t.image);
cg.emitInstruction("p", t.image);
break;
case LEFTPAREN:
consume(LEFTPAREN);
expr();
consume(RIGHTPAREN);
break;
default:
throw genEx("Expecting factor");
}
}
} // end of S1Parser
//======================================================
class S1CodeGen
{
private PrintWriter outFile;
private S1SymTab st;
//-----------------------------------------
public S1CodeGen(PrintWriter outFile, S1SymTab st)
{
this.outFile = outFile;
this.st = st;
}
//-----------------------------------------
public void emitInstruction(String op)
{
outFile.printf(" %-4s%n", op);
}
//-----------------------------------------
public void emitInstruction(String op, String opnd)
{
outFile.printf(" %-4s %s%n", op,opnd);
}
//-----------------------------------------
private void emitdw(String label, String value)
{
outFile.printf(
"%-9s dw %s%n", label + ":", value);
}
//-----------------------------------------
public void endCode()
{
outFile.println();
emitInstruction("halt");
int size = st.getSize();
// emit dw for each symbol in the symbol table
for (int i=0; i < size; i++)
emitdw(st.getSymbol(i), "0");
}
} // end of S1CodeGen