编译原理实验

找回了写代码最初的快乐

一、实验过程

整体程序采用面向对象思想,主要类有LexicalAnalyzer,SyntaxAnalyzer,Interpreter(词法分析器,语法/语义分析器,代码解释器)等;分别完成三部分实验的主要功能。还有一些附属的小类,如Word,TableItem,SyntaxTreeNode等。本实验中,我们采用自上而下分析法进行分析。

image-20210718162551616

1. 词法分析

词法分析将文档流转换为词语流。具体来说,你需要过滤源程序中的空白符(空格,tab,换行等),识别关键字、标识符、分隔符,数字以及运算符。

一般来说,程序中的单词属于以上五种类型(分别是KEYWORD, OPERATOR, DELIMITER, NUMBER, IDENTIFIER),为了方便报错处理,我们添加ERROR类型。每当处理完一个单词,如果返回ERROR类型则直接抛出词法错误。

为了方便分析,我将类型判断封装成了3个函数分别对关键字,运算符和分隔符进行识别;标识符和数字识别则直接写到parser函数中。

标识符文法:

<标识符> → <字母> {<字母>|<数字>}

<字母> → A|B|C…X|Y|Z

<数字> → 0|1|2…7|8|9

数字文法:

1
2
<无符号整数> → <数字>{<数字>}
<数字> → 0|1|2...7|8|9

运算符表:

1
2
3
4
5
6
7
8
9
10
11
=
:=
+
-
*
/
#
<
<=
>
>=

分隔符表:

1
2
3
4
5
;
,
.
(
)

需要注意的是,pl/0语言不区分大小写,所以在开始处理之前需要过一遍filter,把读入的字母全部转换成uppercase。

LexicalAnalyzer的核心函数就是parseByWord()函数,负责把读入的文档转换为词语流,内容如下,思路都在代码注释里了

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
// parse the project word by word

void LexicalAnalyzer::parseByWord(string &project,int &p){

char ch = project[p];

string token;

Word* word = NULL;

// remove disturbing char(meaningless after filter)

while(ch == ' '||ch == '\n' || ch == '\r'|| ch == '\t'){ch = project[++p];}

// if reach the end of the project

if(p == project.length()){

return;

}

// three situations: begin with a letter/a digit/a symbol

if(isalpha(ch)){

// begin with a letter

while(isalpha(ch) || isdigit(ch)){token.push_back(ch);ch = project[++p];}

// check whether is a keyword

// TODO: add syn to Word parameter

if(isKeyword(token) == -1){

​ word = new Word(Type::IDENTIFIER,token);

​ }else{

​ word = new Word(Type::KEYWORD,token);

​ }

}else if(isdigit(ch)){

// begin with a digit

bool letterAfterDigit = false;

while(isdigit(ch)){token.push_back(ch);ch = project[++p];}

// cannot follow any letter

while(isalpha(ch)){token.push_back(ch);ch = project[++p];letterAfterDigit = true;}

​ word = new Word(letterAfterDigit ? Type::ERROR:Type::NUMBER,token);

}else {

// begin with a symbol

// operator length varies, like 2(:=) and 1(=), so check the longer one firstly

​ token = project.substr(p,2);

if(isOperator(token)){

​ word = new Word(Type::OPERATOR,token);

​ p++;

// check shorter one, operator or delimiter

​ }else if(isOperator(token = token.substr(0,1))){

​ word = new Word(Type::OPERATOR,token);

​ }else if(isDelimiter(token)){

​ word = new Word(Type::DELIMITER,token);

​ }else {

​ word = new Word(Type::ERROR,token);

​ }

​ p++;

}

// push a word into code(no matter if type == ERROR)

code.push_back(*word);

return;

}

2. 语法分析

根据pl/0的上下文无关文法:

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
<程序>→<分程序>.
<分程序>→ [<常量说明部分>][<变量说明部分>][<过程说明部分>]<语句>
<常量说明部分> → CONST<常量定义>{ ,<常量定义>};
<常量定义> → <标识符>=<无符号整数>
<无符号整数> → <数字>{<数字>}
<变量说明部分> → VAR<标识符>{ ,<标识符>};
<标识符> → <字母>{<字母>|<数字>}
<过程说明部分> → <过程首部><分程序>;{<过程说明部分>}
<过程首部> → PROCEDURE <标识符>;
<语句> → <赋值语句>|<条件语句>|<当型循环语句>|<过程调用语句>|<读语句>|<写语句>|<复合语句>|<空语句>
<赋值语句> → <标识符>:=<表达式>
<复合语句> → BEGIN<语句>{ ;<语句>} END
<条件> → <表达式><关系运算符><表达式>|ODD<表达式>
<表达式> → [+|-]<项>{<加减运算符><项>}
<项> → <因子>{<乘除运算符><因子>}
<因子> → <标识符>|<无符号整数>|(<表达式>)
<加减运算符> → +|-
<乘除运算符> → *|/
<关系运算符> → =|#|<|<=|>|>=
<条件语句> → IF<条件>THEN<语句>
<过程调用语句> → CALL<标识符>
<当型循环语句> → WHILE<条件>DO<语句>
<读语句> → READ(<标识符>{ ,<标识符>})
<写语句> → WRITE(<标识符>{,<标识符>})
<字母> → A|B|C…X|Y|Z
<数字> → 0|1|2…7|8|9
<空语句> → epsilon

