forked from KJlmfe/KJCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser6.html
765 lines (721 loc) · 37 KB
/
Parser6.html
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
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
/*log打印函数 每次在原log上追加str和换行*/
function log(str) {
var log_node = document.getElementById("log");
var text_node = document.createTextNode(str);
var br_node = document.createElement("br");
log_node.appendChild(text_node);
log_node.appendChild(br_node);
}
</script>
<script type="text/javascript">
/* 字符串字符处理雷 */
function Reader(str) {
this.data = str;
this.currPos = 0;
this.length = str.length;
}
/* 获取字符串下一个字符 */
Reader.prototype.nextChar = function() {
if(this.currPos >= this.length) {
return -1;
}
return this.data[this.currPos++];
}
/* 回退当前读取位置指针 n是回退的步伐 默认为1步*/
Reader.prototype.retract = function(n) {
if(n === undefined) {
n = 1;
}
this.currPos -= n;
if(this.currPos < 0) {
this.currPos = 0;
}
}
</script>
<script type="text/javascript">
/* 定义Token类型 */
function Token(type, text) {
this.type = type;
this.text = text;
}
/* 定义关键字 保留字 */
Token.tokens = {};
Token.tokens.EOS_TOKEN = 1; //end of stream
// using + 1 allows adding a new token easily later
Token.tokens.COLON_TOKEN = Token.tokens.EOS_TOKEN + 1; //:
Token.tokens.SEMICOLON_TOKEN = Token.tokens.COLON_TOKEN + 1; //;
Token.tokens.LEFTPAREN_TOKEN = Token.tokens.SEMICOLON_TOKEN + 1; //( 4
Token.tokens.RIGHTPAREN_TOKEN = Token.tokens.LEFTPAREN_TOKEN + 1; //)
Token.tokens.LEFTBRACE_TOKEN = Token.tokens.RIGHTPAREN_TOKEN + 1; //{
Token.tokens.RIGHTBRACE_TOKEN = Token.tokens.LEFTBRACE_TOKEN + 1; //}
Token.tokens.MOD_TOKEN = Token.tokens.RIGHTBRACE_TOKEN + 1; //%
Token.tokens.VAR_TOKEN = Token.tokens.MOD_TOKEN + 1; //var 9
Token.tokens.TYPE_TOKEN = Token.tokens.VAR_TOKEN + 1; //int bool
Token.tokens.BOOLLITERAL_TOKEN = Token.tokens.TYPE_TOKEN + 1; //true false
Token.tokens.IF_TOKEN = Token.tokens.BOOLLITERAL_TOKEN + 1; //if 12
Token.tokens.ELSE_TOKEN = Token.tokens.IF_TOKEN + 1; //else
Token.tokens.WHILE_TOKEN = Token.tokens.ELSE_TOKEN + 1; //while
Token.tokens.PRINT_TOKEN = Token.tokens.WHILE_TOKEN + 1; //print
Token.tokens.IDENTIFIER_TOKEN = Token.tokens.PRINT_TOKEN + 1; //id 16
Token.tokens.INTLITERAL_TOKEN = Token.tokens.IDENTIFIER_TOKEN + 1; // int number
Token.tokens.PLUS_TOKEN = Token.tokens.INTLITERAL_TOKEN + 1; //+
Token.tokens.PLUSPLUS_TOKEN = Token.tokens.PLUS_TOKEN + 1; //++
Token.tokens.PLUSASSIGN_TOKEN = Token.tokens.PLUSPLUS_TOKEN + 1; //+=
Token.tokens.MINUS_TOKEN = Token.tokens.PLUSASSIGN_TOKEN + 1; //-
Token.tokens.MINUSMINUS_TOKEN = Token.tokens.MINUS_TOKEN + 1; //--
Token.tokens.MINUSASSIGN_TOKEN = Token.tokens.MINUSMINUS_TOKEN + 1; // -=
Token.tokens.MULT_TOKEN = Token.tokens.MINUSASSIGN_TOKEN + 1; // *
Token.tokens.DIV_TOKEN = Token.tokens.MULT_TOKEN + 1; // /
Token.tokens.ASSIGN_TOKEN = Token.tokens.DIV_TOKEN + 1; // =
Token.tokens.EQUAL_TOKEN = Token.tokens.ASSIGN_TOKEN + 1; // ==
Token.tokens.NOTEQUAL_TOKEN = Token.tokens.EQUAL_TOKEN + 1; // !=
Token.tokens.GREATER_TOKEN = Token.tokens.NOTEQUAL_TOKEN + 1; // >
Token.tokens.GREATEREQUAL_TOKEN = Token.tokens.GREATER_TOKEN + 1; // >=
Token.tokens.LESS_TOKEN = Token.tokens.GREATEREQUAL_TOKEN + 1; // <
Token.tokens.LESSEQUAL_TOKEN = Token.tokens.LESS_TOKEN + 1; // <=
Token.tokens.AND_TOKEN = Token.tokens.LESSEQUAL_TOKEN + 1; // &&
Token.tokens.OR_TOKEN = Token.tokens.AND_TOKEN + 1; // ||
Token.tokens.NOT_TOKEN = Token.tokens.OR_TOKEN + 1; // !
Token.tokens.LINECOMMENT_TOKEN = Token.tokens.NOT_TOKEN + 1; // //
Token.tokens.BLOCKCOMMENT_TOKEN = Token.tokens.LINECOMMENT_TOKEN + 1;// /* .... */
Token.tokens.ERROR_TOKEN = Token.tokens.BLOCKCOMMENT_TOKEN + 1;// 词法错误
Token.tokens.NEWLINE_TOKEN = Token.tokens.ERROR_TOKEN + 1;// \n \r 39
Token.backwardMap = {}; //for inverse look-up
for(var x in Token.tokens) {
Token.backwardMap[Token.tokens[x]] = x;
}
</script>
<script type="text/javascript">
function Scanner(reader) {
this.reader = reader;
this.currentToken = new Token();
this.currLine = 0;
this.bufferStr = "";
this.state = Scanner.START_STATE;
}
Scanner.START_STATE = 0;
Scanner.IDENTIFIER_STATE = Scanner.START_STATE + 1;
Scanner.MULTISYMBOL_STATE = Scanner.IDENTIFIER_STATE + 1;
Scanner.SLASH_STATE= Scanner.MULTISYMBOL_STATE + 1;
Scanner.INTLITERAL_STATE = Scanner.SLASH_STATE + 1;
Scanner.prototype.makeToken = function(type, text) {
this.currentToken.type = type;
this.currentToken.text = text;
return type;
};
Scanner.prototype.nextToken = function() {
switch(this.state) {
case Scanner.START_STATE:
var next_char = this.reader.nextChar();
/* 遇到字母开头 表明可能是标示符或者是保留字 跳转状态*/
if((next_char >= 'a' && next_char <= 'z') || (next_char >= 'A' && next_char <= 'Z')) {
this.state = Scanner.IDENTIFIER_STATE;
this.bufferStr = next_char; //记录单词首字符
return this.nextToken();
}
/* 遇到数字 跳到整数处理状态 */
if(next_char >= '0' && next_char <= '9') {
this.state = Scanner.INTLITERAL_STATE;
this.bufferStr = next_char; //记录单词首字符
return this.nextToken();
}
switch(next_char) {
case -1 : return this.makeToken(Token.tokens.EOS_TOKEN);
case ':': return this.makeToken(Token.tokens.COLON_TOKEN);
case ';': return this.makeToken(Token.tokens.SEMICOLON_TOKEN);
case '(': return this.makeToken(Token.tokens.LEFTPAREN_TOKEN);
case ')': return this.makeToken(Token.tokens.RIGHTPAREN_TOKEN);
case '{': return this.makeToken(Token.tokens.LEFTBRACE_TOKEN);
case '}': return this.makeToken(Token.tokens.RIGHTBRACE_TOKEN);
case '%': return this.makeToken(Token.tokens.MOD_TOKEN);
case '*': return this.makeToken(Token.tokens.MULT_TOKEN);
case '\r': case '\n':
this.currLine++;
return this.makeToken(Token.tokens.NEWLINE_TOKEN);
default:
/*非字母 非单子元无歧义字符 则可能是其他有歧义符号*/
this.state = Scanner.MULTISYMBOL_STATE;
this.bufferStr = next_char;
return this.nextToken();
}
break;
case Scanner.INTLITERAL_STATE:
var next_char = this.reader.nextChar();
if(next_char >= '0' && next_char <= '9') {
this.bufferStr += next_char;
return this.nextToken();
} else {
/* 读取了连续由数字构成的整数 则一个整数字元读取结束 切换状态到开始状态 以便下次读取新的字元*/
this.state = Scanner.START_STATE;
/* 由于多读入了一个非数字字符来判断是否整数结束 所以要对字符读取器回退一个字符 */
this.reader.retract();
return this.makeToken(Token.tokens.INTLITERAL_TOKEN, parseInt(this.bufferStr));
}
break;
case Scanner.IDENTIFIER_STATE:
var next_char = this.reader.nextChar();
if((next_char >= 'a' && next_char <= 'z') || (next_char >= 'A' && next_char <= 'Z')) {
this.bufferStr += next_char;
return this.nextToken();
} else {
/* 读取了连续由字母构成的单词 则一个单词字元读取结束 切换状态到开始状态 以便下次读取新的字元*/
this.state = Scanner.START_STATE;
/* 由于多读入了一个非字母字符来判断是否单词结束 所以要对字符读取器回退一个字符 */
this.reader.retract();
}
switch(this.bufferStr) {
case "var":
return this.makeToken(Token.tokens.VAR_TOKEN);
case "int": case "bool":
return this.makeToken(Token.tokens.TYPE_TOKEN, this.bufferStr);
case "true": case "false": case "TRUE": case "FALSE":
return this.makeToken(Token.tokens.BOOLLITERAL_TOKEN, this.bufferStr.toLowerCase());
case "if":
return this.makeToken(Token.tokens.IF_TOKEN);
case "else":
return this.makeToken(Token.tokens.ELSE_TOKEN);
case "while":
return this.makeToken(Token.tokens.WHILE_TOKEN);
case "print" :
return this.makeToken(Token.tokens.PRINT_TOKEN);
default:
return this.makeToken(Token.tokens.IDENTIFIER_TOKEN, this.bufferStr);
}
break;
case Scanner.MULTISYMBOL_STATE:
this.state = Scanner.START_STATE;
switch(this.bufferStr) {
case '+':
var c = this.reader.nextChar();
if(c == '+') { //++
return this.makeToken(Token.tokens.PLUSPLUS_TOKEN);
} else if(c == '=') { // +=
return this.makeToken(Token.tokens.PLUSASSIGN_TOKEN);
} else { // +
this.reader.retract();
return this.makeToken(Token.tokens.PLUS_TOKEN);
}
case '-':
var c = this.reader.nextChar();
if(c == '-') { //--
return this.makeToken(Token.tokens.MINUSMINUS_TOKEN);
} else if(c == '=') { // -=
return this.makeToken(Token.tokens.MINUSASSIGN_TOKEN);
} else { // -
this.reader.retract();
return this.makeToken(Token.tokens.MINUS_TOKEN);
}
case '=':
var c = this.reader.nextChar();
if(c == '=') { //==
return this.makeToken(Token.tokens.EQUAL_TOKEN);
} else { // =
this.reader.retract();
return this.makeToken(Token.tokens.ASSIGN_TOKEN);
}
case '!':
var c = this.reader.nextChar();
if(c == '=') { // !=
return this.makeToken(Token.tokens.NOTEQUAL_TOKEN);
} else { // !
this.reader.retract();
return this.makeToken(Token.tokens.NOT_TOKEN);
}
case '<':
var c = this.reader.nextChar();
if(c == '=') { //<=
return this.makeToken(Token.tokens.LESSEQUAL_TOKEN);
} else { // <
this.reader.retract();
return this.makeToken(Token.tokens.LESS_TOKEN);
}
case '>':
var c = this.reader.nextChar();
if(c == '=') { //>=
return this.makeToken(Token.tokens.GREATEREQUAL_TOKEN);
} else { // >
this.reader.retract();
return this.makeToken(Token.tokens.GREATER_TOKEN);
}
case '|':
var c = this.reader.nextChar();
if(c == '|') { // ||
return this.makeToken(Token.tokens.OR_TOKEN);
} else { // error
if(c != -1) {
this.reader.retract();
}
return this.makeToken(Token.tokens.ERROR_TOKEN, "line " + this.currLine + ": Missing a |");
}
case '&':
var c = this.reader.nextChar();
if(c == '&') { // &&
return this.makeToken(Token.tokens.AND_TOKEN);
} else { //error
if(c != -1) {
this.reader.retract();
}
return this.makeToken(Token.tokens.ERROR_TOKEN, "line " + this.currLine + ": Missing a &");
}
case '/':
this.state = Scanner.SLASH_STATE;
return this.nextToken();
default:
return this.nextToken();
//ignore other char
}
break;
case Scanner.SLASH_STATE:
this.state = Scanner.START_STATE;
var c = this.reader.nextChar();
this.bufferStr = "";
switch(c) {
case '/': // //....
do {
var d = this.reader.nextChar();
this.bufferStr += d;
} while(d != '\r' && d != '\n');
this.currLine++;
return this.makeToken(Token.tokens.LINECOMMENT_TOKEN, this.bufferStr);
case '*': // /* sdff */
while(true) {
var d = this.reader.nextChar();
if(d == '*') {
if(this.reader.nextChar() == '/') {
return this.makeToken(Token.tokens.BLOCKCOMMENT_TOKEN, this.bufferStr);
} else {
this.reader.retract();
}
} else if(d == -1) {
return this.makeToken(Token.tokens.BLOCKCOMMENT_TOKEN, this.bufferStr);
} else {
this.bufferStr += d;
if(d == '\r' || d == '\n') {
this.currLine++;
}
}
}
default : // /
return this.makeToken(Token.tokens.DIV_TOKEN);
}
break;
default:
break;
}
};
</script>
<script type="text/javascript">
function Parser(scanner) {
this.scanner = scanner;
this.currentToken = new Token();
this.lookaheadToken = new Token();
this.lookaheadToken.used = true;
}
Parser.prototype.nextToken = function() {
if(this.lookaheadToken.used) { //lookaheadToken 被使用了
do {
var token = this.scanner.nextToken();
//skip comments and errors
}while(token == Token.tokens.BLOCKCOMMENT_TOKEN || token == Token.tokens.LINECOMMENT_TOKEN || token == Token.tokens.ERROR_TOKEN);
this.currentToken.type = this.scanner.currentToken.type;
this.currentToken.text = this.scanner.currentToken.text;
return token;
} else { //looaheadToken 没有被使用
this.currentToken.type = this.lookaheadToken.type;
this.currentToken.text = this.lookaheadToken.text;
this.lookaheadToken.used = true;
return this.currentToken.type;
}
}
Parser.prototype.lookahead = function() {
if(this.lookaheadToken.used) {
do {
var token = this.scanner.nextToken();
}while(token == Token.tokens.BLOCKCOMMENT_TOKEN || token == Token.tokens.LINECOMMENT_TOKEN || token == Token.tokens.ERROR_TOKEN);
this.lookaheadToken.type = this.scanner.currentToken.type;
this.lookaheadToken.text = this.scanner.currentToken.text;
this.lookaheadToken.used = false;
return token;
} else {
return this.lookaheadToken.type;
}
}
//the entry point of our parser
Parser.prototype.parse = function() {
var rootBlock = new ExpressionBlockNode();
this.parseExpressions(rootBlock);
return rootBlock;
}
//to parse a list of expressions
Parser.prototype.parseExpressions = function(expressionBlockNode) {
while (this.lookahead() != Token.tokens.RIGHTBRACE_TOKEN &&
this.lookahead() != Token.tokens.EOS_TOKEN){
// skip \r \n Token
if(this.lookahead() == Token.tokens.NEWLINE_TOKEN) {
this.nextToken();
continue;
}
var expressionNode = this.parseExpression();
if (expressionNode){
expressionBlockNode.push(expressionNode);
}
}
}
//to parse an expression
Parser.prototype.parseExpression = function() {
switch (this.lookahead()){
case Token.tokens.PRINT_TOKEN: // print
var printToken = this.nextToken();
var expressionNode = this.parseExpression();
if (expressionNode == undefined){
log("Line " + this.scanner.currLine + ":(Syntax Error) Missing an expression after \"print\"");
}
this.matchSemicolon();
return new PrintNode(expressionNode);
/*
case Token.tokens.INTLITERAL_TOKEN: // 整数常量
var initToken = this.nextToken();
return new IntNode(this.currentToken.text);
case Token.tokens.BOOLLITERAL_TOKEN: // bool 常量
var boolToken = this.nextToken();
return new BoolNode(this.currentToken.text);
*/
case Token.tokens.VAR_TOKEN: //var
return this.parseVarExpression();
case Token.tokens.IF_TOKEN: // if
return this.parseIfExpression();
case Token.tokens.WHILE_TOKEN: // while
return this.parseWhileExpression();
default:
//unexpected, consume it
return this.parseCompoundExpression(0);
}
}
//parse var a:bool; or var b:int = 213;
Parser.prototype.parseVarExpression = function() {
//cosume var token
this.nextToken();
if(this.lookahead() == Token.tokens.IDENTIFIER_TOKEN) { // is a id
this.nextToken(); // consume id token
var varName = this.currentToken.text;
if(this.lookahead() != Token.tokens.COLON_TOKEN) { // is not :
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a : after " + varName);
this.skipError();
return;
}
this.nextToken(); //consume : token
if(this.lookahead() != Token.tokens.TYPE_TOKEN) { // is not type token
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a \"int\" or \"bool\" after :");
this.skipError();
return;
}
this.nextToken(); //consume type token
var type = this.currentToken.text;
var initNode;
if(this.lookahead() == Token.tokens.ASSIGN_TOKEN) { // is a = token
this.nextToken(); //consume = token
initNode = this.parseExpression();
}
this.matchSemicolon();
return new VariableNode(varName, type, initNode);
}
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting an identifier after \"var\"");
this.skipError();
}
Parser.prototype.parseIfExpression = function() {
//cosume if token
this.nextToken();
var condition = this.parseParenExpression();
var expressions = this.parseBlockExpression();
var elseExpressions;
if(this.lookahead() == Token.tokens.ELSE_TOKEN) {
//cosume else token
this.nextToken();
elseExpressions = this.parseBlockExpression();
}
return new IfNode(condition, expressions, elseExpressions);
}
Parser.prototype.parseWhileExpression = function() {
//cosume while token
this.nextToken();
var condition = this.parseParenExpression();
var expressions = this.parseBlockExpression();
return new WhileNode(condition, expressions);
}
Parser.prototype.parseParenExpression = function() {
if(this.lookahead() != Token.tokens.LEFTPAREN_TOKEN) {
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a ( ");
} else {
this.nextToken(); //cosume ( token
}
var expression = this.parseExpression();
if(this.lookahead() != Token.tokens.RIGHTPAREN_TOKEN) {
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a ) ");
} else {
this.nextToken(); //cosume ) token
}
return expression;
}
Parser.prototype.parseBlockExpression = function() {
if(this.lookahead() != Token.tokens.LEFTBRACE_TOKEN) {
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a { ");
} else {
this.nextToken(); //cosume { token
}
var block = new ExpressionBlockNode();
var blockExpression = this.parseExpressions(block);
if(this.lookahead() != Token.tokens.RIGHTBRACE_TOKEN) {
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a } ");
} else {
this.nextToken(); //cosume } token
}
return block;
}
Parser.prototype.matchSemicolon = function() {
if(this.lookahead() != Token.tokens.SEMICOLON_TOKEN) { //一个语句结束了 应该末尾是一个;
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a ; at the end of expression");
} else {
this.nextToken(); //consume ; token
}
}
Parser.prototype.parseOperand = function() { // 对算数表达式进行分项 例如 1 + 2 * (b * (4 / 6) - a) + 5 - -5
var token = this.nextToken();
switch(token) {
case Token.tokens.INTLITERAL_TOKEN: // 整数常量
return new IntNode(this.currentToken.text);
case Token.tokens.BOOLLITERAL_TOKEN: // bool 常量
return new BoolNode(this.currentToken.text);
case Token.tokens.IDENTIFIER_TOKEN: // 标示符
return new IdentifierNode(this.currentToken.text);
case Token.tokens.LEFTPAREN_TOKEN: // 左括号 (
var operand = new ParenNode(this.parseCompoundExpression(0)); // (....) 括号表达式项目
if(this.lookahead() == Token.tokens.RIGHTPAREN_TOKEN) {
// consume )
this.nextToken();
} else {
log("Line " + this.scanner.currLine + ":(Syntax Error) Expecting a ) ");
}
return operand;
case Token.tokens.NOT_TOKEN:
return new NotNode(this.parseOperand()); // 非 因为!的优先级最高 所以可以单独拿出来
case Token.tokens.MINUS_TOKEN:
return new NegateNode(this.parseOperand()); // 负数
default:
log("Line " + this.scanner.currLine + ":(Syntax Error) Unexpected Token ");
return null;
}
}
Parser.prototype.parseCompoundExpression = function(rightBindingPower) { // 处理复杂的表达式
var operandNode = this.parseOperand(); //得到表达式第一个操作数项目
if(operandNode == null) {
return null;
}
var compoundExpressionNode = new CompoundNode();
compoundExpressionNode.push(operandNode); //操作数压堆栈
var operator = this.lookahead(); //获取操作符
var leftBindingPower = this.getBindingPower(operator);
if(leftBindingPower == -1) { //不是一个操作符 表明表达式结束
return compoundExpressionNode;
}
while(rightBindingPower < leftBindingPower) { //这里的left 和 right 我们习惯的反方向
operator = this.nextToken();
compoundExpressionNode.push(this.createOperatorNode(operator)); //运算符压堆栈
var node = this.parseCompoundExpression(leftBindingPower);
compoundExpressionNode.push(node); // 操作数(一个表达式)压堆栈
operator = this.lookahead(); //接下来的操作符
leftBindingPower = this.getBindingPower(operator);
if(leftBindingPower == -1) { //不是操作符 表明表达式结束
return compoundExpressionNode;
}
}
return compoundExpressionNode;
}
Parser.prototype.getBindingPower = function(token) { //算符优先级 数字越高越优先
switch(token) {
case Token.tokens.MULT_TOKEN:
case Token.tokens.DIV_TOKEN:
case Token.tokens.MOD_TOKE:
return 200; // * / %
case Token.tokens.PLUS_TOKEN:
case Token.tokens.MINUS_TOKEN:
return 190; //+ -
case Token.tokens.EQUAL_TOKEN:
case Token.tokens.NOTEQUAL_TOKEN:
return 180; // == !=
case Token.tokens.AND_TOKEN:
return 170; // &&
case Token.tokens.OR_TOKEN:
return 160; // ||
default:
return -1;
}
}
Parser.prototype.createOperatorNode = function(operator) { //返回操作符node
switch(operator) {
case Token.tokens.PLUS_TOKEN:
return new OperatorPlusNode();
case Token.tokens.MINUS_TOKEN:
return new OperatorMinusNode();
case Token.tokens.MULT_TOKEN:
return new OperatorMultNode();
case Token.tokens.DIV_TOKEN:
return new OperatorDivNode();
case Token.tokens.MOD_TOKEN:
return new OperatorModNode();
case Token.tokens.AND_TOKEN:
return new OperatorAndNode();
case Token.tokens.OR_TOKEN:
return new OperatorOrNode();
case Token.tokens.EQUAL_TOKEN:
return new OperatorEqualNode();
case Token.tokens.NOTEQUAL_TOKEN:
return new OperatorNotEqualNode();
default:
return null;
}
}
Parser.prototype.skipError = function() {
while(this.lookahead() != Token.tokens.NEWLINE_TOKEN && this.lookahead() != Token.tokens.EOS_TOKEN) {
this.nextToken();
}
}
</script>
<script type="text/javascript">
function extend(subClass, baseClass) {
function inheritance() {}
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
}
function Node(param) {
}
function ExpressionBlockNode() {
ExpressionBlockNode.baseConstructor.call(this, "test");
this.expressions = [];
}
extend(ExpressionBlockNode, Node);
ExpressionBlockNode.prototype.push = function(expression) {
this.expressions.push(expression);
}
ExpressionBlockNode.prototype.iterate = function(func) {
for(var i = 0, l = this.expressions.length; i < l; i++) {
var expression = this.expressions[i];
func(expression, i);
}
}
function PrintNode(expressionNode) {
this.expressionNode = expressionNode;
}
extend(PrintNode, Node);
function IntNode(data){
this.data = data;
}
extend(IntNode, Node);
function BoolNode(data){
this.data = data;
}
extend(IntNode, Node);
function VariableNode(varName, type, initExpressionNode) {
this.varName = varName;
this.type = type;
this.initExpressionNode = initExpressionNode;
}
extend(VariableNode, Node);
function IfNode(conditionExpression, expressions, elseExpressions){
this.conditionExpression = conditionExpression;
this.expressions = expressions;
this.elseExpressions = elseExpressions;
}
extend(IfNode, Node);
function WhileNode(conditionExpression, expressions){
this.conditionExpression = conditionExpression;
this.expressions = expressions;
}
extend(WhileNode, Node);
function IdentifierNode(identifer){
this.identifer = identifer;
}
extend(IdentifierNode, Node);
function ParenNode(node){
this.node = node;
}
extend(ParenNode, Node);
function NegateNode(node){
this.node = node;
}
extend(NegateNode, Node);
function CompoundNode(){
this.nodes = [];
}
extend(CompoundNode, Node);
CompoundNode.prototype.push = function (node){
this.nodes.push(node);
}
function OperatorNode(){
}
extend(OperatorNode, Node);
function OperatorPlusNode(){
}
extend(OperatorPlusNode, OperatorNode);
function OperatorMinusNode(){
}
extend(OperatorMinusNode, OperatorNode);
function OperatorMultNode(){
}
extend(OperatorMultNode, OperatorNode);
function OperatorDivNode(){
}
extend(OperatorDivNode, OperatorNode);
function OperatorModNode(){
}
extend(OperatorModNode, OperatorNode);
function OperatorAndNode(){
}
extend(OperatorAndNode, OperatorNode);
function OperatorOrNode(){
}
extend(OperatorOrNode, OperatorNode);
function OperatorEqualNode(){
}
function NotNode(node){
this.node = node;
}
extend(NotNode, Node);
extend(OperatorEqualNode, OperatorNode);
function OperatorNotEqualNode(){
}
extend(OperatorNotEqualNode, OperatorNode);
</script>
<script type="text/javascript">
window.onload = function () {
var textarea = document.getElementById("source_code");
var run_button = document.getElementById("run");
/* 测试Scanner类 逐个读取Token 且输出每次Token到log*/
run_button.onclick = function() {
var code_to_be_compiled = textarea.value;
var reader = new Reader(code_to_be_compiled);
var scanner = new Scanner(reader);
var parser = new Parser(scanner);
var expressionBlockNode = parser.parse();
console.log(expressionBlockNode);
};
};
</script>
</head>
<body>
<textarea id="source_code" style="width:600px; height:200px">
print ! false && true != true == false || ! true;
/*语法生成树在js console log里*/
</textarea>
<button id="run">Run</button>
<div id="log">
</div>
</body>
</html>