-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
JavascriptParser.js
4775 lines (4505 loc) · 141 KB
/
JavascriptParser.js
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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { Parser: AcornParser } = require("acorn");
const { importAttributesOrAssertions } = require("acorn-import-attributes");
const { SyncBailHook, HookMap } = require("tapable");
const vm = require("vm");
const Parser = require("../Parser");
const StackedMap = require("../util/StackedMap");
const binarySearchBounds = require("../util/binarySearchBounds");
const memoize = require("../util/memoize");
const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
/** @typedef {import("acorn").Options} AcornOptions */
/** @typedef {import("estree").AssignmentExpression} AssignmentExpression */
/** @typedef {import("estree").BinaryExpression} BinaryExpression */
/** @typedef {import("estree").BlockStatement} BlockStatement */
/** @typedef {import("estree").SequenceExpression} SequenceExpression */
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("estree").BaseCallExpression} BaseCallExpression */
/** @typedef {import("estree").StaticBlock} StaticBlock */
/** @typedef {import("estree").ImportExpression} ImportExpression */
/** @typedef {import("estree").ClassDeclaration} ClassDeclaration */
/** @typedef {import("estree").ForStatement} ForStatement */
/** @typedef {import("estree").SwitchStatement} SwitchStatement */
/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
/** @typedef {import("estree").ClassExpression} ClassExpression */
/** @typedef {import("estree").Comment} Comment */
/** @typedef {import("estree").ConditionalExpression} ConditionalExpression */
/** @typedef {import("estree").Declaration} Declaration */
/** @typedef {import("estree").PrivateIdentifier} PrivateIdentifier */
/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").Identifier} Identifier */
/** @typedef {import("estree").VariableDeclaration} VariableDeclaration */
/** @typedef {import("estree").IfStatement} IfStatement */
/** @typedef {import("estree").LabeledStatement} LabeledStatement */
/** @typedef {import("estree").Literal} Literal */
/** @typedef {import("estree").LogicalExpression} LogicalExpression */
/** @typedef {import("estree").ChainExpression} ChainExpression */
/** @typedef {import("estree").MemberExpression} MemberExpression */
/** @typedef {import("estree").YieldExpression} YieldExpression */
/** @typedef {import("estree").MetaProperty} MetaProperty */
/** @typedef {import("estree").Property} Property */
/** @typedef {import("estree").AssignmentPattern} AssignmentPattern */
/** @typedef {import("estree").ChainElement} ChainElement */
/** @typedef {import("estree").Pattern} Pattern */
/** @typedef {import("estree").UpdateExpression} UpdateExpression */
/** @typedef {import("estree").ObjectExpression} ObjectExpression */
/** @typedef {import("estree").UnaryExpression} UnaryExpression */
/** @typedef {import("estree").ArrayExpression} ArrayExpression */
/** @typedef {import("estree").ArrayPattern} ArrayPattern */
/** @typedef {import("estree").AwaitExpression} AwaitExpression */
/** @typedef {import("estree").ThisExpression} ThisExpression */
/** @typedef {import("estree").RestElement} RestElement */
/** @typedef {import("estree").ObjectPattern} ObjectPattern */
/** @typedef {import("estree").SwitchCase} SwitchCase */
/** @typedef {import("estree").CatchClause} CatchClause */
/** @typedef {import("estree").VariableDeclarator} VariableDeclarator */
/** @typedef {import("estree").ForInStatement} ForInStatement */
/** @typedef {import("estree").ForOfStatement} ForOfStatement */
/** @typedef {import("estree").ReturnStatement} ReturnStatement */
/** @typedef {import("estree").WithStatement} WithStatement */
/** @typedef {import("estree").ThrowStatement} ThrowStatement */
/** @typedef {import("estree").MethodDefinition} MethodDefinition */
/** @typedef {import("estree").ModuleDeclaration} ModuleDeclaration */
/** @typedef {import("estree").NewExpression} NewExpression */
/** @typedef {import("estree").SpreadElement} SpreadElement */
/** @typedef {import("estree").FunctionExpression} FunctionExpression */
/** @typedef {import("estree").WhileStatement} WhileStatement */
/** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */
/** @typedef {import("estree").ExpressionStatement} ExpressionStatement */
/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
/** @typedef {import("estree").DoWhileStatement} DoWhileStatement */
/** @typedef {import("estree").TryStatement} TryStatement */
/** @typedef {import("estree").Node} AnyNode */
/** @typedef {import("estree").Program} Program */
/** @typedef {import("estree").Directive} Directive */
/** @typedef {import("estree").Statement} Statement */
/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
/** @typedef {import("estree").Super} Super */
/** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpression */
/** @typedef {import("estree").TemplateLiteral} TemplateLiteral */
/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
/**
* @template T
* @typedef {import("tapable").AsArray<T>} AsArray<T>
*/
/** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
/** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */
/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[] }} GetInfoResult */
/** @typedef {Statement | ModuleDeclaration | Expression} StatementPathItem */
/** @typedef {TODO} OnIdent */
/** @typedef {Record<string, string> & { _isLegacyAssert?: boolean }} ImportAttributes */
/** @type {string[]} */
const EMPTY_ARRAY = [];
const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01;
const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10;
const ALLOWED_MEMBER_TYPES_ALL = 0b11;
// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
const parser = AcornParser.extend(importAttributesOrAssertions);
class VariableInfo {
/**
* @param {ScopeInfo} declaredScope scope in which the variable is declared
* @param {string | true | undefined} freeName which free name the variable aliases, or true when none
* @param {TagInfo | undefined} tagInfo info about tags
*/
constructor(declaredScope, freeName, tagInfo) {
this.declaredScope = declaredScope;
this.freeName = freeName;
this.tagInfo = tagInfo;
}
}
/** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */
/** @typedef {Literal | string | null | undefined} ImportSource */
/** @typedef {Omit<AcornOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */
/**
* @typedef {object} TagInfo
* @property {any} tag
* @property {any} data
* @property {TagInfo | undefined} next
*/
/**
* @typedef {object} ScopeInfo
* @property {StackedMap<string, VariableInfo | ScopeInfo>} definitions
* @property {boolean | "arrow"} topLevelScope
* @property {boolean | string} inShorthand
* @property {boolean} inTaggedTemplateTag
* @property {boolean} inTry
* @property {boolean} isStrict
* @property {boolean} isAsmJs
*/
/** @typedef {[number, number]} Range */
/**
* @typedef {object} DestructuringAssignmentProperty
* @property {string} id
* @property {Range | undefined=} range
* @property {boolean | string} shorthand
*/
/**
* Helper function for joining two ranges into a single range. This is useful
* when working with AST nodes, as it allows you to combine the ranges of child nodes
* to create the range of the _parent node_.
* @param {[number, number]} startRange start range to join
* @param {[number, number]} endRange end range to join
* @returns {[number, number]} joined range
* @example
* ```js
* const startRange = [0, 5];
* const endRange = [10, 15];
* const joinedRange = joinRanges(startRange, endRange);
* console.log(joinedRange); // [0, 15]
* ```
*/
const joinRanges = (startRange, endRange) => {
if (!endRange) return startRange;
if (!startRange) return endRange;
return [startRange[0], endRange[1]];
};
/**
* Helper function used to generate a string representation of a
* [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression).
* @param {string} object object to name
* @param {string[]} membersReversed reversed list of members
* @returns {string} member expression as a string
* @example
* ```js
* const membersReversed = ["property1", "property2", "property3"]; // Members parsed from the AST
* const name = objectAndMembersToName("myObject", membersReversed);
*
* console.log(name); // "myObject.property1.property2.property3"
* ```
*/
const objectAndMembersToName = (object, membersReversed) => {
let name = object;
for (let i = membersReversed.length - 1; i >= 0; i--) {
name = `${name}.${membersReversed[i]}`;
}
return name;
};
/**
* Grabs the name of a given expression and returns it as a string or undefined. Has particular
* handling for [Identifiers](https://github.com/estree/estree/blob/master/es5.md#identifier),
* [ThisExpressions](https://github.com/estree/estree/blob/master/es5.md#identifier), and
* [MetaProperties](https://github.com/estree/estree/blob/master/es2015.md#metaproperty) which is
* specifically for handling the `new.target` meta property.
* @param {Expression | Super} expression expression
* @returns {string | "this" | undefined} name or variable info
*/
const getRootName = expression => {
switch (expression.type) {
case "Identifier":
return expression.name;
case "ThisExpression":
return "this";
case "MetaProperty":
return `${expression.meta.name}.${expression.property.name}`;
default:
return undefined;
}
};
/** @type {AcornOptions} */
const defaultParserOptions = {
ranges: true,
locations: true,
ecmaVersion: "latest",
sourceType: "module",
// https://github.com/tc39/proposal-hashbang
allowHashBang: true,
onComment: null
};
// regexp to match at least one "magic comment"
const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/);
const EMPTY_COMMENT_OPTIONS = {
options: null,
errors: null
};
class JavascriptParser extends Parser {
/**
* @param {"module" | "script" | "auto"} sourceType default source type
*/
constructor(sourceType = "auto") {
super();
this.hooks = Object.freeze({
/** @type {HookMap<SyncBailHook<[UnaryExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[Expression], BasicEvaluatedExpression | undefined | null>>} */
evaluate: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression | MetaProperty], BasicEvaluatedExpression | undefined | null>>} */
evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateDefinedIdentifier: new HookMap(
() => new SyncBailHook(["expression"])
),
/** @type {HookMap<SyncBailHook<[NewExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateNewExpression: new HookMap(
() => new SyncBailHook(["expression"])
),
/** @type {HookMap<SyncBailHook<[CallExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateCallExpression: new HookMap(
() => new SyncBailHook(["expression"])
),
/** @type {HookMap<SyncBailHook<[CallExpression, BasicEvaluatedExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateCallExpressionMember: new HookMap(
() => new SyncBailHook(["expression", "param"])
),
/** @type {HookMap<SyncBailHook<[Expression | Declaration | PrivateIdentifier, number], boolean | void>>} */
isPure: new HookMap(
() => new SyncBailHook(["expression", "commentsStartPosition"])
),
/** @type {SyncBailHook<[Statement | ModuleDeclaration], boolean | void>} */
preStatement: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[Statement | ModuleDeclaration], boolean | void>} */
blockPreStatement: new SyncBailHook(["declaration"]),
/** @type {SyncBailHook<[Statement | ModuleDeclaration], boolean | void>} */
statement: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[IfStatement], boolean | void>} */
statementIf: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[Expression, ClassExpression | ClassDeclaration], boolean | void>} */
classExtendsExpression: new SyncBailHook([
"expression",
"classDefinition"
]),
/** @type {SyncBailHook<[MethodDefinition | PropertyDefinition | StaticBlock, ClassExpression | ClassDeclaration], boolean | void>} */
classBodyElement: new SyncBailHook(["element", "classDefinition"]),
/** @type {SyncBailHook<[Expression, MethodDefinition | PropertyDefinition, ClassExpression | ClassDeclaration], boolean | void>} */
classBodyValue: new SyncBailHook([
"expression",
"element",
"classDefinition"
]),
/** @type {HookMap<SyncBailHook<[LabeledStatement], boolean | void>>} */
label: new HookMap(() => new SyncBailHook(["statement"])),
/** @type {SyncBailHook<[ImportDeclaration, ImportSource], boolean | void>} */
import: new SyncBailHook(["statement", "source"]),
/** @type {SyncBailHook<[ImportDeclaration, ImportSource, string, string], boolean | void>} */
importSpecifier: new SyncBailHook([
"statement",
"source",
"exportName",
"identifierName"
]),
/** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration], boolean | void>} */
export: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource], boolean | void>} */
exportImport: new SyncBailHook(["statement", "source"]),
/** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, Declaration], boolean | void>} */
exportDeclaration: new SyncBailHook(["statement", "declaration"]),
/** @type {SyncBailHook<[ExportDefaultDeclaration, FunctionDeclaration | ClassDeclaration], boolean | void>} */
exportExpression: new SyncBailHook(["statement", "declaration"]),
/** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, string, string, number | undefined], boolean | void>} */
exportSpecifier: new SyncBailHook([
"statement",
"identifierName",
"exportName",
"index"
]),
/** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource, string, string, number | undefined], boolean | void>} */
exportImportSpecifier: new SyncBailHook([
"statement",
"source",
"identifierName",
"exportName",
"index"
]),
/** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
preDeclarator: new SyncBailHook(["declarator", "statement"]),
/** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
declarator: new SyncBailHook(["declarator", "statement"]),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
pattern: new HookMap(() => new SyncBailHook(["pattern"])),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
canRename: new HookMap(() => new SyncBailHook(["initExpression"])),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
rename: new HookMap(() => new SyncBailHook(["initExpression"])),
/** @type {HookMap<SyncBailHook<[AssignmentExpression], boolean | void>>} */
assign: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[AssignmentExpression, string[]], boolean | void>>} */
assignMemberChain: new HookMap(
() => new SyncBailHook(["expression", "members"])
),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
typeof: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {SyncBailHook<[ImportExpression], boolean | void>} */
importCall: new SyncBailHook(["expression"]),
/** @type {SyncBailHook<[Expression | ForOfStatement], boolean | void>} */
topLevelAwait: new SyncBailHook(["expression"]),
/** @type {HookMap<SyncBailHook<[CallExpression], boolean | void>>} */
call: new HookMap(() => new SyncBailHook(["expression"])),
/** Something like "a.b()" */
/** @type {HookMap<SyncBailHook<[CallExpression, string[], boolean[], Range[]], boolean | void>>} */
callMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"members",
"membersOptionals",
"memberRanges"
])
),
/** Something like "a.b().c.d" */
/** @type {HookMap<SyncBailHook<[Expression, string[], CallExpression, string[], Range[]], boolean | void>>} */
memberChainOfCallMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"calleeMembers",
"callExpression",
"members",
"memberRanges"
])
),
/** Something like "a.b().c.d()"" */
/** @type {HookMap<SyncBailHook<[CallExpression, string[], CallExpression, string[], Range[]], boolean | void>>} */
callMemberChainOfCallMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"calleeMembers",
"innerCallExpression",
"members",
"memberRanges"
])
),
/** @type {SyncBailHook<[ChainExpression], boolean | void>} */
optionalChaining: new SyncBailHook(["optionalChaining"]),
/** @type {HookMap<SyncBailHook<[NewExpression], boolean | void>>} */
new: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {SyncBailHook<[BinaryExpression], boolean | void>} */
binaryExpression: new SyncBailHook(["binaryExpression"]),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
expression: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[MemberExpression, string[], boolean[], Range[]], boolean | void>>} */
expressionMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"members",
"membersOptionals",
"memberRanges"
])
),
/** @type {HookMap<SyncBailHook<[MemberExpression, string[]], boolean | void>>} */
unhandledExpressionMemberChain: new HookMap(
() => new SyncBailHook(["expression", "members"])
),
/** @type {SyncBailHook<[ConditionalExpression], boolean | void>} */
expressionConditionalOperator: new SyncBailHook(["expression"]),
/** @type {SyncBailHook<[LogicalExpression], boolean | void>} */
expressionLogicalOperator: new SyncBailHook(["expression"]),
/** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
program: new SyncBailHook(["ast", "comments"]),
/** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
finish: new SyncBailHook(["ast", "comments"])
});
this.sourceType = sourceType;
/** @type {ScopeInfo} */
this.scope = undefined;
/** @type {ParserState} */
this.state = undefined;
/** @type {Comment[] | undefined} */
this.comments = undefined;
/** @type {Set<number> | undefined} */
this.semicolons = undefined;
/** @type {StatementPathItem[]} */
this.statementPath = undefined;
/** @type {Statement | ModuleDeclaration | Expression | undefined} */
this.prevStatement = undefined;
/** @type {WeakMap<Expression, Set<DestructuringAssignmentProperty>> | undefined} */
this.destructuringAssignmentProperties = undefined;
this.currentTagData = undefined;
this.magicCommentContext = vm.createContext(undefined, {
name: "Webpack Magic Comment Parser",
codeGeneration: { strings: false, wasm: false }
});
this._initializeEvaluating();
}
_initializeEvaluating() {
this.hooks.evaluate.for("Literal").tap("JavascriptParser", _expr => {
const expr = /** @type {Literal} */ (_expr);
switch (typeof expr.value) {
case "number":
return new BasicEvaluatedExpression()
.setNumber(expr.value)
.setRange(/** @type {Range} */ (expr.range));
case "bigint":
return new BasicEvaluatedExpression()
.setBigInt(expr.value)
.setRange(/** @type {Range} */ (expr.range));
case "string":
return new BasicEvaluatedExpression()
.setString(expr.value)
.setRange(/** @type {Range} */ (expr.range));
case "boolean":
return new BasicEvaluatedExpression()
.setBoolean(expr.value)
.setRange(/** @type {Range} */ (expr.range));
}
if (expr.value === null) {
return new BasicEvaluatedExpression()
.setNull()
.setRange(/** @type {Range} */ (expr.range));
}
if (expr.value instanceof RegExp) {
return new BasicEvaluatedExpression()
.setRegExp(expr.value)
.setRange(/** @type {Range} */ (expr.range));
}
});
this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => {
const expr = /** @type {NewExpression} */ (_expr);
const callee = expr.callee;
if (callee.type !== "Identifier") return;
if (callee.name !== "RegExp") {
return this.callHooksForName(
this.hooks.evaluateNewExpression,
callee.name,
expr
);
} else if (
expr.arguments.length > 2 ||
this.getVariableInfo("RegExp") !== "RegExp"
)
return;
let regExp;
const arg1 = expr.arguments[0];
if (arg1) {
if (arg1.type === "SpreadElement") return;
const evaluatedRegExp = this.evaluateExpression(arg1);
if (!evaluatedRegExp) return;
regExp = evaluatedRegExp.asString();
if (!regExp) return;
} else {
return (
new BasicEvaluatedExpression()
// eslint-disable-next-line prefer-regex-literals
.setRegExp(new RegExp(""))
.setRange(/** @type {Range} */ (expr.range))
);
}
let flags;
const arg2 = expr.arguments[1];
if (arg2) {
if (arg2.type === "SpreadElement") return;
const evaluatedFlags = this.evaluateExpression(arg2);
if (!evaluatedFlags) return;
if (!evaluatedFlags.isUndefined()) {
flags = evaluatedFlags.asString();
if (
flags === undefined ||
!BasicEvaluatedExpression.isValidRegExpFlags(flags)
)
return;
}
}
return new BasicEvaluatedExpression()
.setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp))
.setRange(/** @type {Range} */ (expr.range));
});
this.hooks.evaluate
.for("LogicalExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {LogicalExpression} */ (_expr);
const left = this.evaluateExpression(expr.left);
let returnRight = false;
/** @type {boolean|undefined} */
let allowedRight;
if (expr.operator === "&&") {
const leftAsBool = left.asBool();
if (leftAsBool === false)
return left.setRange(/** @type {Range} */ (expr.range));
returnRight = leftAsBool === true;
allowedRight = false;
} else if (expr.operator === "||") {
const leftAsBool = left.asBool();
if (leftAsBool === true)
return left.setRange(/** @type {Range} */ (expr.range));
returnRight = leftAsBool === false;
allowedRight = true;
} else if (expr.operator === "??") {
const leftAsNullish = left.asNullish();
if (leftAsNullish === false)
return left.setRange(/** @type {Range} */ (expr.range));
if (leftAsNullish !== true) return;
returnRight = true;
} else return;
const right = this.evaluateExpression(expr.right);
if (returnRight) {
if (left.couldHaveSideEffects()) right.setSideEffects();
return right.setRange(/** @type {Range} */ (expr.range));
}
const asBool = right.asBool();
if (allowedRight === true && asBool === true) {
return new BasicEvaluatedExpression()
.setRange(/** @type {Range} */ (expr.range))
.setTruthy();
} else if (allowedRight === false && asBool === false) {
return new BasicEvaluatedExpression()
.setRange(/** @type {Range} */ (expr.range))
.setFalsy();
}
});
/**
* In simple logical cases, we can use valueAsExpression to assist us in evaluating the expression on
* either side of a [BinaryExpression](https://github.com/estree/estree/blob/master/es5.md#binaryexpression).
* This supports scenarios in webpack like conditionally `import()`'ing modules based on some simple evaluation:
*
* ```js
* if (1 === 3) {
* import("./moduleA"); // webpack will auto evaluate this and not import the modules
* }
* ```
*
* Additional scenarios include evaluation of strings inside of dynamic import statements:
*
* ```js
* const foo = "foo";
* const bar = "bar";
*
* import("./" + foo + bar); // webpack will auto evaluate this into import("./foobar")
* ```
* @param {boolean | number | bigint | string} value the value to convert to an expression
* @param {BinaryExpression | UnaryExpression} expr the expression being evaluated
* @param {boolean} sideEffects whether the expression has side effects
* @returns {BasicEvaluatedExpression | undefined} the evaluated expression
* @example
*
* ```js
* const binaryExpr = new BinaryExpression("+",
* { type: "Literal", value: 2 },
* { type: "Literal", value: 3 }
* );
*
* const leftValue = 2;
* const rightValue = 3;
*
* const leftExpr = valueAsExpression(leftValue, binaryExpr.left, false);
* const rightExpr = valueAsExpression(rightValue, binaryExpr.right, false);
* const result = new BasicEvaluatedExpression()
* .setNumber(leftExpr.number + rightExpr.number)
* .setRange(binaryExpr.range);
*
* console.log(result.number); // Output: 5
* ```
*/
const valueAsExpression = (value, expr, sideEffects) => {
switch (typeof value) {
case "boolean":
return new BasicEvaluatedExpression()
.setBoolean(value)
.setSideEffects(sideEffects)
.setRange(/** @type {Range} */ (expr.range));
case "number":
return new BasicEvaluatedExpression()
.setNumber(value)
.setSideEffects(sideEffects)
.setRange(/** @type {Range} */ (expr.range));
case "bigint":
return new BasicEvaluatedExpression()
.setBigInt(value)
.setSideEffects(sideEffects)
.setRange(/** @type {Range} */ (expr.range));
case "string":
return new BasicEvaluatedExpression()
.setString(value)
.setSideEffects(sideEffects)
.setRange(/** @type {Range} */ (expr.range));
}
};
this.hooks.evaluate
.for("BinaryExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {BinaryExpression} */ (_expr);
/**
* Evaluates a binary expression if and only if it is a const operation (e.g. 1 + 2, "a" + "b", etc.).
* @template T
* @param {(leftOperand: T, rightOperand: T) => boolean | number | bigint | string} operandHandler the handler for the operation (e.g. (a, b) => a + b)
* @returns {BasicEvaluatedExpression | undefined} the evaluated expression
*/
const handleConstOperation = operandHandler => {
const left = this.evaluateExpression(expr.left);
if (!left.isCompileTimeValue()) return;
const right = this.evaluateExpression(expr.right);
if (!right.isCompileTimeValue()) return;
const result = operandHandler(
left.asCompileTimeValue(),
right.asCompileTimeValue()
);
return valueAsExpression(
result,
expr,
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
};
/**
* Helper function to determine if two booleans are always different. This is used in `handleStrictEqualityComparison`
* to determine if an expressions boolean or nullish conversion is equal or not.
* @param {boolean} a first boolean to compare
* @param {boolean} b second boolean to compare
* @returns {boolean} true if the two booleans are always different, false otherwise
*/
const isAlwaysDifferent = (a, b) =>
(a === true && b === false) || (a === false && b === true);
/**
* @param {BasicEvaluatedExpression} left left
* @param {BasicEvaluatedExpression} right right
* @param {BasicEvaluatedExpression} res res
* @param {boolean} eql true for "===" and false for "!=="
* @returns {BasicEvaluatedExpression | undefined} result
*/
const handleTemplateStringCompare = (left, right, res, eql) => {
/**
* @param {BasicEvaluatedExpression[]} parts parts
* @returns {string} value
*/
const getPrefix = parts => {
let value = "";
for (const p of parts) {
const v = p.asString();
if (v !== undefined) value += v;
else break;
}
return value;
};
/**
* @param {BasicEvaluatedExpression[]} parts parts
* @returns {string} value
*/
const getSuffix = parts => {
let value = "";
for (let i = parts.length - 1; i >= 0; i--) {
const v = parts[i].asString();
if (v !== undefined) value = v + value;
else break;
}
return value;
};
const leftPrefix = getPrefix(
/** @type {BasicEvaluatedExpression[]} */ (left.parts)
);
const rightPrefix = getPrefix(
/** @type {BasicEvaluatedExpression[]} */ (right.parts)
);
const leftSuffix = getSuffix(
/** @type {BasicEvaluatedExpression[]} */ (left.parts)
);
const rightSuffix = getSuffix(
/** @type {BasicEvaluatedExpression[]} */ (right.parts)
);
const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length);
const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length);
const prefixMismatch =
lenPrefix > 0 &&
leftPrefix.slice(0, lenPrefix) !== rightPrefix.slice(0, lenPrefix);
const suffixMismatch =
lenSuffix > 0 &&
leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix);
if (prefixMismatch || suffixMismatch) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
};
/**
* Helper function to handle BinaryExpressions using strict equality comparisons (e.g. "===" and "!==").
* @param {boolean} eql true for "===" and false for "!=="
* @returns {BasicEvaluatedExpression | undefined} the evaluated expression
*/
const handleStrictEqualityComparison = eql => {
const left = this.evaluateExpression(expr.left);
const right = this.evaluateExpression(expr.right);
const res = new BasicEvaluatedExpression();
res.setRange(/** @type {Range} */ (expr.range));
const leftConst = left.isCompileTimeValue();
const rightConst = right.isCompileTimeValue();
if (leftConst && rightConst) {
return res
.setBoolean(
eql ===
(left.asCompileTimeValue() === right.asCompileTimeValue())
)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isArray() && right.isArray()) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isTemplateString() && right.isTemplateString()) {
return handleTemplateStringCompare(left, right, res, eql);
}
const leftPrimitive = left.isPrimitiveType();
const rightPrimitive = right.isPrimitiveType();
if (
// Primitive !== Object or
// compile-time object types are never equal to something at runtime
(leftPrimitive === false &&
(leftConst || rightPrimitive === true)) ||
(rightPrimitive === false &&
(rightConst || leftPrimitive === true)) ||
// Different nullish or boolish status also means not equal
isAlwaysDifferent(
/** @type {boolean} */ (left.asBool()),
/** @type {boolean} */ (right.asBool())
) ||
isAlwaysDifferent(
/** @type {boolean} */ (left.asNullish()),
/** @type {boolean} */ (right.asNullish())
)
) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
};
/**
* Helper function to handle BinaryExpressions using abstract equality comparisons (e.g. "==" and "!=").
* @param {boolean} eql true for "==" and false for "!="
* @returns {BasicEvaluatedExpression | undefined} the evaluated expression
*/
const handleAbstractEqualityComparison = eql => {
const left = this.evaluateExpression(expr.left);
const right = this.evaluateExpression(expr.right);
const res = new BasicEvaluatedExpression();
res.setRange(/** @type {Range} */ (expr.range));
const leftConst = left.isCompileTimeValue();
const rightConst = right.isCompileTimeValue();
if (leftConst && rightConst) {
return res
.setBoolean(
eql ===
// eslint-disable-next-line eqeqeq
(left.asCompileTimeValue() == right.asCompileTimeValue())
)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isArray() && right.isArray()) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isTemplateString() && right.isTemplateString()) {
return handleTemplateStringCompare(left, right, res, eql);
}
};
if (expr.operator === "+") {
const left = this.evaluateExpression(expr.left);
const right = this.evaluateExpression(expr.right);
const res = new BasicEvaluatedExpression();
if (left.isString()) {
if (right.isString()) {
res.setString(
/** @type {string} */ (left.string) +
/** @type {string} */ (right.string)
);
} else if (right.isNumber()) {
res.setString(/** @type {string} */ (left.string) + right.number);
} else if (
right.isWrapped() &&
right.prefix &&
right.prefix.isString()
) {
// "left" + ("prefix" + inner + "postfix")
// => ("leftPrefix" + inner + "postfix")
res.setWrapped(
new BasicEvaluatedExpression()
.setString(
/** @type {string} */ (left.string) +
/** @type {string} */ (right.prefix.string)
)
.setRange(
joinRanges(
/** @type {Range} */ (left.range),
/** @type {Range} */ (right.prefix.range)
)
),
right.postfix,
right.wrappedInnerExpressions
);
} else if (right.isWrapped()) {
// "left" + ([null] + inner + "postfix")
// => ("left" + inner + "postfix")
res.setWrapped(
left,
right.postfix,
right.wrappedInnerExpressions
);
} else {
// "left" + expr
// => ("left" + expr + "")
res.setWrapped(left, null, [right]);
}
} else if (left.isNumber()) {
if (right.isString()) {
res.setString(left.number + /** @type {string} */ (right.string));
} else if (right.isNumber()) {
res.setNumber(
/** @type {number} */ (left.number) +
/** @type {number} */ (right.number)
);
} else {
return;
}
} else if (left.isBigInt()) {
if (right.isBigInt()) {
res.setBigInt(
/** @type {bigint} */ (left.bigint) +
/** @type {bigint} */ (right.bigint)
);
}
} else if (left.isWrapped()) {
if (left.postfix && left.postfix.isString() && right.isString()) {
// ("prefix" + inner + "postfix") + "right"
// => ("prefix" + inner + "postfixRight")
res.setWrapped(
left.prefix,
new BasicEvaluatedExpression()
.setString(
/** @type {string} */ (left.postfix.string) +
/** @type {string} */ (right.string)
)
.setRange(
joinRanges(
/** @type {Range} */ (left.postfix.range),
/** @type {Range} */ (right.range)
)
),
left.wrappedInnerExpressions
);
} else if (
left.postfix &&
left.postfix.isString() &&
right.isNumber()
) {
// ("prefix" + inner + "postfix") + 123
// => ("prefix" + inner + "postfix123")
res.setWrapped(
left.prefix,
new BasicEvaluatedExpression()
.setString(
/** @type {string} */ (left.postfix.string) +
/** @type {number} */ (right.number)
)
.setRange(
joinRanges(
/** @type {Range} */ (left.postfix.range),
/** @type {Range} */ (right.range)
)
),
left.wrappedInnerExpressions
);
} else if (right.isString()) {
// ("prefix" + inner + [null]) + "right"
// => ("prefix" + inner + "right")
res.setWrapped(left.prefix, right, left.wrappedInnerExpressions);
} else if (right.isNumber()) {
// ("prefix" + inner + [null]) + 123
// => ("prefix" + inner + "123")
res.setWrapped(
left.prefix,
new BasicEvaluatedExpression()
.setString(String(right.number))
.setRange(/** @type {Range} */ (right.range)),
left.wrappedInnerExpressions
);
} else if (right.isWrapped()) {
// ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2")
// ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2")
res.setWrapped(
left.prefix,
right.postfix,
left.wrappedInnerExpressions &&
right.wrappedInnerExpressions &&
left.wrappedInnerExpressions
.concat(left.postfix ? [left.postfix] : [])
.concat(right.prefix ? [right.prefix] : [])
.concat(right.wrappedInnerExpressions)
);
} else {