Nand2Tetris_Part2_11

Going on ✈

Unit 11.1 Compiler II: Code Generation

roadmap

Program compilation:

  • Each class is compiled separately
  • There two compilation tasks are relatively separate and standalone:
    • class-level code
    • subroutine-level code(constructors, methods, functions)

Compilation challenges:

  • Handling variables
  • Handling expressions
  • Handling flow of control
  • Handling objects
  • Handling arrays

The challenge: expressiong the above semantics in the VM language.

Unit 11.2 Handling Variables

In order to generate actual VM code, we must know(among other things):

  • whether each variable is field, static, local or argument
  • whether each variable is the first, second, third… variable of it’s kind

All the possible variables in Jack:

  • class-level variables: field, static
  • subroutine-level variables: argument, local

About variable properties(in Jack):

  • name(identifier)
  • type(int, char, boolean, class name)
  • kind(field, static, local, argument)
  • scope(class level, subroutine level)

symboltable

🎈 When you compile anything in Jack, you always have to maintain just two symbol tables: the class-level symbol table and the subroutine-level symbol table. And the codewriter will add the variable and it’s properties to the symbol table.

handling_variable

symboltable_usage

handling_nested_scoping

✨ This is something that we don’t need at all when we write the compiler for the Jack, because in jack we have only two symbol tables.

Unit 11.3 Handlding Expressions

Generating code for expressions: a two-stage approach

1
2
              parse              code generation
source code --------> parse tree ----------------> stack-machine code

When executed, the generated code ends up leaving the value of the expression at the top of the stack.

🎉 What we use:
codewrite

🎃 Attention:

  • The Jack language defines no operator priority(except for parentheses)
  • The order priority is left up to the compiler’s developer
  • Parentheses can always be used to enforce operator priority

Unit 11.4 Handling Flow of Control

if

while

A program typically contains multiple if and while statements.
Soultion: the compiler can ensure that generated label are unique.

The f and while statements are often nested.
Soultion: the compiler employs a recursive compilation startegy.

Unit 11.5 Handling Objects: Low-Level Aspects

A. Handling local and argument variables

local, argument:

  • respresent local and argument variables
  • located on the stack

Implementation:

  • Base address: LCL and ARG
  • Managed by the VM implementation

B. Handling object and array data

this, that:

  • represent object and array data
  • located on the heap

Implementation:

  • Base address: THIS and THAT
  • Set using pointer 0(this) and pointer 1(that)
  • Managed by VM code

access_ram

  • Obecjt data is accessed via the this segment
  • Array data is accessed via the that segment
  • Before we use these segments, we must first anchor them using pointer

Unit 11.6 Handling Objects: Construction

A. The caller’s side: compiling new

For declaration: The compiler updates the subroutine’s symbol table, and no code is generated.
For new: The caller assumes that the constructor’s code:

  • arranges a memory block to store the new object
  • returns it’s base address to the caller

B. Object construction: the big picture

A constructor typically does two things:

  • Arranges the creation of a new object
  • Initializes the new object to some initial state

Therefore, the constructor’s code typically needs access to the object’s fields. And how to access the object’s fields:

  • The constructor’s code can access the object’s data using the this segment
  • But first, the constructor’s code must anchor the this segment on the object’s data, using pointer

constructor_1

constructor_2

Unit 11.7 Handling Objects: Manipulation

A. Compiling method calls

The object is always treated as the first, implicit argument.

1
2
3
4
5
6
7
8
9
10
// OOP languange
p1.distance(p2);
p1.getx();
obj.foo(x1, x2);
// |
// V
// Procedural language
distance(p1, p2);
getx(p1);
foo(obj, x1, x2);

method_1

B. Compiling methods

Method are designed to operate on the current object(this). Therefore, each method’s code needs access to the object’s fields. And how to access the object’s fields:

  • The method’s code can access the object’s i-th field by accessing this i
  • But first, the method’s code must anchor the this segment on the object’s data, using pointer

method_2

C. Compiling void methods

void_method1

void_method2

Unit 11.8 Handling Arrays

Array construction

Code generation:

  • var Array arr;: generate no code; only effects the symbol table.
  • let arr = Array.new(n);: from the caller’s perspective, handled exactly like object construction.

Array manipulation

this&that

Array access

array

Unit 11.9 Standard Mapping Over the Virtual Machine

A. Files and subroutines mapping

mapping_1

B. Variables mapping

mapping_2

C. Arrays mapping

mapping_3

D. Compiling subroutines

mapping_4

E. Compiling subroutine calls

mapping_5

F. Compiling constants

mapping_6

G. OS classes and subroutines

mapping_7

H. Special OS services

mapping_8

Unit Completing the compiler: Proposed Implementation

A. JackCompiler

JackCompiler_usage

B. SymbolTable

symboltable_imp1

symboltable_imp2

C. VMWriter

vmwriter_imp1

See the book for API informations.

PS: The JackTokenizer and CompilationEngine are very similar to what we did in project 10, so we won’t elaborate it again.

