-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ProcessCommonJSModules.java
1219 lines (1072 loc) · 44.6 KB
/
ProcessCommonJSModules.java
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
/*
* Copyright 2011 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.jscomp.deps.ModuleLoader.ModulePath;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.Node;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Rewrites a CommonJS module http://wiki.commonjs.org/wiki/Modules/1.1.1
* into a form that can be safely concatenated.
* Does not add a function around the module body but instead adds suffixes
* to global variables to avoid conflicts.
* Calls to require are changed to reference the required module directly.
* goog.provide and goog.require are emitted for closure compiler automatic
* ordering.
*/
public final class ProcessCommonJSModules implements CompilerPass {
private static final String EXPORTS = "exports";
private static final String MODULE = "module";
public static final DiagnosticType COMMON_JS_MODULE_LOAD_ERROR = DiagnosticType.error(
"JSC_COMMONJS_MODULE_LOAD_ERROR",
"Failed to load module \"{0}\"");
public static final DiagnosticType UNKNOWN_REQUIRE_ENSURE =
DiagnosticType.warning(
"JSC_COMMONJS_UNKNOWN_REQUIRE_ENSURE_ERROR", "Unrecognized require.ensure call: {0}");
public static final DiagnosticType SUSPICIOUS_EXPORTS_ASSIGNMENT =
DiagnosticType.warning(
"JSC_COMMONJS_SUSPICIOUS_EXPORTS_ASSIGNMENT",
"Suspicious re-assignment of \"exports\" variable."
+ " Did you actually intend to export something?");
private final Compiler compiler;
private final boolean reportDependencies;
/**
* Creates a new ProcessCommonJSModules instance which can be used to
* rewrite CommonJS modules to a concatenable form.
*
* @param compiler The compiler
*/
public ProcessCommonJSModules(Compiler compiler) {
this(compiler, true);
}
/**
* Creates a new ProcessCommonJSModules instance which can be used to
* rewrite CommonJS modules to a concatenable form.
*
* @param compiler The compiler
* @param reportDependencies Whether the rewriter should report dependency
* information to the Closure dependency manager. This needs to be true
* if we want to sort CommonJS module inputs correctly. Note that goog.provide
* and goog.require calls will still be generated if this argument is
* false.
*/
public ProcessCommonJSModules(Compiler compiler, boolean reportDependencies) {
this.compiler = compiler;
this.reportDependencies = reportDependencies;
}
/**
* Module rewriting is done a on per-file basis prior to main compilation. The pass must handle
* ES6+ syntax and the root node for each file is a SCRIPT - not the typical jsRoot of other
* passes.
*/
@Override
public void process(Node externs, Node root) {
Preconditions.checkState(root.isScript());
FindImportsAndExports finder = new FindImportsAndExports();
NodeTraversal.traverseEs6(compiler, root, finder);
ImmutableList.Builder<ExportInfo> exports = ImmutableList.builder();
if (finder.isCommonJsModule()) {
finder.reportModuleErrors();
finder.replaceUmdPatterns();
//UMD pattern replacement can leave detached export references - don't include those
for (ExportInfo export : finder.getModuleExports()) {
if (NodeUtil.getEnclosingScript(export.node) != null) {
exports.add(export);
}
}
for (ExportInfo export : finder.getExports()) {
if (NodeUtil.getEnclosingScript(export.node) != null) {
exports.add(export);
}
}
finder.addGoogProvide();
compiler.reportCodeChange();
}
NodeTraversal.traverseEs6(
compiler, root, new RewriteModule(finder.isCommonJsModule(), exports.build()));
}
/**
* Information on a Universal Module Definition A UMD is an IF statement and a reference to which
* branch contains the commonjs export
*/
static class UmdPattern {
final Node ifRoot;
final Node activeBranch;
UmdPattern(Node ifRoot, Node activeBranch) {
this.ifRoot = ifRoot;
this.activeBranch = activeBranch;
}
}
static class ExportInfo {
final Node node;
final Scope scope;
ExportInfo(Node node, Scope scope) {
this.node = node;
this.scope = scope;
}
}
private Node getBaseQualifiedNameNode(Node n) {
Node refParent = n;
while (refParent.getParent() != null && refParent.getParent().isQualifiedName()) {
refParent = refParent.getParent();
}
return refParent;
}
/**
* Traverse the script. Find all references to CommonJS require (import) and module.exports or
* export statements. Add goog.require statements for any require statements. Rewrites any require
* calls to reference the rewritten module name.
*/
class FindImportsAndExports implements NodeTraversal.Callback {
private boolean hasGoogProvideOrModule = false;
private Node script = null;
boolean isCommonJsModule() {
return (exports.size() > 0 || moduleExports.size() > 0) && !hasGoogProvideOrModule;
}
List<UmdPattern> umdPatterns = new ArrayList<>();
List<ExportInfo> moduleExports = new ArrayList<>();
List<ExportInfo> exports = new ArrayList<>();
Set<String> imports = new HashSet<>();
List<JSError> errors = new ArrayList<>();
public List<ExportInfo> getModuleExports() {
return ImmutableList.copyOf(moduleExports);
}
public List<ExportInfo> getExports() {
return ImmutableList.copyOf(exports);
}
@Override
public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) {
if (n.isScript()) {
Preconditions.checkState(this.script == null);
this.script = n;
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (t.inGlobalScope()) {
// Check for goog.provide or goog.module statements
if (parent == null
|| NodeUtil.isControlStructure(parent)
|| NodeUtil.isStatementBlock(parent)) {
if (n.isExprResult()) {
Node maybeGetProp = n.getFirstFirstChild();
if (maybeGetProp != null
&& (maybeGetProp.matchesQualifiedName("goog.provide")
|| maybeGetProp.matchesQualifiedName("goog.module"))) {
hasGoogProvideOrModule = true;
}
}
}
}
// Find require.ensure calls
if (n.isCall() && n.getFirstChild().matchesQualifiedName("require.ensure")) {
visitRequireEnsureCall(t, n);
}
if (n.matchesQualifiedName("module.exports")) {
Var v = t.getScope().getVar(MODULE);
// only rewrite "module.exports" if "module" is a free variable,
// meaning it is not defined in the current scope as a local
// variable or function parameter
if (v == null) {
moduleExports.add(new ExportInfo(n, t.getScope()));
// If the module.exports statement is nested in the then branch of an if statement,
// assume the if statement is an UMD pattern with a common js export in the then branch
// This seems fragile but has worked well for a long time.
// TODO(ChadKillingsworth): Discover if there is a better way to detect these.
Node ifAncestor = getOutermostIfAncestor(parent);
if (ifAncestor != null && !umdPatternsContains(umdPatterns, ifAncestor)) {
umdPatterns.add(new UmdPattern(ifAncestor, ifAncestor.getSecondChild()));
}
}
} else if (n.matchesQualifiedName("define.amd")) {
// If a define.amd statement is nested in the then branch of an if statement,
// assume the if statement is an UMD pattern with a common js export
// in the else branch
// This seems fragile but has worked well for a long time.
// TODO(ChadKillingsworth): Discover if there is a better way to detect these.
Node ifAncestor = getOutermostIfAncestor(parent);
if (ifAncestor != null && !umdPatternsContains(umdPatterns, ifAncestor)) {
umdPatterns.add(new UmdPattern(ifAncestor, ifAncestor.getChildAtIndex(2)));
}
}
if (n.isName() && EXPORTS.equals(n.getString())) {
Var v = t.getScope().getVar(EXPORTS);
if (v == null || v.isGlobal()) {
Node qNameRoot = getBaseQualifiedNameNode(n);
if (qNameRoot != null
&& EXPORTS.equals(qNameRoot.getQualifiedName())
&& NodeUtil.isLValue(qNameRoot)) {
if (!this.hasGoogProvideOrModule) {
errors.add(t.makeError(qNameRoot, SUSPICIOUS_EXPORTS_ASSIGNMENT));
}
} else {
exports.add(new ExportInfo(n, t.getScope()));
// If the exports statement is nested in the then branch of an if statement,
// assume the if statement is an UMD pattern with a common js export in the then branch
// This seems fragile but has worked well for a long time.
// TODO(ChadKillingsworth): Discover if there is a better way to detect these.
Node ifAncestor = getOutermostIfAncestor(parent);
if (ifAncestor != null && !umdPatternsContains(umdPatterns, ifAncestor)) {
umdPatterns.add(new UmdPattern(ifAncestor, ifAncestor.getSecondChild()));
}
}
}
}
if (n.isCall()
&& n.getChildCount() == 2
&& n.getFirstChild().matchesQualifiedName("require")
&& n.getSecondChild().isString()) {
visitRequireCall(t, n, parent);
}
}
/** Visit require calls. Emit corresponding goog.require call. */
private void visitRequireCall(NodeTraversal t, Node require, Node parent) {
String requireName = require.getSecondChild().getString();
ModulePath modulePath = t.getInput().getPath().resolveCommonJsModule(requireName);
if (modulePath == null) {
compiler.report(t.makeError(require, COMMON_JS_MODULE_LOAD_ERROR, requireName));
return;
}
String moduleName = modulePath.toModuleName();
// When require("name") is used as a standalone statement (the result isn't used)
// it indicates that a module is being loaded for the side effects it produces.
// In this case the require statement should just be removed as the goog.require
// call inserted will import the module.
if (!NodeUtil.isExpressionResultUsed(require)
&& parent.isExprResult()
&& NodeUtil.isStatementBlock(parent.getParent())) {
parent.getParent().removeChild(parent);
}
if (imports.add(moduleName)) {
if (reportDependencies) {
t.getInput().addRequire(moduleName);
}
this.script.addChildToFront(
IR.exprResult(
IR.call(
IR.getprop(IR.name("goog"), IR.string("require")), IR.string(moduleName)))
.useSourceInfoIfMissingFromForTree(require));
compiler.reportCodeChange();
}
}
/**
* Visit require.ensure calls. Replace the call with an IIFE. Require.ensure must always be of
* the form:
*
* <p>require.ensure(['module1', ...], function(require) {})
*/
private void visitRequireEnsureCall(NodeTraversal t, Node call) {
if (call.getChildCount() != 3) {
compiler.report(
t.makeError(
call,
UNKNOWN_REQUIRE_ENSURE,
"Expected the function to have 2 arguments but instead found {0}",
"" + call.getChildCount()));
return;
}
Node dependencies = call.getSecondChild();
if (!dependencies.isArrayLit()) {
compiler.report(
t.makeError(
dependencies,
UNKNOWN_REQUIRE_ENSURE,
"The first argument must be an array literal of string literals."));
return;
}
for (Node dep : dependencies.children()) {
if (!dep.isString()) {
compiler.report(
t.makeError(
dep,
UNKNOWN_REQUIRE_ENSURE,
"The first argument must be an array literal of string literals."));
return;
}
}
Node callback = dependencies.getNext();
if (!(callback.isFunction()
&& callback.getSecondChild().getChildCount() == 1
&& callback.getSecondChild().getFirstChild().isName()
&& "require".equals(callback.getSecondChild().getFirstChild().getString()))) {
compiler.report(
t.makeError(
callback,
UNKNOWN_REQUIRE_ENSURE,
"The second argument must be a function"
+ " whose first argument is named \"require\"."));
return;
}
callback.detach();
// Remove the "require" argument from the parameter list.
callback.getSecondChild().removeChildren();
call.removeChildren();
call.putBooleanProp(Node.FREE_CALL, true);
call.addChildToFront(callback);
compiler.reportCodeChange();
}
void reportModuleErrors() {
for (JSError error : errors) {
compiler.report(error);
}
}
/**
* Add a goog.provide statement for the module. If the export is directly assigned more than
* once, or the assignments are not global, declare the module name variable.
*
* <p>If all of the assignments are simply property assignments, initialize the module name
* variable as a namespace.
*/
void addGoogProvide() {
CompilerInput ci = compiler.getInput(this.script.getInputId());
ModulePath modulePath = ci.getPath();
if (modulePath == null) {
return;
}
String moduleName = modulePath.toModuleName();
// Add goog.provide calls.
if (reportDependencies) {
ci.addProvide(moduleName);
}
this.script.addChildToFront(
IR.exprResult(
IR.call(IR.getprop(IR.name("goog"), IR.string("provide")), IR.string(moduleName)))
.useSourceInfoIfMissingFromForTree(this.script));
// The default declaration for the goog.provide is a constant so
// we need to declare the variable if we have more than one
// assignment to module.exports or those assignments are not
// at the top level.
//
// If we assign to the variable more than once or all the assignments
// are properties, initialize the variable as well.
int directAssignmentsAtTopLevel = 0;
int directAssignments = 0;
for (ExportInfo export : moduleExports) {
if (NodeUtil.getEnclosingScript(export.node) == null) {
continue;
}
Node base = getBaseQualifiedNameNode(export.node);
if (base == export.node && export.node.getParent().isAssign()) {
Node rValue = NodeUtil.getRValueOfLValue(export.node);
if (rValue == null || !rValue.isObjectLit()) {
directAssignments++;
if (export.node.getParent().getParent().isExprResult()
&& NodeUtil.isTopLevel(export.node.getParent().getParent().getParent())) {
directAssignmentsAtTopLevel++;
}
}
}
}
if (directAssignmentsAtTopLevel > 1
|| (directAssignmentsAtTopLevel == 0 && directAssignments > 0)
|| directAssignments == 0) {
int totalExportStatements = this.moduleExports.size() + this.exports.size();
Node initModule = IR.var(IR.name(moduleName));
if (directAssignments < totalExportStatements) {
initModule.getFirstChild().addChildToFront(IR.objectlit());
// If all the assignments are property exports, initialize the
// module as a namespace
if (directAssignments == 0) {
JSDocInfoBuilder builder = new JSDocInfoBuilder(true);
builder.recordConstancy();
initModule.setJSDocInfo(builder.build());
}
}
initModule.useSourceInfoIfMissingFromForTree(this.script);
Node refChild = this.script.getFirstChild();
while (refChild.getNext() != null & refChild.getNext().isExprResult()
&& refChild.getNext().getFirstChild().isCall()
&& (refChild.getNext().getFirstFirstChild().matchesQualifiedName("goog.require")
|| refChild.getNext().getFirstFirstChild().matchesQualifiedName("goog.provide"))) {
refChild = refChild.getNext();
}
this.script.addChildAfter(initModule, refChild);
}
}
/** Find the outermost if node ancestor for a node without leaving the function scope */
private Node getOutermostIfAncestor(Node n) {
if (n == null || NodeUtil.isTopLevel(n) || n.isFunction()) {
return null;
}
Node parent = n.getParent();
if (parent == null) {
return null;
}
if (parent.isIf() && parent.getFirstChild() == n) {
Node outerIf = getOutermostIfAncestor(parent);
if (outerIf != null) {
return outerIf;
}
return parent;
}
return getOutermostIfAncestor(parent);
}
/** Remove a Universal Module Definition and leave just the commonjs export statement */
void replaceUmdPatterns() {
for (UmdPattern umdPattern : umdPatterns) {
Node p = umdPattern.ifRoot.getParent();
Node newNode = umdPattern.activeBranch;
if (newNode == null) {
p.removeChild(umdPattern.ifRoot);
return;
}
// Remove redundant block node. Not strictly necessary, but makes tests more legible.
if (umdPattern.activeBranch.isBlock() && umdPattern.activeBranch.getChildCount() == 1) {
newNode = umdPattern.activeBranch.getFirstChild();
umdPattern.activeBranch.detachChildren();
} else {
umdPattern.ifRoot.detachChildren();
}
p.replaceChild(umdPattern.ifRoot, newNode);
}
}
}
private static boolean umdPatternsContains(List<UmdPattern> umdPatterns, Node n) {
for (UmdPattern umd : umdPatterns) {
if (umd.ifRoot == n) {
return true;
}
}
return false;
}
/**
* Traverse a file and rewrite all references to imported names directly to the targeted module
* name.
*
* <p>If a file is a CommonJS module, rewrite export statements. Typically exports create an alias
* - the rewriting tries to avoid such aliases.
*/
private class RewriteModule extends AbstractPostOrderCallback {
private final boolean allowFullRewrite;
private final ImmutableCollection<ExportInfo> exports;
private final List<Node> imports = new ArrayList<>();
private final List<Node> rewrittenClassExpressions = new ArrayList<>();
public RewriteModule(boolean allowFullRewrite, ImmutableCollection<ExportInfo> exports) {
this.allowFullRewrite = allowFullRewrite;
this.exports = exports;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case SCRIPT:
// Class names can't be changed during the middle of a traversal. Unlike functions,
// the name can be the EMPTY token rather than just a zero length string.
for (Node clazz : rewrittenClassExpressions) {
clazz.replaceChild(
clazz.getFirstChild(), IR.empty().useSourceInfoFrom(clazz.getFirstChild()));
compiler.reportCodeChange();
}
for (ExportInfo export : exports) {
visitExport(t, export.node);
}
for (Node require : imports) {
visitRequireCall(t, require, require.getParent());
}
break;
case CALL:
if (n.getChildCount() == 2
&& n.getFirstChild().matchesQualifiedName("require")
&& n.getSecondChild().isString()) {
imports.add(n);
}
break;
case NAME:
{
String qName = n.getQualifiedName();
if (qName == null) {
break;
}
Var nameDeclaration = t.getScope().getVar(qName);
if (nameDeclaration != null
&& nameDeclaration.getNode() != null
&& nameDeclaration.getNode().getInputId() == n.getInputId()) {
maybeUpdateName(t, n, nameDeclaration);
}
break;
}
// ES6 object literal shorthand notation can refer to renamed variables
case STRING_KEY:
{
if (n.hasChildren()
|| n.isQuotedString()
|| n.getParent().getParent().isDestructuringLhs()) {
break;
}
Var nameDeclaration = t.getScope().getVar(n.getString());
if (nameDeclaration == null) {
break;
}
String importedName = getModuleImportName(t, nameDeclaration.getNode());
if (nameDeclaration.isGlobal() || importedName != null) {
Node value = IR.name(n.getString()).useSourceInfoFrom(n);
n.addChildToBack(value);
maybeUpdateName(t, value, nameDeclaration);
}
break;
}
default:
break;
}
JSDocInfo info = n.getJSDocInfo();
if (info != null) {
for (Node typeNode : info.getTypeNodes()) {
fixTypeNode(t, typeNode);
}
}
}
/**
* Visit require calls. Rewrite require statements to be a direct reference to name of require
* module. By this point all references to the import alias should have already been renamed.
*/
private void visitRequireCall(NodeTraversal t, Node require, Node parent) {
String requireName = require.getSecondChild().getString();
ModulePath modulePath = t.getInput().getPath().resolveCommonJsModule(requireName);
if (modulePath == null) {
compiler.report(t.makeError(require, COMMON_JS_MODULE_LOAD_ERROR, requireName));
return;
}
String moduleName = modulePath.toModuleName();
Node moduleRef = IR.name(moduleName).srcref(require);
parent.replaceChild(require, moduleRef);
compiler.reportCodeChange();
}
/**
* Visit export statements. Export statements can be either a direct assignment: module.exports
* = foo or a property assignment: module.exports.foo = foo; exports.foo = foo;
*/
private void visitExport(NodeTraversal t, Node export) {
Node root = getBaseQualifiedNameNode(export);
Node rValue = NodeUtil.getRValueOfLValue(root);
// For object literal assignments to module.exports, convert them to
// individual property assignments.
//
// module.exports = { foo: bar};
//
// becomes
//
// module.exports = {};
// module.exports.foo = bar;
if ("module.exports".equals(root.getQualifiedName())) {
if (rValue != null
&& rValue.isObjectLit()
&& root.getParent().isAssign()
&& root.getParent().getParent().isExprResult()) {
expandObjectLitAssignment(t, root);
return;
}
}
// If this is an assignment to module.exports or exports, renaming
// has already handled this case. Remove the export.
Var rValueVar = null;
if (rValue != null && rValue.isQualifiedName()) {
rValueVar = t.getScope().getVar(rValue.getQualifiedName());
}
if (root.getParent().isAssign()
&& (root.getNext().isName() || root.getNext().isGetProp())
&& root.getParent().getParent().isExprResult()
&& rValueVar != null) {
root.getParent().getParent().detachFromParent();
compiler.reportCodeChange();
return;
}
ModulePath modulePath = t.getInput().getPath();
String moduleName = modulePath.toModuleName();
Node updatedExport =
NodeUtil.newName(compiler, moduleName, export, export.getQualifiedName());
// Ensure that direct assignments to "module.exports" have var definitions
if ("module.exports".equals(root.getQualifiedName())
&& rValue != null
&& t.getScope().getVar("module.exports") == null
&& root.getParent().isAssign()
&& root.getParent().getParent().isExprResult()) {
Node parent = root.getParent();
Node var = IR.var(updatedExport, rValue.detach()).useSourceInfoFrom(root.getParent());
parent.getParent().replaceWith(var);
} else {
export.replaceWith(updatedExport);
}
compiler.reportCodeChange();
}
/**
* Since CommonJS modules may have only a single export, it's common to see the export be an
* object literal. We want to expand this to individual property assignments. If any individual
* property assignment has been renamed, it will be removed.
*
* <p>We need to keep assignments which aren't names
*
* <p>module.exports = { foo: bar, baz: function() {} }
*
* <p>becomes
*
* <p>module.exports.foo = bar; // removed later module.exports.baz = function() {};
*/
private void expandObjectLitAssignment(NodeTraversal t, Node export) {
Preconditions.checkState(export.getParent().isAssign());
Node insertionRef = export.getParent().getParent();
Preconditions.checkState(insertionRef.isExprResult());
Node insertionParent = insertionRef.getParent();
Preconditions.checkNotNull(insertionParent);
Node rValue = NodeUtil.getRValueOfLValue(export);
Node key = rValue.getFirstChild();
while (key != null) {
Node lhs;
if (key.isQuotedString()) {
lhs = IR.getelem(export.cloneTree(), IR.string(key.getString()));
} else {
lhs = IR.getprop(export.cloneTree(), IR.string(key.getString()));
}
Node value = null;
if (key.isStringKey()) {
if (key.hasChildren()) {
value = key.getFirstChild().detachFromParent();
} else {
value = IR.name(key.getString());
}
} else if (key.isMemberFunctionDef()) {
value = key.getFirstChild().detach();
}
Node expr = IR.exprResult(IR.assign(lhs, value)).useSourceInfoIfMissingFromForTree(key);
insertionParent.addChildAfter(expr, insertionRef);
visitExport(t, lhs.getFirstChild());
// Export statements can be removed in visitExport
if (expr.getParent() != null) {
insertionRef = expr;
}
key = key.getNext();
}
export.getParent().getParent().detach();
}
/**
* Given a name reference, check to see if it needs renamed.
*
* <p>We handle 3 main cases: 1. References to an import alias. These are replaced with a direct
* reference to the imported module. 2. Names which are exported. These are rewritten to be the
* export assignment directly. 3. Global names: If a name is global to the script, add a suffix
* so it doesn't collide with any other global.
*
* <p>Rewriting case 1 is safe to perform on all files. Cases 2 and 3 can only be done if this
* file is a commonjs module.
*/
private void maybeUpdateName(NodeTraversal t, Node n, Var var) {
Preconditions.checkNotNull(var);
Preconditions.checkState(n.isName() || n.isGetProp());
Preconditions.checkState(n.getParent() != null);
String importedModuleName = getModuleImportName(t, var.getNode());
String originalName = n.getOriginalQualifiedName();
// Check if the name refers to a alias for a require('foo') import.
if (importedModuleName != null && n != var.getNode()) {
// Reference the imported name directly, rather than the alias
updateNameReference(t, n, originalName, importedModuleName, false);
} else if (allowFullRewrite) {
String exportedName = getExportedName(t, n, var);
// We need to exclude the alias created by the require import. We assume dead
// code elimination will remove these later.
if ((n != var.getNode() || n.getParent().isClass()) && exportedName == null) {
// The name is actually the export reference itself.
// This will be handled later by visitExports.
if (n.getParent().isClass() && n.getParent().getFirstChild() == n) {
rewrittenClassExpressions.add(n.getParent());
}
return;
}
// Check if the name is used as an export
if (importedModuleName == null
&& exportedName != null
&& !exportedName.equals(originalName)) {
updateNameReference(t, n, originalName, exportedName, true);
// If it's a global name, rename it to prevent conflicts with other scripts
} else if (var.isGlobal()) {
ModulePath modulePath = t.getInput().getPath();
String currentModuleName = modulePath.toModuleName();
if (currentModuleName.equals(originalName)) {
return;
}
// refs to 'exports' are handled separately.
if (EXPORTS.equals(originalName)) {
return;
}
// closure_test_suite looks for test*() functions
if (compiler.getOptions().exportTestFunctions && currentModuleName.startsWith("test")) {
return;
}
String newName = originalName + "$$" + currentModuleName;
updateNameReference(t, n, originalName, newName, false);
}
}
}
/**
* @param nameRef the qualified name node
* @param originalName of nameRef
* @param newName for nameRef
* @param requireFunctionExpressions Whether named class or functions should be rewritten to
* variable assignments
*/
private void updateNameReference(
NodeTraversal t,
Node nameRef,
String originalName,
String newName,
boolean requireFunctionExpressions) {
Node parent = nameRef.getParent();
Preconditions.checkNotNull(parent);
Preconditions.checkNotNull(newName);
boolean newNameIsQualified = newName.indexOf('.') >= 0;
Var newNameDeclaration = t.getScope().getVar(newName);
switch (parent.getToken()) {
case CLASS:
if (parent.getIndexOfChild(nameRef) == 0
&& (newNameIsQualified || requireFunctionExpressions)) {
// Refactor a named class to a class expression
// We can't remove the class name during a traversal, so save it for later
rewrittenClassExpressions.add(parent);
Node newNameRef = NodeUtil.newQName(compiler, newName, nameRef, originalName);
Node grandparent = parent.getParent();
Node expr;
if (!newNameIsQualified && newNameDeclaration == null) {
expr = IR.let(newNameRef, IR.nullNode()).useSourceInfoIfMissingFromForTree(nameRef);
} else {
expr =
IR.exprResult(IR.assign(newNameRef, IR.nullNode()))
.useSourceInfoIfMissingFromForTree(nameRef);
}
grandparent.replaceChild(parent, expr);
if (expr.isLet()) {
expr.getFirstChild().replaceChild(expr.getFirstChild().getFirstChild(), parent);
} else {
expr.getFirstChild().replaceChild(expr.getFirstChild().getSecondChild(), parent);
}
} else if (parent.getIndexOfChild(nameRef) == 1) {
Node newNameRef = NodeUtil.newQName(compiler, newName, nameRef, originalName);
parent.replaceChild(nameRef, newNameRef);
} else {
nameRef.setString(newName);
nameRef.setOriginalName(originalName);
}
break;
case FUNCTION:
if (newNameIsQualified || requireFunctionExpressions) {
// Refactor a named function to a function expression
Node newNameRef = NodeUtil.newQName(compiler, newName, nameRef, originalName);
Node grandparent = parent.getParent();
nameRef.setString("");
Node expr;
if (!newNameIsQualified && newNameDeclaration == null) {
expr = IR.var(newNameRef, IR.nullNode()).useSourceInfoIfMissingFromForTree(nameRef);
} else {
expr =
IR.exprResult(IR.assign(newNameRef, IR.nullNode()))
.useSourceInfoIfMissingFromForTree(nameRef);
}
grandparent.replaceChild(parent, expr);
if (expr.isVar()) {
expr.getFirstChild().replaceChild(expr.getFirstChild().getFirstChild(), parent);
} else {
expr.getFirstChild().replaceChild(expr.getFirstChild().getSecondChild(), parent);
}
} else {
nameRef.setString(newName);
nameRef.setOriginalName(originalName);
}
break;
case VAR:
case LET:
case CONST:
if (newNameIsQualified) {
// Refactor a var declaration to a getprop assignment
Node getProp = NodeUtil.newQName(compiler, newName, nameRef, originalName);
JSDocInfo info = parent.getJSDocInfo();
if (info != null) {
parent.setJSDocInfo(null);
getProp.setJSDocInfo(info);
}
if (nameRef.hasChildren()) {
Node expr =
IR.exprResult(IR.assign(getProp, nameRef.getFirstChild().detachFromParent()))
.useSourceInfoIfMissingFromForTree(nameRef);
parent.replaceWith(expr);
} else {
parent.replaceWith(IR.exprResult(getProp).useSourceInfoFrom(getProp));
}
} else if (newNameDeclaration != null) {
// Variable is already defined. Convert this to an assignment.
Node name = NodeUtil.newName(compiler, newName, nameRef, originalName);
Node assign = IR.assign(name, nameRef.getFirstChild().detachFromParent());
JSDocInfo info = parent.getJSDocInfo();
if (info != null) {
parent.setJSDocInfo(null);
assign.setJSDocInfo(info);
}
parent.replaceWith(IR.exprResult(assign).useSourceInfoFromForTree(nameRef));
} else {
nameRef.setString(newName);
nameRef.setOriginalName(originalName);
}
break;
default:
{
Node name =
newNameIsQualified
? NodeUtil.newQName(compiler, newName, nameRef, originalName)
: NodeUtil.newName(compiler, newName, nameRef, originalName);
JSDocInfo info = nameRef.getJSDocInfo();
if (info != null) {
nameRef.setJSDocInfo(null);
name.setJSDocInfo(info);
}
parent.replaceChild(nameRef, name);
if (nameRef.hasChildren()) {
name.addChildrenToFront(nameRef.removeChildren());
}
break;
}
}
compiler.reportCodeChange();
}
/**
* Determine whether the given name Node n is referenced in an export
*
* @return string - If the name is not used in an export, return it's own name If the name node
* is actually the export target itself, return null;
*/
private String getExportedName(NodeTraversal t, Node n, Var var) {
if (var == null || var.getNode().getInputId() != n.getInputId()) {
return n.getQualifiedName();
}
String moduleName = t.getInput().getPath().toModuleName();
for (ExportInfo export : this.exports) {
Node exportBase = getBaseQualifiedNameNode(export.node);
Node exportRValue = NodeUtil.getRValueOfLValue(exportBase);
if (exportRValue == null) {
continue;
}
Node exportedName = getExportedNameNode(export);
// We don't want to handle the export itself
if (exportRValue == n
|| ((NodeUtil.isClassExpression(exportRValue)
|| NodeUtil.isFunctionExpression(exportRValue))
&& exportedName == n)) {
return null;
}
String exportBaseQName = exportBase.getQualifiedName();
if (exportRValue.isObjectLit()) {
if (!"module.exports".equals(exportBaseQName)) {
return n.getQualifiedName();
}