可以将所有左边的语句封装成相应的函数,相互调用实现自动机的运行过程。由于代码较长,在此就不放置过多代码,只放一个头文件声明。

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
class SyntaxAnalyzer: public LexicalAnalyzer{

private:

typedef SyntaxTreeNode* (SyntaxAnalyzer::*sentenceFunc)(bool);

SyntaxTreeNode* root;

int p;

SyntaxTreeNode* getRead(bool required);

SyntaxTreeNode* getWrite(bool required);

SyntaxTreeNode* getItem(bool required);

SyntaxTreeNode* getExp(bool required);

SyntaxTreeNode* getCondition(bool required);

SyntaxTreeNode* getSentence(bool required);

SyntaxTreeNode* getWhile(bool required);

SyntaxTreeNode* getCall(bool required);

SyntaxTreeNode* getBranch(bool required);

SyntaxTreeNode* getFactor(bool required);

SyntaxTreeNode* getBlock(bool required);

SyntaxTreeNode* getAssign(bool required);

SyntaxTreeNode* getProcedureHead(bool required);

SyntaxTreeNode* getLeaf(string s,bool required);

SyntaxTreeNode* getLeaf(Type type,bool required);

SyntaxTreeNode* getConstantDeclare(bool required);

SyntaxTreeNode* getConstDefinition(bool required);

SyntaxTreeNode* getVarDeclare(bool required);

SyntaxTreeNode* getSubprog(bool required,int level);

SyntaxTreeNode* getProcedureDeclare(bool required,int level);

SyntaxTreeNode* getProgram();

public:

void process();

void printSyntaxTree(SyntaxTreeNode* root);

};

可以看到,由于语法分析的前提需要词法分析产生的结果,因此在这里直接继承了LexicalAnalyzer类,方便直接使用其分析结果vector<string>code;

对于各个函数,广泛采用了以下try-catch形式进行编写:(以read为例)

SyntaxTreeNode* SyntaxAnalyzer::getRead(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::READSENTENCE);

try{

​ node->append(getLeaf("READ",1));

}catch(int err){

return required ? throw err : nullptr;

}

node->append(getLeaf("(",1));

node->append(getLeaf(Type::IDENTIFIER,1));

while(node->append(getLeaf(",",0))){

​ node->append(getLeaf(Type::IDENTIFIER,1));

}

node->append(getLeaf(")",1));

return node;

}

参数required表示是否read语句在此处被“强制”读取,如果required为1但未能成功读取,则需要抛出异常,代表此处发生了语法分析错误;如果未能成功读取但required为0,则只需要返回一个空指针即可,因为read语句在此处不是必须的;如果读取成功,则返回一个指向包含read语句的SyntaxTreeNode类指针。

每个函数中都有相应的required字段以及try-catch语句对下一层函数可能抛出的异常进行处理。可以看到,所有需要对code中的单词进行读取验证的地方(最底层)都调用了getLeaf方法来统一读取。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
SyntaxTreeNode* SyntaxAnalyzer::getLeaf(string s,bool required){

if(code.size() <= p) throw p;

return code[p].val == s ? new SyntaxTreeNode(code[p++],NodeType::SELF) : (required ? throw p : nullptr);

}

SyntaxTreeNode* SyntaxAnalyzer::getLeaf(Type type,bool required){

if(code.size() <= p) throw p;

return code[p].type == type ? new SyntaxTreeNode(code[p++],NodeType::SELF) : (required ? throw p: nullptr);

}

根据需要验证的单词类型不同,我对getLeaf进行了重载,方便用相同的思路进行调用。这里也可以看到,如果required被置为1,则抛出当前处理到的位置指针p。经过层层catchthrow后,到达最上层对其进行处理。结果可以通过cerr打印到控制台,报出SyntaxError以及高亮显示错误位置。

![img](file:///C:/Users/Eric/AppData/Local/Temp/msohtmlclip1/01/clip_image004.jpg)

比较难处理的部分是语法中“或”的逻辑,这也是加上Required的动机之一。因为“或”链接的两部分只要存在一个就可,但是进行分析之前永远不知道到底存在哪一个,或者都不存在。比如getFactor中:


<因子> → <标识符>|<无符号整数>|(<表达式>)

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

因此函数写成:

SyntaxTreeNode* SyntaxAnalyzer::getFactor(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::FACTOR);

try{

​ node->append(getLeaf(Type::IDENTIFIER,0));

​ node->append(getLeaf(Type::NUMBER,0));

​ if(node->append(getLeaf("(",0))){

​ node->append(getExp(1));

​ node->append(getLeaf(")",1));

​ }

}catch(int err){

​ return required ? throw err : nullptr;

}

if(node->empty()){

​ return required ? throw p : nullptr;

}else{

​ return node;

}

}

在这里将获取标识符和数字、以及左括号的required全部写成0,因为某个项get不到并不一定会导致最终的语法错误。因此最后需要检查一下当前节点是否为空,如果为空则需要根据required值抛出异常或返回空指针。

最终,如果没有发生错误,每个getxxx函数都会返回一个语法分析树节点。树节点又分实节点和虚节点,区别在于是否包含终结符。在函数中对节点进行链接,我们就可以得到一棵语法树。题目要求的输出答案,我们可以通过遍历这棵语法树轻易得到。

3. 语义分析与目标代码产生

词法分析器会向语法分析器提供词语流,而语法分析器则按规范推导/规约生成一棵语法树。在本实验中,我们将用语法制导翻译的方式,完成给定语法的语义分析以及目标代码生成。

在本实验中,我们将使用一些翻译模式,在生成语法树的过程中将词语流直接翻译成目标代码(与课本的区别是,省略了中间代码和优化的步骤)。然后,自行编写一个解释器,对给出的八条目标代码进行解释运行。

语义分析

在构建语法树时我们需要边构建边输出目标代码,这就需要对每个功能性语句的语义进行理解,根据句子的语义,输出相应的目标代码对存储器进行控制。例如声明语句var a ;其语义是:在当前执行栈中为变量a申请一块栈空间。而声明语句const b := 10;则没有为const开辟真实的空间,而是将其存储到名字表中,在后续调用时直接将立即数10压入栈顶。具体内容可以参照“动态存储管理”一节。