Unit 11.11 Project 11

Project 11: extend the syntax analyzer into a full-scale compiler.

Here is the code:

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <stdexcept>
using namespace std;

#include "jackcompiler.h"

int main(int argc, char** argv) {
if(argc != 2) {
cerr << "Input error!\nUsage: .\\JackCompiler.exe [filename or filepath]" << endl;
return 0;
}
try {
string path(argv[1]);
JackCompiler jCompiler(path);
jCompiler.doCompiling();
} catch(exception& e) {
cerr << e.what() << endl;
}

return 0;
}

✅ main.cpp: the file is very similar with another file which is same name in project 10.

jacktokenizer.h
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
#ifndef __JACK_TOKENIZER_H__
#define __JACK_TOKENIZER_H__

#include <string>
#include <sstream>

using namespace std;

class JackTokenizer {
public:
enum TokenType {
T_UNKNOWN,
T_KEYWORD,
T_SYMBOL,
T_IDENTIFIER,
T_INT_CONST,
T_STRING_CONST,
};
public:
JackTokenizer(const string& filepath);
bool hasMoreTokens();
void advance();
TokenType tokenType();
string keyword();
char symbol();
string identifier();
int intVal();
string stringVal();

string getCurToken() const;

private:
stringstream m_iss;
string m_curToken;
};

#endif
jacktokenizer.cpp
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
#include "jacktokenizer.h"

#include <iostream>
#include <fstream>
#include <regex>
#include <unordered_set>

static unordered_set<char> s_symbols = {
'{', '}', '(', ')', '[', ']',
'.', ',', ';',
'+', '-', '*', '/',
'&', '|', '<', '>', '=', '~',
};

static unordered_set<string> s_keywords = {
"class", "method", "int", "function",
"boolean", "constructor", "char",
"void", "var", "static", "field",
"let", "do", "if", "else", "while",
"return", "true", "false", "null",
"this",
};

static string removeComments(const string& source) {
enum State {
NORMAL,
IN_STRING,
IN_SINGLE_LINE_COMMENT,
IN_MULT_LINE_COMMENT,
};
State state = NORMAL;
string result;
size_t i = 0;
size_t len = source.length();

while(i < len) {
char current = source[i];
char next = (i + 1 < len) ? source[i + 1] : '\0';
switch(state) {
case NORMAL:
if(current == '"') {
result += current;
state = IN_STRING;
} else if(current == '/' && next == '/') {
state = IN_SINGLE_LINE_COMMENT;
++i;
} else if(current == '/' && next == '*') {
state = IN_MULT_LINE_COMMENT;
++i;
} else {
result += current;
}
break;
case IN_STRING:
result += current;
if(current == '"' && source[i - 1] != '\\') {
state = NORMAL;
}
break;
case IN_SINGLE_LINE_COMMENT:
if(current == '\n') {
result += '\n';
state = NORMAL;
}
break;
case IN_MULT_LINE_COMMENT:
if(current == '*' && next == '/') {
state = NORMAL;
++i;
}
break;
}
++i;
}

regex endl_re("\\r*\\n+");
regex space_re("\\s+");
regex tailSpace_re("\\s+$");
result = regex_replace(result, endl_re, "");
result = regex_replace(result, space_re, " ");
result = regex_replace(result, tailSpace_re, "");

return result;
}

