forked from glayzzle/php-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
656 lines (635 loc) · 16.9 KB
/
parser.js
File metadata and controls
656 lines (635 loc) · 16.9 KB
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
/**
* Copyright (C) 2018 Glayzzle (BSD3 License)
* @authors https://github.com/glayzzle/php-parser/graphs/contributors
* @url http://glayzzle.com
*/
"use strict";
/**
* @private
*/
function isNumber(n) {
return n != "." && n != "," && !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* The PHP Parser class that build the AST tree from the lexer
*
* @class
* @tutorial Parser
* @property {Lexer} lexer - current lexer instance
* @property {AST} ast - the AST factory instance
* @property {Integer|String} token - current token
* @property {Boolean} extractDoc - should extract documentation as AST node
* @property {Boolean} extractTokens - should extract each token
* @property {Boolean} suppressErrors - should ignore parsing errors and continue
* @property {Boolean} debug - should output debug informations
*/
const parser = function(lexer, ast) {
this.lexer = lexer;
this.ast = ast;
this.tok = lexer.tok;
this.EOF = lexer.EOF;
this.token = null;
this.prev = null;
this.debug = false;
this.php7 = true;
this.extractDoc = false;
this.extractTokens = false;
this.suppressErrors = false;
const mapIt = function(item) {
return [item, null];
};
this.entries = {
IDENTIFIER: new Map(
[
this.tok.T_ABSTRACT,
this.tok.T_ARRAY,
this.tok.T_AS,
this.tok.T_BREAK,
this.tok.T_CALLABLE,
this.tok.T_CASE,
this.tok.T_CATCH,
this.tok.T_CLASS,
this.tok.T_CLASS_C,
this.tok.T_CLONE,
this.tok.T_CONST,
this.tok.T_CONTINUE,
this.tok.T_DECLARE,
this.tok.T_DEFAULT,
this.tok.T_DIR,
this.tok.T_DO,
this.tok.T_ECHO,
this.tok.T_ELSE,
this.tok.T_ELSEIF,
this.tok.T_EMPTY,
this.tok.T_ENDDECLARE,
this.tok.T_ENDFOR,
this.tok.T_ENDFOREACH,
this.tok.T_ENDIF,
this.tok.T_ENDSWITCH,
this.tok.T_ENDWHILE,
this.tok.T_EVAL,
this.tok.T_EXIT,
this.tok.T_EXTENDS,
this.tok.T_FILE,
this.tok.T_FINAL,
this.tok.T_FINALLY,
this.tok.T_FUNC_C,
this.tok.T_FOR,
this.tok.T_FOREACH,
this.tok.T_FUNCTION,
this.tok.T_GLOBAL,
this.tok.T_GOTO,
this.tok.T_IF,
this.tok.T_IMPLEMENTS,
this.tok.T_INCLUDE,
this.tok.T_INCLUDE_ONCE,
this.tok.T_INSTANCEOF,
this.tok.T_INSTEADOF,
this.tok.T_INTERFACE,
this.tok.T_ISSET,
this.tok.T_LINE,
this.tok.T_LIST,
this.tok.T_LOGICAL_AND,
this.tok.T_LOGICAL_OR,
this.tok.T_LOGICAL_XOR,
this.tok.T_METHOD_C,
this.tok.T_NAMESPACE,
this.tok.T_NEW,
this.tok.T_NS_C,
this.tok.T_PRINT,
this.tok.T_PRIVATE,
this.tok.T_PROTECTED,
this.tok.T_PUBLIC,
this.tok.T_REQUIRE,
this.tok.T_REQUIRE_ONCE,
this.tok.T_RETURN,
this.tok.T_STATIC,
this.tok.T_SWITCH,
this.tok.T_THROW,
this.tok.T_TRAIT,
this.tok.T_TRY,
this.tok.T_UNSET,
this.tok.T_USE,
this.tok.T_VAR,
this.tok.T_WHILE,
this.tok.T_YIELD
].map(mapIt)
),
VARIABLE: new Map(
[
this.tok.T_VARIABLE,
"$",
"&",
this.tok.T_NS_SEPARATOR,
this.tok.T_STRING,
this.tok.T_NAMESPACE,
this.tok.T_STATIC
].map(mapIt)
),
SCALAR: new Map(
[
this.tok.T_CONSTANT_ENCAPSED_STRING,
this.tok.T_START_HEREDOC,
this.tok.T_LNUMBER,
this.tok.T_DNUMBER,
this.tok.T_ARRAY,
"[",
this.tok.T_CLASS_C,
this.tok.T_TRAIT_C,
this.tok.T_FUNC_C,
this.tok.T_METHOD_C,
this.tok.T_LINE,
this.tok.T_FILE,
this.tok.T_DIR,
this.tok.T_NS_C,
'"',
'b"',
'B"',
"-",
this.tok.T_NS_SEPARATOR
].map(mapIt)
),
T_MAGIC_CONST: new Map(
[
this.tok.T_CLASS_C,
this.tok.T_TRAIT_C,
this.tok.T_FUNC_C,
this.tok.T_METHOD_C,
this.tok.T_LINE,
this.tok.T_FILE,
this.tok.T_DIR,
this.tok.T_NS_C
].map(mapIt)
),
T_MEMBER_FLAGS: new Map(
[
this.tok.T_PUBLIC,
this.tok.T_PRIVATE,
this.tok.T_PROTECTED,
this.tok.T_STATIC,
this.tok.T_ABSTRACT,
this.tok.T_FINAL
].map(mapIt)
),
EOS: new Map([";", this.EOF, this.tok.T_INLINE_HTML].map(mapIt)),
EXPR: new Map(
[
"@",
"-",
"+",
"!",
"~",
"(",
"`",
this.tok.T_LIST,
this.tok.T_CLONE,
this.tok.T_INC,
this.tok.T_DEC,
this.tok.T_NEW,
this.tok.T_ISSET,
this.tok.T_EMPTY,
this.tok.T_INCLUDE,
this.tok.T_INCLUDE_ONCE,
this.tok.T_REQUIRE,
this.tok.T_REQUIRE_ONCE,
this.tok.T_EVAL,
this.tok.T_INT_CAST,
this.tok.T_DOUBLE_CAST,
this.tok.T_STRING_CAST,
this.tok.T_ARRAY_CAST,
this.tok.T_OBJECT_CAST,
this.tok.T_BOOL_CAST,
this.tok.T_UNSET_CAST,
this.tok.T_EXIT,
this.tok.T_PRINT,
this.tok.T_YIELD,
this.tok.T_STATIC,
this.tok.T_FUNCTION,
// using VARIABLES :
this.tok.T_VARIABLE,
"$",
this.tok.T_NS_SEPARATOR,
this.tok.T_STRING,
// using SCALAR :
this.tok.T_STRING, // @see variable.js line 45 > conflict with variable = shift/reduce :)
this.tok.T_CONSTANT_ENCAPSED_STRING,
this.tok.T_START_HEREDOC,
this.tok.T_LNUMBER,
this.tok.T_DNUMBER,
this.tok.T_ARRAY,
"[",
this.tok.T_CLASS_C,
this.tok.T_TRAIT_C,
this.tok.T_FUNC_C,
this.tok.T_METHOD_C,
this.tok.T_LINE,
this.tok.T_FILE,
this.tok.T_DIR,
this.tok.T_NS_C
].map(mapIt)
)
};
};
/**
* helper : gets a token name
*/
parser.prototype.getTokenName = function(token) {
if (!isNumber(token)) {
return "'" + token + "'";
} else {
if (token == this.EOF) return "the end of file (EOF)";
return this.lexer.engine.tokens.values[token];
}
};
/**
* main entry point : converts a source code to AST
*/
parser.prototype.parse = function(code, filename) {
this._errors = [];
this.filename = filename || "eval";
this.currentNamespace = [""];
if (this.extractDoc) {
this._docs = [];
} else {
this._docs = null;
}
if (this.extractTokens) {
this._tokens = [];
} else {
this._tokens = null;
}
this._docIndex = 0;
this._lastNode = null;
this.lexer.setInput(code);
this.lexer.all_tokens = this.extractTokens;
this.lexer.comment_tokens = this.extractDoc;
this.length = this.lexer._input.length;
this.innerList = false;
this.innerListForm = false;
const program = this.node("program");
let childs = [];
this.next();
while (this.token != this.EOF) {
const node = this.read_start();
if (node !== null && node !== undefined) {
if (Array.isArray(node)) {
childs = childs.concat(node);
} else {
childs.push(node);
}
}
}
// #176 : register latest position
this.prev = [
this.lexer.yylloc.last_line,
this.lexer.yylloc.last_column,
this.lexer.offset
];
const result = program(childs, this._errors, this._docs, this._tokens);
if (this.debug) {
const errors = this.ast.checkNodes();
if (errors.length > 0) {
errors.forEach(function(error) {
// eslint-disable-next-line no-console
console.log(
"Node at line " +
error.position.line +
", column " +
error.position.column
);
// eslint-disable-next-line no-console
console.log(error.stack.join("\n"));
});
throw new Error("Some nodes are not closed");
}
}
return result;
};
/**
* Raise an error
*/
parser.prototype.raiseError = function(message, msgExpect, expect, token) {
message += " on line " + this.lexer.yylloc.first_line;
if (!this.suppressErrors) {
const err = new SyntaxError(
message,
this.filename,
this.lexer.yylloc.first_line
);
err.lineNumber = this.lexer.yylloc.first_line;
err.fileName = this.filename;
err.columnNumber = this.lexer.yylloc.first_column;
throw err;
}
// Error node :
const node = this.ast.prepare("error", null, this)(
message,
token,
this.lexer.yylloc.first_line,
expect
);
this._errors.push(node);
return node;
};
/**
* handling errors
*/
parser.prototype.error = function(expect) {
let msg = "Parse Error : syntax error";
let token = this.getTokenName(this.token);
let msgExpect = "";
if (this.token !== this.EOF) {
if (isNumber(this.token)) {
let symbol = this.text();
if (symbol.length > 10) {
symbol = symbol.substring(0, 7) + "...";
}
token = "'" + symbol + "' (" + token + ")";
}
msg += ", unexpected " + token;
}
if (expect && !Array.isArray(expect)) {
if (isNumber(expect) || expect.length === 1) {
msgExpect = ", expecting " + this.getTokenName(expect);
}
msg += msgExpect;
}
return this.raiseError(msg, msgExpect, expect, token);
};
/**
* Creates a new AST node
*/
parser.prototype.node = function(name) {
if (this.extractDoc) {
let docs = null;
if (this._docIndex < this._docs.length) {
docs = this._docs.slice(this._docIndex);
this._docIndex = this._docs.length;
if (this.debug) {
// eslint-disable-next-line no-console
console.log(new Error("Append docs on " + name));
// eslint-disable-next-line no-console
console.log(docs);
}
}
const node = this.ast.prepare(name, docs, this);
/**
* TOKENS :
* node1 commentA token commmentB node2 commentC token commentD node3 commentE token
*
* AST :
* structure:S1 [
* left: node1 ( trail: commentA ),
* right: structure:S2 [
* node2 (lead: commentB, trail: commentC),
* node3 (lead: commentD)
* ],
* trail: commentE
* ]
*
* Algorithm :
*
* Attach the last comments on parent of current node
* If a new node is started and the parent has a trailing comment
* the move it on previous node
*
* start S2
* start node1
* consume node1 & set commentA as trailingComment on S2
* start S2
* S1 has a trailingComment, attach it on node1
* ...
* NOTE : As the trailingComment Behavior depends on AST, it will be build on
* the AST layer - last child node will keep it's trailingComment nodes
*/
node.postBuild = function(self) {
if (this._docIndex < this._docs.length) {
if (this._lastNode) {
const offset = this.prev[2];
let max = this._docIndex;
for (; max < this._docs.length; max++) {
if (this._docs[max].offset > offset) {
break;
}
}
if (max > this._docIndex) {
// inject trailing comment on child node
this._lastNode.setTrailingComments(
this._docs.slice(this._docIndex, max)
);
this._docIndex = max;
}
} else if (this.token === this.EOF) {
// end of content
self.setTrailingComments(this._docs.slice(this._docIndex));
this._docIndex = this._docs.length;
}
}
this._lastNode = self;
}.bind(this);
return node;
}
return this.ast.prepare(name, null, this);
};
/**
* expects an end of statement or end of file
* @return {boolean}
*/
parser.prototype.expectEndOfStatement = function(node) {
if (this.token === ";") {
// include only real ';' statements
// https://github.com/glayzzle/php-parser/issues/164
if (node && this.lexer.yytext === ";") {
node.includeToken(this);
}
} else if (this.token !== this.tok.T_INLINE_HTML && this.token !== this.EOF) {
this.error(";");
return false;
}
this.next();
return true;
};
/** outputs some debug information on current token **/
const ignoreStack = ["parser.next", "parser.node", "parser.showlog"];
parser.prototype.showlog = function() {
const stack = new Error().stack.split("\n");
let line;
for (let offset = 2; offset < stack.length; offset++) {
line = stack[offset].trim();
let found = false;
for (let i = 0; i < ignoreStack.length; i++) {
if (line.substring(3, 3 + ignoreStack[i].length) === ignoreStack[i]) {
found = true;
break;
}
}
if (!found) {
break;
}
}
// eslint-disable-next-line no-console
console.log(
"Line " +
this.lexer.yylloc.first_line +
" : " +
this.getTokenName(this.token) +
">" +
this.lexer.yytext +
"<" +
" @-->" +
line
);
return this;
};
/**
* Force the parser to check the current token.
*
* If the current token does not match to expected token,
* the an error will be raised.
*
* If the suppressError mode is activated, then the error will
* be added to the program error stack and this function will return `false`.
*
* @param {String|Number} token
* @return {boolean}
* @throws Error
*/
parser.prototype.expect = function(token) {
if (Array.isArray(token)) {
if (token.indexOf(this.token) === -1) {
this.error(token);
return false;
}
} else if (this.token != token) {
this.error(token);
return false;
}
return true;
};
/**
* Returns the current token contents
* @return {String}
*/
parser.prototype.text = function() {
return this.lexer.yytext;
};
/** consume the next token **/
parser.prototype.next = function() {
// prepare the back command
if (this.token !== ";" || this.lexer.yytext === ";") {
// ignore '?>' from automated resolution
// https://github.com/glayzzle/php-parser/issues/168
this.prev = [
this.lexer.yylloc.last_line,
this.lexer.yylloc.last_column,
this.lexer.offset
];
}
// eating the token
this.lex();
// showing the debug
if (this.debug) {
this.showlog();
}
// handling comments
if (this.extractDoc) {
while (
this.token === this.tok.T_COMMENT ||
this.token === this.tok.T_DOC_COMMENT
) {
// APPEND COMMENTS
if (this.token === this.tok.T_COMMENT) {
this._docs.push(this.read_comment());
} else {
this._docs.push(this.read_doc_comment());
}
}
}
return this;
};
/**
* Eating a token
*/
parser.prototype.lex = function() {
// append on token stack
if (this.extractTokens) {
do {
// the token
this.token = this.lexer.lex() || this.EOF;
if (this.token === this.EOF) return this;
let entry = this.lexer.yytext;
if (this.lexer.engine.tokens.values.hasOwnProperty(this.token)) {
entry = [
this.lexer.engine.tokens.values[this.token],
entry,
this.lexer.yylloc.first_line,
this.lexer.yylloc.first_offset,
this.lexer.offset
];
} else {
entry = [
null,
entry,
this.lexer.yylloc.first_line,
this.lexer.yylloc.first_offset,
this.lexer.offset
];
}
this._tokens.push(entry);
if (this.token === this.tok.T_CLOSE_TAG) {
// https://github.com/php/php-src/blob/7ff186434e82ee7be7c59d0db9a976641cf7b09c/Zend/zend_compile.c#L1680
this.token = ";";
return this;
} else if (this.token === this.tok.T_OPEN_TAG_WITH_ECHO) {
this.token = this.tok.T_ECHO;
return this;
}
} while (
this.token === this.tok.T_WHITESPACE || // ignore white space
(!this.extractDoc &&
(this.token === this.tok.T_COMMENT || // ignore single lines comments
this.token === this.tok.T_DOC_COMMENT)) || // ignore doc comments
// ignore open tags
this.token === this.tok.T_OPEN_TAG
);
} else {
this.token = this.lexer.lex() || this.EOF;
}
return this;
};
/**
* Check if token is of specified type
*/
parser.prototype.is = function(type) {
if (Array.isArray(type)) {
return type.indexOf(this.token) !== -1;
}
return this.entries[type].has(this.token);
};
// extends the parser with syntax files
[
require("./parser/array.js"),
require("./parser/class.js"),
require("./parser/comment.js"),
require("./parser/expr.js"),
require("./parser/function.js"),
require("./parser/if.js"),
require("./parser/loops.js"),
require("./parser/main.js"),
require("./parser/namespace.js"),
require("./parser/scalar.js"),
require("./parser/statement.js"),
require("./parser/switch.js"),
require("./parser/try.js"),
require("./parser/utils.js"),
require("./parser/variable.js")
].forEach(function(ext) {
for (const k in ext) {
if (parser.prototype.hasOwnProperty(k)) {
// @see https://github.com/glayzzle/php-parser/issues/234
throw new Error("Function " + k + " is already defined - collision");
}
parser.prototype[k] = ext[k];
}
});
module.exports = parser;