上面提到名字表,其作用就是在生成目标代码时作为辅助工具。例如后续调用到变量b时,如何判断b是一个const类型变量,如何将其之前定义好的值放到栈顶?这就需要到当前维护的名字表中查找。

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
struct TableItem{

enum Kind {CONSTANT,VARIABLE,PROCEDURE} kind;

int value,level,addr;

TableItem(Kind kind,int level,int val_addr);

};



class NameTable{

private:

std::map<std::string,std::vector<TableItem*> > table;

int tx,dx;

void append(std::string name,TableItem::Kind kind,int lev,int val_addr);

public:

void appendProcedure(std::string name,int lev,int addr);

void appendVariable(std::string name,int lev);

void appendConstant(std::string name,int lev,std::string val);

void writeBackProcAddress(std::string name,int lev,int addr);

TableItem* find(std::string,int lev);

// void find(SyntaxTreeNode* node,int lev);

void resetDx(int x);

int getDx();

void show();

};

每个名字表项包含五个字段(名字是首字段):变量名、种类、值、层级、地址。后四个字段引用了TableItem类,由于可能存在变量重名,因此这里采用vector存储,让每个名字都可以对应多个变量/常量/过程名。

种类kind字段是指当前名字的标识符是函数/变量/常量,常量地址字段为空;层级level字段表示当前标识符所在过程嵌套的层级,主要为了方便后续递归嵌套调用、变量重名覆盖以及运行时程序栈静态链、动态链的处理。

目标代码产生

生成的目标代码是一种假想栈式计算机的汇编语言,其格式如下:

F——L——A

其中f为功能码,l代表层次差(当前操作的变量所在栈与调用栈的层差),a是一个数值(相对于当前栈底的位移量/立即数/跳转地址)。

共有8种目标码:

单参数:

LIT : L域无效,将A位置的值提到栈顶

INT: L域无效,在栈顶分配A个空间

JMP: L域无效,无条件跳转到地址A执行

JPC: L域无效,若栈顶对应的布尔值为假(即0)则跳转到地址A处执行,否则顺序执行

OPR: L域无效,对栈顶执行运算,结果存放在次顶,A=0时为调用返回

双参数:

LOD: 将于当前层层差为L的调用栈、变量位置为A的变量复制到栈顶

STO: 将栈顶内容复制到于当前层层差为L的调用栈、相对位置为A的变量

CAL: 调用过程。L标明层差,A表明目标程序入口地址(目标代码)

通过分析函数语义,结合运行时存储管理的思想,可以将其行为解构为以上八种目标码,以及对名字表的操作。

具体来说,在声明部分:

常量直接记录下 level和 value 即可,处理成中间代码是直接用 lit 调取数值;

变量需要记录下 level 和 addr,处理成中间代码时需要用到 lit、sto、lod;

过程是进入时先存下当前的目标代码栈位置cur,每个过程的第一条指令都是 jmp,此时跳转地址空出,之后可能会有常量定义或者其他声明部分;整个过程结束时才把 jmp 指令的跳转地址给补上(即此时的目标代码栈顶位置),这个时候表示存下当前代码块可执行部分的起始位置。

对于重名变量的处理方式:

由于仅使用了一张名字表进行记录,因此这里采取将重名变量按照加入表中的时间顺序拉成一条链,并记录其所在level;需要引用到变量内容时,查找名字表时从前向后遍历,找到level**值小于等于查找时所在level**值的最后一个位置的tableItem内容(因为PL/0不允许访问层次低于当前层的变量)即可。那如何发现某过程中的重复声明问题并报错?遗憾的是,单使用当前结构的名字表,确实没办法判断是同层级的不同过程声明还是单个过程中的重复声明(见下图,显然后者应报错)。我采取了一种比较取巧的做法:在SyntaxAnalyzer中维护一个set数组,存储以层级为下标的标识符名字,如果声明一个变量时set中已经存在该变量名则报错;在退出当前层级时将该层级的set清空;因为如果是在相同层级的不同过程中声明的变量,中间必然存在一个退栈清空的过程,因而问题得以解决。

image-20210718162622708image-20210718162637890

在 getFactor 中完成常量的 lit 或变量的 lod,在 getItem 中完成乘除的 opr,getExp 中完成加减和负号的 opr,getCondition 中完成逻辑运算的 opr,getSentence 中完成赋值 sto、过程调用 cal、getBranch 以及 getWhile 的跳转 jmp、jpc,getBlock 中完成程序运行跳转 jmp 和开栈空间 int等。同时需要维护调用栈层级,符号表层级等。以及过程、条件、跳转、判断函数的翻译方式比较特殊,需要特别注意。

由于OPR指令需要自定义支持加减乘除取反比较等操作,因此定义了enum类型变量CALCULATE来表示这些操作;

1
2
3
4
enum CALCULATE{
ADD=1,SUB,MUL,DIV,NOT,ODD,EQL,NEQ,LEQ,LSS,GEQ,GTR,RD,WT

};

该枚举类型定义为全局变量,放在全局变量文件global.h中;需要引用时只需要引用global.h头文件即可。

4. 代码解释执行

在上一步生成了目标代码后,还需要运行目标代码;由于我们使用假想栈式计算机的汇编语言,因此需要手写一个适配的解释器进行目标代码的解释执行。这部分的前置知识也涉及到运行时的存储管理部分。

这部分代码中,比较复杂的部分是调用栈的新建、静态链和动态链的链接部分。

静态链: 指向当前过程代码层面的上一级过程调用栈底。主要用来访问低层过程的变量。

动态链: 指向调用当前过程的过程调用栈底。主要用来维护更新调用栈退栈时的信息(应该把栈底指针指向哪儿),以及新建过程调用栈时静态链的维护;

二、写在最后