JackTokenizer::JackTokenizer(const string& filepath) {
ifstream ifs(filepath);
if(!ifs) {
throw runtime_error("JackTokenizer fails to open file: " + filepath);
}
string src_code((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());
ifs.close();
string dst_code = removeComments(src_code);
m_iss << dst_code;
}

bool JackTokenizer::hasMoreTokens() {
return !m_iss.eof() && m_iss.peek() != EOF;
}

void JackTokenizer::advance() {
if(!hasMoreTokens()) {
throw runtime_error("JackTokenizer: expected a token");
return;
}

m_curToken.clear();
while(hasMoreTokens()) {
char next = m_iss.peek();
if(isalnum(next) || next == '"') {
m_curToken.push_back(m_iss.get());
if(m_curToken[0] == '"') {
while(hasMoreTokens()) {
char c = m_iss.get();
m_curToken.push_back(c);
if(c == '"')
break;
}
}
} else if(next == ' ') {
m_iss.get();
if(!m_curToken.empty())
break;
} else if(s_symbols.count(next)) {
if(m_curToken.empty())
m_curToken.push_back(m_iss.get());
break;
}
}
}

JackTokenizer::TokenType JackTokenizer::tokenType() {
TokenType ret = T_UNKNOWN;
if(m_curToken.empty())
return ret;
else if(s_symbols.count(m_curToken[0]))
ret = T_SYMBOL;
else if(s_keywords.count(m_curToken))
ret = T_KEYWORD;
else if(all_of(m_curToken.begin(), m_curToken.end(), [](char c) { return isdigit(c); }))
ret = T_INT_CONST;
else if(m_curToken[0] == '"')
ret = T_STRING_CONST;
else
ret = T_IDENTIFIER;
return ret;
}

string JackTokenizer::keyword() {
return m_curToken;
}

char JackTokenizer::symbol() {
return m_curToken[0];
}

string JackTokenizer::identifier() {
return m_curToken;
}

int JackTokenizer::intVal() {
return stoi(m_curToken);
}

string JackTokenizer::stringVal() {
return m_curToken.substr(1, m_curToken.length() - 2);
}

string JackTokenizer::getCurToken() const {
return m_curToken;
}

✅ jacktokenizer module: no more changes.

compilationengine.h
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
#ifndef __COMPILATION_ENGINE_H__
#define __COMPILATION_ENGINE_H__


#include <fstream>

#include "jacktokenizer.h"
#include "symboltable.h"
#include "vmwriter.h"

using namespace std;

class CompilationEngine {
public:
CompilationEngine(const string& input, const string& output);

private:
bool isSymbol(char c);
bool isSubroutine();
bool isType();
VMWriter::VMSegment variableKindToVMSegment(SymbolTable::VariableKind v);

void compileClass();
void compileClassVarDec();
void compileSubroutine();
void compileParameterList();
void compileVarDec();
void compileStatements();
void compileDo();
void compileLet();
void compileWhile();
void compileReturn();
void compileIf();
void compileExpression();
void compileTerm();
int compileExpressionList();

private:
JackTokenizer m_tokenizer;
SymbolTable m_symboltable;
VMWriter m_vmwriter;

string m_className;
};

#endif
compilationengine.cpp
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
#include "compilationengine.h"

#include <iostream>
#include <stdexcept>
#include <unordered_set>
#include <unordered_map>

static unordered_map<string, int> s_OSAPI = {
{"Math.multiply", 2}, {"Math.divide", 2},
{"String.new", 1}, {"String.appendchar", 1},
{"Output.printInt", 1},
{"Memory.alloc", 1}, {"Memory.peek", 1},
{"Keyboard.readInt", 1}, {"Keyboard.keyPressed", 0},
{"Array.new", 1}, {"Array.dispose", 0},
{"String.new", 1}, {"String.dispose", 1}, {"String.length", 1},
{"String.charAt", 2}, {"String.setCharAt", 3},{"String.appendChar", 2},
};

static int s_whileLabelCount = 0;
static int s_ifLabelCount = 0;

CompilationEngine::CompilationEngine(const string& input, const string& output)
: m_tokenizer(input), m_vmwriter(output) {
if(!m_tokenizer.hasMoreTokens())
throw(runtime_error("The input file is empty"));

m_tokenizer.advance();

if(m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD
&& m_tokenizer.keyword() == "class") {
compileClass();
} else {
throw(runtime_error("The first keyword is not class"));
}
}

bool CompilationEngine::isSymbol(char c) {
return m_tokenizer.tokenType() == JackTokenizer::T_SYMBOL &&
m_tokenizer.symbol() == c;
}

bool CompilationEngine::isSubroutine() {
return m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD &&
(m_tokenizer.keyword() == "constructor" ||
m_tokenizer.keyword() == "function" ||
m_tokenizer.keyword() == "method");
}

bool CompilationEngine::isType() {
return m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER ||
(m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD &&
(m_tokenizer.keyword() == "int" ||
m_tokenizer.keyword() == "char" ||
m_tokenizer.keyword() == "boolean"));
}

VMWriter::VMSegment CompilationEngine::variableKindToVMSegment(SymbolTable::VariableKind v) {
VMWriter::VMSegment ret = VMWriter::S_UNKNOWN;
if(v == SymbolTable::V_STATIC) {
ret = VMWriter::S_STATIC;
} else if(v == SymbolTable::V_FIELD) {
ret = VMWriter::S_THIS;
} else if(v == SymbolTable::V_ARG) {
ret = VMWriter::S_ARG;
} else if(v == SymbolTable::V_VAR) {
ret = VMWriter::S_LOCAL;
}
return ret;
}

void CompilationEngine::compileClass() {
// class className { classVarDec* subroutineDec* }
m_tokenizer.advance();
if(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
m_className = m_tokenizer.getCurToken();
m_tokenizer.advance();
} else {
throw runtime_error("(class)expected className");
}
if(isSymbol('{')) {
m_tokenizer.advance();
} else {
throw runtime_error("(class)expected '{'");
}
// classVarDec*
compileClassVarDec();
// subroutineDec*
compileSubroutine();
if(!isSymbol('}')) {
throw runtime_error("(class)expected '}'");
}
}

void CompilationEngine::compileClassVarDec() {
while(m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD &&
(m_tokenizer.keyword() == "static" ||
m_tokenizer.keyword() == "field")) {
// (static | field) type varName (, varName)*;
// static | field
SymbolTable::VariableKind vkind = SymbolTable::V_NONE;
if(m_tokenizer.getCurToken() == "static") {
vkind = SymbolTable::V_STATIC;
} else if(m_tokenizer.getCurToken() == "field") {
vkind = SymbolTable::V_FIELD;
}
m_tokenizer.advance();
// type
string vtype;
if(isType()) {
vtype = m_tokenizer.getCurToken();
m_tokenizer.advance();
} else {
throw runtime_error("(classVarDec)expected type");
}
// varName(, varName)*
while(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
m_symboltable.define(m_tokenizer.getCurToken(), vtype, vkind);
m_tokenizer.advance();
if(isSymbol(',')) {
m_tokenizer.advance();
}
}
// ;
if(isSymbol(';')) {
m_tokenizer.advance();
} else {
throw runtime_error("(classVarDec)expected ';'");
}
}
}

void CompilationEngine::compileSubroutine() {
// (constructor | function | method)
// (void | type) subroutineName ( parameterList )
// subroutineBody
// (constructor | function | method)
while(isSubroutine()) {
m_symboltable.startSubroutine();
s_whileLabelCount = 0;
s_ifLabelCount = 0;
// 1 - method, 2 - constructor, else - function
int sType = 0;
if(m_tokenizer.getCurToken() == "method") {
m_symboltable.define("this", m_className, SymbolTable::V_ARG);
sType = 1;
} else if(m_tokenizer.getCurToken() == "constructor") {
sType = 2;
} else if(m_tokenizer.getCurToken() == "function") {
sType = 3;
} else {
throw runtime_error("(subroutineDec)expected method, constructor or function");
}
m_tokenizer.advance();
// void | type
if((m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD && m_tokenizer.keyword() == "void") ||
isType()) {
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineDec)expected type");
}
// subroutineName
string sName;
if(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
sName = m_tokenizer.getCurToken();
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineDec)expected subroutineName");
}
if(isSymbol('(')) {
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineDec)expected '('");
}
// parameterList
compileParameterList();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineDec)expected ')'");
}
// subroutineBody
// { varDec* statements }
if(isSymbol('{')) {
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineBody)expected '{'");
}
// varDec*
compileVarDec();
// 1 - method, 2 - constructor, 3 - function
m_vmwriter.writeFunction(m_className + "." + sName, m_symboltable.varCount(SymbolTable::V_VAR));
if(sType == 1) {
m_vmwriter.writePush(VMWriter::S_ARG, 0);
m_vmwriter.writePop(VMWriter::S_POINTER, 0);
} else if(sType == 2) {
m_vmwriter.writePush(VMWriter::S_CONST, m_symboltable.varCount(SymbolTable::V_FIELD));
m_vmwriter.writeCall("Memory.alloc", s_OSAPI["Memory.alloc"]);
m_vmwriter.writePop(VMWriter::S_POINTER, 0);
}
// statements
compileStatements();
if(isSymbol('}')) {
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineBody)expected '}'");
}
// m_symboltable.print();
}
}

void CompilationEngine::compileParameterList() {
// ((type varName)(, type varName)*)? ;
while(isType()) {
// type
string vtype = m_tokenizer.getCurToken();
m_tokenizer.advance();
// varName
if(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
m_symboltable.define(m_tokenizer.getCurToken(), vtype, SymbolTable::V_ARG);
m_tokenizer.advance();
// ,
if(isSymbol(',')) {
m_tokenizer.advance();
} else {
break;
}
} else {
throw runtime_error("(parameterList)expected varName");
}
}
}

void CompilationEngine::compileVarDec() {
// var type varName (, varName)* ;
while(m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD &&
m_tokenizer.keyword() == "var") {
m_tokenizer.advance();
string vtype;
if(isType()) {
vtype = m_tokenizer.getCurToken();
m_tokenizer.advance();
} else {
throw runtime_error("(VarDec)expected type");
}
while(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
m_symboltable.define(m_tokenizer.getCurToken(), vtype, SymbolTable::V_VAR);
m_tokenizer.advance();
if(isSymbol(',')) {
m_tokenizer.advance();
} else {
break;
}
}
if(isSymbol(';')) {
m_tokenizer.advance();
} else {
throw runtime_error("(VarDec)expected ';'");
}
}
}

void CompilationEngine::compileStatements() {
while(m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD) {
if(m_tokenizer.keyword() == "let") {
compileLet();
} else if(m_tokenizer.keyword() == "if") {
compileIf();
} else if(m_tokenizer.keyword() == "while") {
compileWhile();
} else if(m_tokenizer.keyword() == "do") {
compileDo();
} else if(m_tokenizer.keyword() == "return") {
compileReturn();
} else {
throw runtime_error("(statements)expected let or if or while or do or return");
break;
}
}
}