经过本实验,大大加深了我对课本内容的理解,对编译器运行原理有了更加深层次的认识;

在实际编写编译器解释的过程中,锻炼了我的代码能力和数据结构的运用能力,以及面向对象整体设计的能力。

最后,感谢助教的数据和对第一年编译原理实验转移到OJ工作的推动,相信以后会有更多同学因此受益。

三、完整代码

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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
// complier.cpp

\#include "WordPraser.h"

\#include "SyntaxAnalyzer.h"

// #include "Interpreter.h"

using namespace std;

int main() {

SyntaxAnalyzer *analyzer = new SyntaxAnalyzer();

analyzer->read("test_code.pas");

if(analyzer->parse()){

// analyzer->print();

​ analyzer->process();

​ analyzer->outputTargetCode("program.code");

// analyzer->outputNameTable();

}

// Interpreter *interpreter = new Interpreter(analyzer->codeStack);

// interpreter->run();

return 0;

}

// interp.cpp

\#include "Interpreter.h"



int main(int argc, char **argv){

Interpreter *interpreter = new Interpreter("program.code");

interpreter->run();

return 0;

}





// global.h

\#ifndef GLOBAL_H_INCLUDED

\#define GLOBAL_H_INCLUDED



\#include <cstring>

\#include <string>

using namespace std;



extern const int KEYWORDS_SIZE;

extern const int OPERATORS_SIZE;

extern const int DELIMITER_SIZE;

extern const int OP_SIZE;

extern const int TooMuchEmbedded;

extern const int VariableNotFound;

extern const int IllegalAssignment;

extern const int DivByZero;

extern const int MultiDefination;

extern const int IllegalCall;



extern std::string keywords[];

extern std::string operators[];

extern std::string delimiters[];

extern std::string nodeNames[];

extern std::string opNames[];

extern std::string kindNames[];



enum Type{

KEYWORD, OPERATOR, DELIMITER, NUMBER, IDENTIFIER, UNDEFINED, ERROR

};

enum CALCULATE{

ADD=1,SUB,MUL,DIV,NOT,ODD,EQL,NEQ,LEQ,LSS,GEQ,GTR,RD,WT

};



enum NodeType{

SELF,EMPTY,LP,RP,COMMA,PROGRAM,SUBPROG,CONSTANTDECLARE,

CONSTANTDEFINE,VARIABLEDECLARE,PROCEDUREDECLARE,PROCEDUREHEAD,

SENTENCE,ASSIGNMENT,COMBINED,CONDITION,EXPRESSION,ITEM,FACTOR,

IFSENTENCE,CALLSENTENCE,WHILESENTENCE,READSENTENCE,WRITESENTENCE

};



\#endif // GLOBAL_H_INCLUDED



// global.cpp

\#include "global.h"

\#include <string>

using namespace std;



const int KEYWORDS_SIZE = 13;

const int OPERATORS_SIZE = 11;

const int DELIMITER_SIZE = 5;

const int OP_SIZE = 8;

const int TooMuchEmbedded = -1;

const int VariableNotFound = -2;

const int IllegalAssignment = -3;

const int DivByZero = -4;

const int MultiDefination = -5;

const int IllegalCall = -6;



std::string keywords[] = {

"CONST","VAR","PROCEDURE","BEGIN","END","ODD",

"IF","THEN","CALL","WHILE","DO","READ","WRITE"

};

std::string opNames[] = {

"LIT","LOD","STO","CAL","INT","JMP","JPC","OPR"

};

std::string kindNames[] = {

"const","var","proc"

};

std::string operators[]={"=","+","-","*","/","#","<","<=",">",">=",":="};

std::string delimiters[]={";",",",".","(",")"};

std::string nodeNames[]={

"SELF","EMPTY","LP","RP","COMMA","PROGRAM","SUBPROG","CONSTANTDECLARE",

"CONSTANTDEFINE","VARIABLEDECLARE","PROCEDUREDECLARE","PROCEDUREHEAD",

"SENTENCE","ASSIGNMENT","COMBINED","CONDITION","EXPRESSION","ITEM","FACTOR",

"IFSENTENCE","CALLSENTENCE","WHILESENTENCE","READSENTENCE","WRITESENTENCE"

};



// NameTable.h

\#ifndef _NAMETABLE_H_

\#define _NAMETABLE_H_



\#include<map>

\#include<string>

\#include<cstdlib>

\#include<vector>

\#define UNKNOWN -1

// pre declare

class SyntaxTreeNode;

/*

param: kind

% kind of table item

param: value

param: level

param: address

*/



struct TableItem{

enum Kind {CONSTANT,VARIABLE,PROCEDURE} kind;

int value,level,addr;

TableItem(Kind kind,int level,int val_addr);

};



class NameTable{

private:

std::map<std::string,std::vector<TableItem*> > table;

int tx,dx;

void append(std::string name,TableItem::Kind kind,int lev,int val_addr);

public:

void appendProcedure(std::string name,int lev,int addr);

void appendVariable(std::string name,int lev);

void appendConstant(std::string name,int lev,std::string val);

void writeBackProcAddress(std::string name,int lev,int addr);

TableItem* find(std::string,int lev);

// void find(SyntaxTreeNode* node,int lev);

void resetDx(int x);

int getDx();

void show();

};



\#endif // _NAMETABLE_H_

// NameTable.cpp

\#include "NameTable.h"

\#include "SyntaxAnalyzer.h"

\#include "global.h"

TableItem::TableItem(Kind kind,int level,int val_addr):kind(kind),level(level){

switch(kind){

case TableItem::PROCEDURE:{

this->addr = val_addr;

this->value = -1;

break;

​ }

case TableItem::VARIABLE:{

this->addr = val_addr;

this->value = -1;

break;

​ }

case TableItem::CONSTANT:{

this->value = val_addr;

this->addr = -1;

break;

​ }

}

}