void CompilationEngine::compileDo() {
// do subroutineCall ;
m_tokenizer.advance();
// subroutineName | className | varName
string subName;
string classOrVarName;
if(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
subName = m_tokenizer.getCurToken();
classOrVarName = m_tokenizer.getCurToken();
m_tokenizer.advance();
} else {
throw runtime_error("(Do)expected subroutineName");
}
if(isSymbol('(')) {
// subroutimeName(expressionList)
m_tokenizer.advance();
m_vmwriter.writePush(VMWriter::S_POINTER, 0);
int nArgs = compileExpressionList();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(SubroutineCall)expected ')'");
}
m_vmwriter.writeCall(m_className + "." + subName, nArgs + 1);
} else if(isSymbol('.')) {
// className/varName.subroutineName(expressionList)
int nArgs = 0;
if(m_symboltable.exist(classOrVarName)) {
++nArgs;
subName = m_symboltable.typeOf(classOrVarName);
SymbolTable::VariableKind vk = m_symboltable.kindOf(classOrVarName);
int index = m_symboltable.indexOf(classOrVarName);
VMWriter::VMSegment vs = variableKindToVMSegment(vk);
m_vmwriter.writePush(vs, index);
}
subName.append(".");
m_tokenizer.advance();
if(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
subName.append(m_tokenizer.getCurToken());
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineCall)expected 'subroutineName'");
}
if(isSymbol('(')) {
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineCall)expected '('");
}
nArgs += compileExpressionList();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(subroutineCall)expected ')'");
}
if(s_OSAPI.count(subName)) {
nArgs = s_OSAPI[subName];
}
m_vmwriter.writeCall(subName, nArgs);
} else {
throw runtime_error("(subroutineCall)expected '(' or '.'");
}
m_vmwriter.writePop(VMWriter::S_TEMP, 0);
if(isSymbol(';')) {
m_tokenizer.advance();
} else {
throw runtime_error("(Do)expected ';'");
}
}

void CompilationEngine::compileLet() {
// let varName ([expression])? = expression;
m_tokenizer.advance();
string vName;
if(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
vName = m_tokenizer.getCurToken();
m_tokenizer.advance();
} else {
throw runtime_error("(Let)expected varName");
}
// ([expression])?
if(isSymbol('[')) {
m_tokenizer.advance();
compileExpression();
if(isSymbol(']')) {
m_tokenizer.advance();
} else {
throw runtime_error("(Let)expected ']'");
}
SymbolTable::VariableKind vk = m_symboltable.kindOf(vName);
int index = m_symboltable.indexOf(vName);
VMWriter::VMSegment vs = variableKindToVMSegment(vk);
m_vmwriter.writePush(vs, index);
m_vmwriter.wirteArithmetic("add");
vName.append("[]");
}
if(isSymbol('=')) {
m_tokenizer.advance();
} else {
throw runtime_error("(Let)expected '='");
}
compileExpression();
if(isSymbol(';')) {
m_tokenizer.advance();
} else {
throw runtime_error("(Let)expected ';'");
}
SymbolTable::VariableKind vk = m_symboltable.kindOf(vName);
if(vk != SymbolTable::V_NONE) {
m_vmwriter.writePop(variableKindToVMSegment(vk), m_symboltable.indexOf(vName));
} else {
m_vmwriter.writePop(VMWriter::S_TEMP, 0);
m_vmwriter.writePop(VMWriter::S_POINTER, 1);
m_vmwriter.writePush(VMWriter::S_TEMP, 0);
m_vmwriter.writePop(VMWriter::S_THAT, 0);
}
}

void CompilationEngine::compileWhile() {
string L1 = "WHILE_EXP" + to_string(s_whileLabelCount);
string L2 = "WHILE_END" + to_string(s_whileLabelCount);
++s_whileLabelCount;

// while ( expression ) { statements }
m_tokenizer.advance();
m_vmwriter.writeLabel(L1);
if(isSymbol('(')) {
m_tokenizer.advance();
} else {
throw runtime_error("(While)expected '('");
}
compileExpression();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(While)expected ')'");
}
m_vmwriter.wirteArithmetic("not");
m_vmwriter.writeIf(L2);
if(isSymbol('{')) {
m_tokenizer.advance();
} else {
throw runtime_error("(While)expected '{'");
}
compileStatements();
m_vmwriter.writeGoto(L1);
m_vmwriter.writeLabel(L2);
if(isSymbol('}')) {
m_tokenizer.advance();
} else {
throw runtime_error("(While)expected '}'");
}
}

void CompilationEngine::compileReturn() {
// return expression? ;
m_tokenizer.advance();
bool voidFlag = true;
if(!isSymbol(';')) {
voidFlag = false;
compileExpression();
}
if(voidFlag) {
m_vmwriter.writePush(VMWriter::S_CONST, 0);
}
if(isSymbol(';')) {
m_tokenizer.advance();
} else {
throw runtime_error("(Return)expected ';'");
}
m_vmwriter.writeReturn();
}

void CompilationEngine::compileIf() {
string L1 = "IF_TRUE" + to_string(s_ifLabelCount);
string L2 = "IF_FALSE" + to_string(s_ifLabelCount);
++s_ifLabelCount;

// if ( expression ) { statements } (else { statelemtns })?
m_tokenizer.advance();
if(isSymbol('(')) {
m_tokenizer.advance();
} else {
throw runtime_error("(If)expected '('");
}
compileExpression();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(If)expected ')'");
}
m_vmwriter.wirteArithmetic("not");
m_vmwriter.writeIf(L1);
if(isSymbol('{')) {
m_tokenizer.advance();
} else {
throw runtime_error("(If)expected '{'");
}
compileStatements();
if(isSymbol('}')) {
m_tokenizer.advance();
} else {
throw runtime_error("(If)expected '}'");
}
m_vmwriter.writeGoto(L2);
m_vmwriter.writeLabel(L1);
// (else { statements })?
if(m_tokenizer.tokenType() == JackTokenizer::T_KEYWORD &&
m_tokenizer.keyword() == "else") {
m_tokenizer.advance();
if(isSymbol('{')) {
m_tokenizer.advance();
} else {
throw runtime_error("(If-else)expected '{'");
}
compileStatements();
if(isSymbol('}')) {
m_tokenizer.advance();
} else {
throw runtime_error("(If-else)expected '}'");
}
}
m_vmwriter.writeLabel(L2);
}

void CompilationEngine::compileExpression() {
static unordered_map<char, string> s_op = {
{'+', "add"}, {'-', "sub"}, {'*', "Math.multiply"}, {'/', "Math.divide"},
{'&', "and"}, {'|', "or"},
{'<', "lt"}, {'>', "gt"}, {'=', "eq"},
};
// term (op term)*
// term
compileTerm();
// op term
while(m_tokenizer.tokenType() == JackTokenizer::T_SYMBOL &&
s_op.count(m_tokenizer.symbol())) {
char op = m_tokenizer.getCurToken()[0];
m_tokenizer.advance();
compileTerm();
if(op == '*' || op == '/') {
m_vmwriter.writeCall(s_op[op], s_OSAPI[s_op[op]]);
} else if(s_op.count(op)) {
m_vmwriter.wirteArithmetic(s_op[op]);
}
}
}

void CompilationEngine::compileTerm() {
// integerConstant | stringConstant | keywordConstant |
// varName | varName [expression] | subroutineCall |
// (expression) | unaryOp term
JackTokenizer::TokenType tt = m_tokenizer.tokenType();
if(tt == JackTokenizer::T_INT_CONST) {
// integerConstant
m_vmwriter.writePush(VMWriter::S_CONST, stoi(m_tokenizer.getCurToken()));
m_tokenizer.advance();
} else if(tt == JackTokenizer::T_STRING_CONST) {
string sConst = m_tokenizer.getCurToken();
sConst = sConst.substr(1, sConst.length() - 2);
m_vmwriter.writePush(VMWriter::S_CONST, sConst.length());
m_vmwriter.writeCall("String.new", s_OSAPI["String.new"]);
for(char c: sConst) {
m_vmwriter.writePush(VMWriter::S_CONST, static_cast<int>(c));
m_vmwriter.writeCall("String.appendChar", s_OSAPI["String.appendChar"]);
}
m_tokenizer.advance();
} else if(tt == JackTokenizer::T_KEYWORD) {
// keywordConstant
if(m_tokenizer.keyword() == "true") {
m_vmwriter.writePush(VMWriter::S_CONST, 0);
m_vmwriter.wirteArithmetic("not");
} else if(m_tokenizer.keyword() == "false" || m_tokenizer.keyword() == "null") {
m_vmwriter.writePush(VMWriter::S_CONST, 0);
} else if(m_tokenizer.keyword() == "this") {
m_vmwriter.writePush(VMWriter::S_POINTER, 0);
} else {
throw runtime_error("(term)expected keyword: true, false, null or this");
}
m_tokenizer.advance();
} else if(tt == JackTokenizer::T_IDENTIFIER) {
// varName | subroutineName
string name = m_tokenizer.getCurToken();
m_tokenizer.advance();
if(m_tokenizer.tokenType() == JackTokenizer::T_SYMBOL) {
// [expression]
if(m_tokenizer.symbol() != '[') {
SymbolTable::VariableKind vk = m_symboltable.kindOf(name);
if(vk != SymbolTable::V_NONE) {
m_vmwriter.writePush(variableKindToVMSegment(vk), m_symboltable.indexOf(name));
}
}
if(m_tokenizer.symbol() == '[') {
m_tokenizer.advance();
compileExpression();
if(isSymbol(']')) {
m_tokenizer.advance();
} else {
throw runtime_error("(term)expected ']");
}
SymbolTable::VariableKind vk = m_symboltable.kindOf(name);
if(vk != SymbolTable::V_NONE) {
m_vmwriter.writePush(variableKindToVMSegment(vk), m_symboltable.indexOf(name));
}
m_vmwriter.wirteArithmetic("add");
m_vmwriter.writePop(VMWriter::S_POINTER, 1);
m_vmwriter.writePush(VMWriter::S_THAT, 0);
} else if(m_tokenizer.symbol() == '(') {
// (expressionList)
m_tokenizer.advance();
int nArgs = compileExpressionList();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(term)expected ')'");
}
m_vmwriter.writeCall(name, nArgs);
} else if(m_tokenizer.symbol() == '.') {
int nArgs = 0;
if(m_symboltable.exist(name)) {
name = m_symboltable.typeOf(name);
nArgs += 1;
}
// . soubroutineName ( expressionList )
// .
name.append(m_tokenizer.getCurToken());
m_tokenizer.advance();
if(m_tokenizer.tokenType() == JackTokenizer::T_IDENTIFIER) {
name.append(m_tokenizer.getCurToken());
m_tokenizer.advance();
} else {
throw runtime_error("(term)expected subroutineName");
}
if(isSymbol('(')) {
m_tokenizer.advance();
} else {
throw runtime_error("(term)expected '('");
}
// expressionList
nArgs += compileExpressionList();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(term)expected ')'");
}
if(s_OSAPI.count(name)) {
nArgs = s_OSAPI[name];
}
m_vmwriter.writeCall(name, nArgs);
}
}
} else if(tt == JackTokenizer::T_SYMBOL) {
// ( expression )
if(m_tokenizer.symbol() == '(') {
m_tokenizer.advance();
compileExpression();
if(isSymbol(')')) {
m_tokenizer.advance();
} else {
throw runtime_error("(term)expected ')'");
}
} else if(m_tokenizer.symbol() == '-' ||
m_tokenizer.symbol() == '~') {
// unaryOp term
char unaryOp = m_tokenizer.symbol();
m_tokenizer.advance();
compileTerm();
if(unaryOp == '-') {
m_vmwriter.wirteArithmetic("neg");
} else if(unaryOp == '~') {
m_vmwriter.wirteArithmetic("not");
} else {
throw runtime_error("(term)Unknown unary op: " + unaryOp);
}
}
}
}