void NameTable::append(std::string name,TableItem::Kind kind,int lev,int val_addr){

if(table.find(name) == table.end()){

vector<TableItem*> items;

​ items.push_back(new TableItem(kind,lev,val_addr));

​ table[name] = items;

}else{

// different type defination

if(table[name].front()->kind != kind) {cerr<<"TypeError\n"; throw MultiDefination;}

// defination on same level

// if(table[name].back()->level == lev) {cerr<<"MultiDefination\n"; throw MultiDefination;}

​ table[name].push_back(new TableItem(kind,lev,val_addr));

}

}

TableItem* NameTable::find(std::string name,int lev){

if(table.find(name) != table.end()){

vector<TableItem*>::iterator it = table[name].begin();

​ TableItem* ans = *it;

while(it != table[name].end()){

// gan write reversed

if((*it)->level <= lev){

​ ans = *it;

​ it++;

​ }else break;

​ }

return ans;

}else throw(VariableNotFound);

}

void NameTable::resetDx(int x){

dx = x;

return;

}

void NameTable::appendProcedure(std::string name,int lev,int addr){

this->append(name,TableItem::PROCEDURE,lev,addr);

}

void NameTable::appendConstant(std::string name,int lev,std::string val){

this->append(name,TableItem::CONSTANT,lev,std::stoi(val));

}

void NameTable::appendVariable(std::string name,int lev){

this->append(name,TableItem::VARIABLE,lev,dx++);

}

int NameTable::getDx(){

return dx;

}

void NameTable::show(){

cerr<<"name\tkind\tvalue\tlevel\taddress\n";

for(auto&i : table){

// cerr<<"size:"<<i.second.size()<<"\n";

for(auto&j : i.second){

cerr<<i.first<<":\t"<<kindNames[j->kind]<<"\t"<<j->value<<"\t"<<j->level<<"\t"<<j->addr<<endl;

​ }

}

}

void NameTable::writeBackProcAddress(string name,int lev,int addr){

TableItem* item = this->find(name,lev);

item->addr = addr;

}

// Interpreter.h

\#ifndef _INTERPRETER_H_

\#define _INTERPRETER_H_



\#include <string>

\#include <vector>

\#include <fstream>

\#include "SyntaxAnalyzer.h"

class Interpreter{

private:

std::vector<CodeItem*> code;

std::vector<int> stack;

void interp(int p);

int PC,SL,DL,RA;

int getIndex(string s);

public:

Interpreter(std::vector<CodeItem*> codeStack);

void run();

Interpreter(std::string fileName);

};



\#endif //_INTERPRETER_H_

// Interpreter.cpp

\#include "Interpreter.h"



void Interpreter::interp(int p){

switch(code[p]->op){

case CodeItem::LIT :{

stack.push_back(code[p]->a);

break;

​ }

case CodeItem::LOD :{

int pos = SL;

int layer = code[p]->l;

while(layer-- > 0){

​ pos = stack[pos];

​ }

stack.push_back(stack[pos+code[p]->a]);

break;

​ }

case CodeItem::STO :{

int pos = SL;

int layer = code[p]->l;

while(layer-- > 0){

​ pos = stack[pos];

​ }

stack[pos+code[p]->a] = stack.back();

break;

​ }

case CodeItem::CAL :{

int pos = SL;

int layer = code[p]->l;

// one more jump

while(layer-- >= 0){

​ pos = stack[pos];

​ }

stack.push_back(pos);

stack.push_back(PC);

stack.push_back(SL);

​ SL = stack.size()-3;

​ RA = stack.size()-2;

​ DL = stack.size()-1;

​ PC = code[p]->a;

break;

​ }

case CodeItem::INT :{

for(int i = 0; i < code[p]->a;i++){

stack.push_back(0);

​ }

break;

​ }

case CodeItem::JMP :{

​ PC = code[p]->a;

break;

​ }

case CodeItem::JPC :{

if(stack.back() == 0){

​ PC = code[p]->a;

​ }

break;

​ }

case CodeItem::OPR :{

switch(code[p]->a){

case 0:{

​ PC = stack[RA];

int tmp = stack[DL];

while(stack.size() > SL+1) stack.pop_back();

​ SL = tmp;

​ RA = tmp+1;

​ DL = tmp+2;

// cout<<"return to : "<<PC<<"\n";

break;

​ }

case CALCULATE::ADD:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(a+b);

break;

​ }

case CALCULATE::SUB:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(b-a);

break;

​ }

case CALCULATE::MUL:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(a*b);

break;

​ }

case CALCULATE::DIV:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

if(a == 0) throw(DivByZero);

stack.push_back(b/a);

break;

​ }

case CALCULATE::ODD:{

int a = stack.back();

stack.pop_back();

stack.push_back(a%2);

break;

​ }

case CALCULATE::NOT:{

int a = stack.back();

stack.pop_back();

stack.push_back(-a);

break;

​ }

case CALCULATE::EQL:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

// cout<<a<<" "<<b<<"\n";

stack.push_back(a == b);

break;

​ }

case CALCULATE::NEQ:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(a!=b);

break;

​ }

case CALCULATE::LEQ:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(b <= a);

break;

​ }

case CALCULATE::LSS:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(b < a);

break;

​ }

case CALCULATE::GEQ:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(b >= a);

break;

​ }

case CALCULATE::GTR:{

int a = stack.back();

stack.pop_back();

int b = stack.back();

stack.pop_back();

stack.push_back(b > a);

break;

​ }

case CALCULATE::RD:{

int a = -1;

std::cin>>a;

stack.push_back(a);

break;

​ }

case CALCULATE::WT:{

int a = stack.back();

std::cout<<a<<"\n";

break;

​ }

​ }

break;

​ }

}

}

void Interpreter::run(){

while(PC != -1){

// cout<<PC<<"\n";

try{

​ interp(PC++);

​ }catch(int err){

cerr<< err <<"\n";

exit(0);

​ }

}

}

Interpreter::Interpreter(std::vector<CodeItem*> codeStack):code(codeStack){

PC = SL = 0;

RA = 1;

DL = 2;

stack.push_back(0); // SL

stack.push_back(-1); // RA

stack.push_back(0); // DL

}

int Interpreter::getIndex(string s){

for(int i = 0; i < OP_SIZE;i++){

if(s == opNames[i]){

return i;

​ }

}

return -1;

}

Interpreter::Interpreter(std::string fileName){

PC = SL = 0;

RA = 1;

DL = 2;

stack.push_back(0); // SL

stack.push_back(-1); // RA

stack.push_back(0); // DL

string op;

int l,a;

std::ifstream fin(fileName);

while(fin>>op>>l>>a){

​ code.push_back(new CodeItem((CodeItem::OPCODE)getIndex(op),l,a));

}

fin.close();

}

// SyntaxAnalyzer.h

\#ifndef _SYNTAXANALYZER_H_

\#define _SYNTAXANALYZER_H_



\#include <cstdio>

\#include <iostream>

\#include <sstream>

\#include <algorithm>

\#include <string>

\#include <cstring>

\#include <cstdlib>

\#include <vector>

\#include <set>

\#include <map>

\#include "WordPraser.h"



using namespace std;



class SyntaxTreeNode{

public:

vector<SyntaxTreeNode*> childs;

Word terminator;

NodeType nodetype;

SyntaxTreeNode(Word terminator,NodeType nodetype);

SyntaxTreeNode(NodeType nodetype);

bool append(SyntaxTreeNode* child);

bool empty();

};

class SyntaxAnalyzer: public WordParser{

private:

typedef SyntaxTreeNode* (SyntaxAnalyzer::*sentenceFunc)(bool);

// vector<Word> code;

SyntaxTreeNode* root;

int p;

SyntaxTreeNode* getRead(bool required);

SyntaxTreeNode* getWrite(bool required);

SyntaxTreeNode* getItem(bool required);

SyntaxTreeNode* getExp(bool required);

SyntaxTreeNode* getCondition(bool required);

SyntaxTreeNode* getSentence(bool required);

SyntaxTreeNode* getWhile(bool required);

SyntaxTreeNode* getCall(bool required);

SyntaxTreeNode* getBranch(bool required);

SyntaxTreeNode* getFactor(bool required);

SyntaxTreeNode* getBlock(bool required);

SyntaxTreeNode* getAssign(bool required);

SyntaxTreeNode* getProcedureHead(bool required);

SyntaxTreeNode* getLeaf(string s,bool required);

SyntaxTreeNode* getLeaf(Type type,bool required);

SyntaxTreeNode* getConstantDeclare(bool required);

SyntaxTreeNode* getConstDefinition(bool required);

SyntaxTreeNode* getVarDeclare(bool required);

SyntaxTreeNode* getSubprog(bool required,int level);

SyntaxTreeNode* getProcedureDeclare(bool required,int level);

SyntaxTreeNode* getProgram();

public:

void process();

void printSyntaxTree(SyntaxTreeNode* root);

};

\#endif //_SYNTAXANALYZER_H_

// SyntaxAnalyzer.cpp

\#include "SyntaxAnalyzer.h"



using namespace std;

SyntaxTreeNode::SyntaxTreeNode(Word terminator,NodeType nodetype):terminator(terminator),nodetype(nodetype){}

SyntaxTreeNode::SyntaxTreeNode(NodeType nodetype):nodetype(nodetype){}

bool SyntaxTreeNode::append(SyntaxTreeNode* child){

if(child != nullptr){

​ childs.push_back(child);

return true;

}

return false;

}

bool SyntaxTreeNode::empty(){

return childs.empty();

}

SyntaxTreeNode* SyntaxAnalyzer::getRead(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::READSENTENCE);