int CompilationEngine::compileExpressionList() {
int cnt = 0;
if(!isSymbol(')')) {
compileExpression();
++cnt;
while(isSymbol(',')) {
// ,
m_tokenizer.advance();
// expression
compileExpression();
++cnt;
}
}
return cnt;
}

✅ compilationengine module: change some API, but the basic logic has not changed much.

symboltable.h
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
#ifndef __SYMBOL_TABLE_H__
#define __SYMBOL_TABLE_H__

#include <unordered_map>
#include <tuple>
using namespace std;


class SymbolTable {
public:
enum VariableKind {
V_NONE,
V_STATIC,
V_FIELD,
V_ARG,
V_VAR,
};
public:
SymbolTable();
void startSubroutine();
void define(const string& name, const string& type, VariableKind v);
int varCount(VariableKind v);
VariableKind kindOf(const string& name);
string typeOf(const string& name);
int indexOf(const string& name);

void print();
bool exist(const string& name);

private:
unordered_map<string, tuple<string, VariableKind, size_t>> m_classSymbolTable;
unordered_map<string, tuple<string, VariableKind, size_t>> m_subroutineSymbolTabel;
size_t m_classFieldIndex;
size_t m_classStaticIndex;
size_t m_subroutineArgIndex;
size_t m_subroutineLocalIndex;

};

#endif
symboltable.cpp
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
#include "symboltable.h"

#include <iostream>


SymbolTable::SymbolTable()
: m_classFieldIndex(0)
, m_classStaticIndex(0)
, m_subroutineArgIndex(0)
, m_subroutineLocalIndex(0) {
}

void SymbolTable::startSubroutine() {
m_subroutineSymbolTabel.clear();
m_subroutineArgIndex = 0;
m_subroutineLocalIndex = 0;
}

void SymbolTable::define(const string& name, const string& type, VariableKind v) {
if(v == V_FIELD) {
m_classSymbolTable[name] = make_tuple(type, v, m_classFieldIndex++);
}
if(v == V_STATIC) {
m_classSymbolTable[name] = make_tuple(type, v, m_classStaticIndex++);
}
if(v == V_ARG) {
m_subroutineSymbolTabel[name] = make_tuple(type, v, m_subroutineArgIndex++);
}
if(v == V_VAR) {
m_subroutineSymbolTabel[name] = make_tuple(type, v, m_subroutineLocalIndex++);
}
}

int SymbolTable::varCount(VariableKind v) {
int ret = 0;
if(v == V_STATIC || v == V_FIELD) {
for(auto& p: m_classSymbolTable) {
if(v == get<1>(p.second))
++ret;
}
}
if(v == V_ARG || v == V_VAR) {
for(auto& p: m_subroutineSymbolTabel) {
if(v == get<1>(p.second))
++ret;
}
}
return ret;
}

SymbolTable::VariableKind SymbolTable::kindOf(const string& name) {
if(m_subroutineSymbolTabel.count(name)) {
return get<1>(m_subroutineSymbolTabel[name]);
}
if(m_classSymbolTable.count(name)) {
return get<1>(m_classSymbolTable[name]);
}
return V_NONE;
}

string SymbolTable::typeOf(const string& name) {
if(m_subroutineSymbolTabel.count(name)) {
return get<0>(m_subroutineSymbolTabel[name]);
}
if(m_classSymbolTable.count(name)) {
return get<0>(m_classSymbolTable[name]);
}
return "unkonwn";
}

int SymbolTable::indexOf(const string& name) {
if(m_subroutineSymbolTabel.count(name)) {
return get<2>(m_subroutineSymbolTabel[name]);
}
if(m_classSymbolTable.count(name)) {
return get<2>(m_classSymbolTable[name]);
}
return -1;
}

void SymbolTable::print() {
cout << "class-level:" << endl;
for(auto& elem: m_classSymbolTable) {
cout << "---\n";
cout << "name: " << elem.first << endl;
cout << "type: " << get<0>(elem.second) << endl;
cout << "kind: " << get<1>(elem.second) << endl;
cout << "index: " << get<2>(elem.second) << endl;
cout << "---\n";
}
cout << endl << "subroutine-level:" << endl;
for(auto& elem: m_subroutineSymbolTabel) {
cout << "+++\n";
cout << "name: " << elem.first << endl;
cout << "type: " << get<0>(elem.second) << endl;
cout << "kind: " << get<1>(elem.second) << endl;
cout << "index: " << get<2>(elem.second) << endl;
cout << "+++\n";
}
}

bool SymbolTable::exist(const string& name) {
return m_classSymbolTable.count(name) || m_subroutineSymbolTabel.count(name);
}

✅ symboltable module: the new module for recording different variables.

vmwriter.h
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
#ifndef __VM_WRITER_H__
#define __VM_WRITER_H__

#include <fstream>
#include <string>

using namespace std;

class VMWriter {
public:
enum VMSegment {
S_UNKNOWN,
S_CONST,
S_ARG,
S_LOCAL,
S_STATIC,
S_THIS,
S_THAT,
S_POINTER,
S_TEMP,
};
private:
string VMSegmentToString(VMSegment vms);

public:
VMWriter(const string& filename);
~VMWriter();
void close();

void writePush(VMSegment vms, int index);
void writePop(VMSegment vms, int index);
void wirteArithmetic(string cmd);
void writeLabel(const string& label);
void writeGoto(const string& label);
void writeIf(const string& label);
void writeCall(const string& name, int nArgs);
void writeFunction(const string& name, int nArgs);
void writeReturn();

private:
ofstream m_ofs;
};

#endif
vmwriter.cpp
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
#include "vmwriter.h"

#include <iostream>
#include <sstream>

VMWriter::VMWriter(const string& filename)
: m_ofs(filename) {
if(!m_ofs) {
throw(runtime_error("VMWriter fails to create a output file: " + filename));
}
}

VMWriter::~VMWriter() {
close();
}

void VMWriter::close() {
m_ofs.close();
}

string VMWriter::VMSegmentToString(VMSegment v) {
stringstream ss;
#define XX(in, vms, str) \
if(in == vms) \
ss << str;

XX(v, S_CONST, "constant");
XX(v, S_ARG, "argument");
XX(v, S_LOCAL, "local");
XX(v, S_STATIC, "static");
XX(v, S_THIS, "this");
XX(v, S_THAT, "that");
XX(v, S_POINTER, "pointer");
XX(v, S_TEMP, "temp");
#undef XX

return ss.str();
}

void VMWriter::writePush(VMSegment vms, int index) {
stringstream ss;
ss << "push " << VMSegmentToString(vms) << " " << index;
m_ofs << ss.str() << '\n';
}

void VMWriter::writePop(VMSegment vms, int index) {
stringstream ss;
ss << "pop " << VMSegmentToString(vms) << " " << index;
m_ofs << ss.str() << '\n';
}

void VMWriter::wirteArithmetic(string cmd) {
stringstream ss;
ss << cmd << '\n';
m_ofs << ss.str();
}

void VMWriter::writeLabel(const string& label) {
stringstream ss;
ss << "label " << label;
m_ofs << ss.str() << '\n';
}

void VMWriter::writeGoto(const string& label) {
stringstream ss;
ss << "goto " << label;
m_ofs << ss.str() << '\n';
}

void VMWriter::writeIf(const string& label) {
stringstream ss;
ss << "if-goto " << label;
m_ofs << ss.str() << '\n';
}

void VMWriter::writeCall(const string& name, int nArgs) {
stringstream ss;
ss << "call " << name << " " << nArgs;
m_ofs << ss.str() << '\n';
}

void VMWriter::writeFunction(const string& name, int nArgs) {
stringstream ss;
ss << "function " << name << " " << nArgs;
m_ofs << ss.str() << '\n';
}

void VMWriter::writeReturn() {
stringstream ss;
ss << "return";
m_ofs << ss.str() << '\n';
}

✅ vmwriter module: the new module for writing vm code to a file.

Unit 11.12 Perspective

  1. What would it take to generate code for a more realistically complex language?
  • Typing system, inheritance, public fields…
  1. How difficult will it be to close the gaps between Jack in languages like Java or Python?
  • support switch-case statements, char assignments …, these is not difficult.
  1. What is the meaning of compiler optimization?
  • The compiler will generate low-level code which is efficient and optimized.

Buy me a coffee ? :)
0%