try{

​ node->append(getLeaf("READ",1));

​ node->append(getLeaf("(",1));

​ node->append(getLeaf(Type::IDENTIFIER,1));

while(node->append(getLeaf(",",0))){

​ node->append(getLeaf(Type::IDENTIFIER,1));

​ }

​ node->append(getLeaf(")",1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getWrite(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::WRITESENTENCE);

try{

​ node->append(getLeaf("WRITE",1));

​ node->append(getLeaf("(",1));

​ node->append(getLeaf(Type::IDENTIFIER,1));

while(node->append(getLeaf(",",0))){

​ node->append(getLeaf(Type::IDENTIFIER,1));

​ }

​ node->append(getLeaf(")",1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getItem(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::ITEM);

try{

​ node->append(getFactor(1));

while(node->append(getLeaf("*",0))||node->append(getLeaf("/",0))){

​ node->append(getFactor(1));

​ }

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getExp(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::EXPRESSION);

try{

​ node->append(getLeaf("+",0));

​ node->append(getLeaf("-",0));

​ node->append(getItem(1));

while(node->append(getLeaf("+",0))||node->append(getLeaf("-",0))){

​ node->append(getItem(1));

​ }

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getCondition(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::CONDITION);

try{

if(node->append(getExp(0))){

if(node->append(getLeaf("=",0))

​ ||node->append(getLeaf("#",0))

​ ||node->append(getLeaf("<",0))

​ ||node->append(getLeaf("<=",0))

​ ||node->append(getLeaf(">",0))

​ ||node->append(getLeaf(">=",0))){

​ node->append(getExp(1));

​ }else{

throw p;

​ }

​ }else{

​ node->append(getLeaf("ODD",1));

​ node->append(getExp(1));

​ }

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getSentence(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::SENTENCE);

sentenceFunc sentence[] = {

​ &SyntaxAnalyzer::getAssign,

​ &SyntaxAnalyzer::getBranch,

​ &SyntaxAnalyzer::getWhile,

​ &SyntaxAnalyzer::getCall,

​ &SyntaxAnalyzer::getRead,

​ &SyntaxAnalyzer::getWrite,

​ &SyntaxAnalyzer::getBlock

};

bool notEmpty = false;

try{

for(int i = 0; i < 7 ;i++){

if(node->append((this->*sentence[i])(0))){

​ notEmpty = true;

break;

​ }

​ }

}catch(int err){

return required ? throw err : nullptr;

}

if(!notEmpty){

​ node->append(new SyntaxTreeNode(NodeType::EMPTY));

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getWhile(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::WHILESENTENCE);

try{

​ node->append(getLeaf("WHILE",1));

​ node->append(getCondition(1));

​ node->append(getLeaf("DO",1));

​ node->append(getSentence(1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getCall(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::CALLSENTENCE);

try{

​ node->append(getLeaf("CALL",1));

​ node->append(getLeaf(Type::IDENTIFIER,1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getBranch(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::IFSENTENCE);

try{

​ node->append(getLeaf("IF",1));

​ node->append(getCondition(1));

​ node->append(getLeaf("THEN",1));

​ node->append(getSentence(1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getFactor(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::FACTOR);

try{

​ node->append(getLeaf(Type::IDENTIFIER,0));

​ node->append(getLeaf(Type::NUMBER,0));

if(node->append(getLeaf("(",0))){

​ node->append(getExp(1));

​ node->append(getLeaf(")",1));

​ }

}catch(int err){

return required ? throw err : nullptr;

}

if(node->empty()){

return required ? throw p : nullptr;

}else{

return node;

}

}

SyntaxTreeNode* SyntaxAnalyzer::getBlock(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::COMBINED);

try{

​ node->append(getLeaf("BEGIN",1));

​ node->append(getSentence(1));

while(node->append(getLeaf(";",0))){

​ node->append(getSentence(1));

​ }

​ node->append(getLeaf("END",1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getAssign(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::ASSIGNMENT);

try{

​ node->append(getLeaf(Type::IDENTIFIER,1));

​ node->append(getLeaf(":=",1));

​ node->append(getExp(1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getProcedureHead(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::PROCEDUREHEAD);

try{

​ node->append(getLeaf("PROCEDURE",1));

​ node->append(getLeaf(Type::IDENTIFIER,1));

​ node->append(getLeaf(";",1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getLeaf(string s,bool required){

if(code.size() <= p) throw p;

return code[p].val == s ? new SyntaxTreeNode(code[p++],NodeType::SELF) : (required ? throw p : nullptr);

}

SyntaxTreeNode* SyntaxAnalyzer::getLeaf(Type type,bool required){

if(code.size() <= p) throw p;

return code[p].type == type ? new SyntaxTreeNode(code[p++],NodeType::SELF) : (required ? throw p: nullptr);

}

SyntaxTreeNode* SyntaxAnalyzer::getConstantDeclare(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::CONSTANTDECLARE);

try{

​ node->append(getLeaf("CONST",1));

​ node->append(getConstDefinition(1));

while(node->append(getLeaf(",",0))){

​ node->append(getConstDefinition(1));

​ }

​ node->append(getLeaf(";",1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getConstDefinition(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::CONSTANTDEFINE);

try{

​ node->append(getLeaf(Type::IDENTIFIER,1));

​ node->append(getLeaf("=",1));

​ node->append(getLeaf(Type::NUMBER,1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getVarDeclare(bool required){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::VARIABLEDECLARE);

try{

​ node->append(getLeaf("VAR",1));

​ node->append(getLeaf(Type::IDENTIFIER,1));

while(node->append(getLeaf(",",0))){

​ node->append(getLeaf(Type::IDENTIFIER,1));

​ }

​ node->append(getLeaf(";",1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getSubprog(bool required,int level){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::SUBPROG);

try{

​ node->append(getConstantDeclare(0));

​ node->append(getVarDeclare(0));

​ node->append(getProcedureDeclare(0,level+1));

​ node->append(getSentence(1));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getProcedureDeclare(bool required,int level){

if(level > 4) throw level;

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::PROCEDUREDECLARE);

try{

​ node->append(getProcedureHead(1));

​ node->append(getSubprog(1,level));

​ node->append(getLeaf(";",1));

while(node->append(getProcedureDeclare(0,level)));

}catch(int err){

return required ? throw err : nullptr;

}

return node;

}

SyntaxTreeNode* SyntaxAnalyzer::getProgram(){

SyntaxTreeNode* node = new SyntaxTreeNode(NodeType::PROGRAM);

node->append(getSubprog(1,0));

node->append(getLeaf(".",1));

return node;

}

void SyntaxAnalyzer::process(){

p = 0;

try{

​ root = getProgram();

if(p != code.size()) throw p;

}catch(int err){

cout<<"Syntax Error\n";

cerr<<"at "<<err<<" : "<<code[p].val<<"\n";

return;

}

printSyntaxTree(root);

}

void SyntaxAnalyzer::printSyntaxTree(SyntaxTreeNode* root){

if(root->terminator.val == "("){

cout<<"LP";

}else if(root->terminator.val == ")"){

cout<<"RP";

}else if(root->terminator.val == ","){

cout<<"COMMA";

}else if(root->nodetype == NodeType::SELF){

cout<<root->terminator.val;

}else if(root->nodetype == NodeType::EMPTY){

cout<<nodeNames[(int)root->nodetype];

}else {

cout<<nodeNames[(int)root->nodetype]<<"(";

// cerr<<"size:"<<root->childs.size()<<"\n";

for(int i = 0; i < root->childs.size()-1;i++){

​ printSyntaxTree(root->childs[i]);

cout<<",";

​ }

​ printSyntaxTree(root->childs[root->childs.size()-1]);

cout<<")";

}

}

// LexicalAnalyzer.h

\#ifndef _LexicalAnalyzer_H_

\#define _LexicalAnalyzer_H_



\#include <cstdio>

\#include <iostream>

\#include <sstream>

\#include <algorithm>

\#include <string>

\#include <cstring>

\#include <cstdlib>

\#include <vector>

\#include <set>

\#include <map>

\#include "global.h"



using namespace std;



class Word {

public:

Type type;

string val;

int syn;

Word(Type typ, string value);

Word();

};



/*

\-----------------------------

wordList 单词表

project 所有输入

\-----------------------------

*/

class WordParser{

protected:

vector<Word> code;

private:

string project;

// check whether a word is keyword

int isKeyword(string word);

// check whether a word is delimiter

bool isDelimiter(string s);

// check whether a word is operator

bool isOperator(string s);

// parse the project word by word

void parseByWord(string &project,int &p);

// remove the disturbing word in the project

void filter(string& str);

public:

// read the whole content into project and do some preprocessing

void read();

// parse the project, get a wordlist contains all the words

bool parse();

// print the wordlist

void print();

void read(string fileName);

};

\#endif //_LexicalAnalyzer_H_

// LexicalAnalyzer.cpp

\#include "LexicalAnalyzer.h"

\#include <fstream>

using namespace std;



Word::Word(){

type = Type::UNDEFINED;

val = "";

}

Word::Word(Type typ, string value):type(typ),val(value){

if(type == Type::IDENTIFIER && val.length() > 10){

// restrict identifier length

​ type = Type::ERROR;

}

if(type == Type::NUMBER){

// remove leading zero

while(val.size() > 1 && val[0] == '0') val.erase(val.begin());

}

}



/*

\-----------------------------

LexicalAnalyzer

\-----------------------------

*/

// check whether a word is keyword

int WordParser::isKeyword(string word){

for(int i=0;i<KEYWORDS_SIZE;i++){

if(keywords[i] == word) return i;

}

return -1; // IDENTIFIER id

}

// check whether a word is delimiter

bool WordParser::isDelimiter(string s){

for(int i = 0; i < DELIMITER_SIZE; i++){

if(delimiters[i] == s){

return true;

​ }

}

return false;

}

// check whether a word is operator

bool WordParser::isOperator(string s){

for(int i = 0; i < OPERATORS_SIZE; i++){

if(operators[i] == s){

return true;

​ }

}

return false;

}

// parse the project word by word

void WordParser::parseByWord(string &project,int &p){

char ch = project[p];

string token;

Word* word = NULL;

// remove disturbing char(meaningless after filter)

while(ch == ' '||ch == '\n' || ch == '\r'|| ch == '\t'){ch = project[++p];}

// if reach the end of the project

if(p == project.length()){

return;

}

// three situations: begin with a letter/a digit/a symbol

if(isalpha(ch)){

// begin with a letter

while(isalpha(ch) || isdigit(ch)){token.push_back(ch);ch = project[++p];}

// check whether is a keyword

// TODO: add syn to Word parameter

if(isKeyword(token) == -1){

​ word = new Word(Type::IDENTIFIER,token);

​ }else{

​ word = new Word(Type::KEYWORD,token);

​ }

}else if(isdigit(ch)){

// begin with a digit

bool letterAfterDigit = false;

while(isdigit(ch)){token.push_back(ch);ch = project[++p];}

// cannot follow any letter

while(isalpha(ch)){token.push_back(ch);ch = project[++p];letterAfterDigit = true;}

​ word = new Word(letterAfterDigit ? Type::ERROR:Type::NUMBER,token);

}else {

// begin with a symbol

// operator length varies, like 2(:=) and 1(=), so check the longer one firstly

​ token = project.substr(p,2);

if(isOperator(token)){

​ word = new Word(Type::OPERATOR,token);

​ p++;

// check shorter one, operator or delimiter

​ }else if(isOperator(token = token.substr(0,1))){

​ word = new Word(Type::OPERATOR,token);

​ }else if(isDelimiter(token)){

​ word = new Word(Type::DELIMITER,token);

​ }else {

​ word = new Word(Type::ERROR,token);

​ }

​ p++;

}

// push a word into code(no matter if type == ERROR)

code.push_back(*word);

return;

}

// remove the disturbing word in the project

void WordParser::filter(string& str){

for(int i = 0; i < str.size(); i++){

if(isalpha(str[i])){

​ str[i] = toupper(str[i]);

​ }else if(str[i] < 33 || str[i] == 127) str[i] = ' ';

}

}

// read the whole content into project and do some preprocessing

void WordParser::read(){

string tmp = "";

while(getline(cin,tmp)){

​ project += tmp + "\n";

}

filter(project);

}

void WordParser::read(string fileName){

string tmp = "";

ifstream fin(fileName);

while(getline(fin,tmp)){

​ project += tmp + "\n";

}

fin.close();

filter(project);

}

// parse the project, get a code contains all the words

bool WordParser::parse(){

// p is the current pointer position in project parsing

int p = 0;

while(p < project.size()){

​ parseByWord(project,p);

if(!code.empty() && code.back().type == Type::ERROR){

// if Error return false directly

cout<<"Lexical Error\n";

return false;

​ }

}

return true;

}

// print the code

void WordParser::print(){

for(auto i :code){

if(i.type == Type::IDENTIFIER){

cout<<"IDENTIFIER "+i.val<<"\n";

​ }else if(i.type == Type::NUMBER){

cout<<"NUMBER "+i.val<<"\n";

​ }else{

cout<<i.val<<"\n";

​ }

}

}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×