-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ClosureRewriteModule.java
1750 lines (1544 loc) · 65.6 KB
/
ClosureRewriteModule.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 2014 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 static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.javascript.jscomp.NodeTraversal.Callback;
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 com.google.javascript.rhino.Token;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Process aliases in goog.modules.
* <pre>
* goog.module('foo.Bar');
* var Baz = goog.require('foo.Baz');
* class Bar extends Baz {}
* exports = Bar;
* </pre>
*
* becomes
*
* <pre>
* class module$contents$foo$Bar_Bar extends module$exports$foo$Baz {}
* var module$exports$foo$Bar = module$contents$foo$Bar_Bar;
* </pre>
*
* and
*
* <pre>
* goog.loadModule(function(exports) {
* goog.module('foo.Bar');
* var Baz = goog.require('foo.Baz');
* class Bar extends Baz {}
* exports = Bar;
* return exports;
* })
* </pre>
*
* becomes
*
* <pre>
* class module$contents$foo$Bar_Bar extends module$exports$foo$Baz {}
* var module$exports$foo$Bar = module$contents$foo$Bar_Bar;
* </pre>
*
* @author johnlenz@google.com (John Lenz)
* @author stalcup@google.com (John Stalcup)
*/
final class ClosureRewriteModule implements HotSwapCompilerPass {
// TODO(johnlenz): handle non-namespace module identifiers aka 'foo/bar'
static final DiagnosticType INVALID_MODULE_NAMESPACE =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_MODULE_NAMESPACE",
"goog.module parameter must be string literals");
static final DiagnosticType INVALID_PROVIDE_NAMESPACE =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_PROVIDE_NAMESPACE",
"goog.provide parameter must be a string literal.");
static final DiagnosticType INVALID_REQUIRE_NAMESPACE =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_REQUIRE_NAMESPACE",
"goog.require parameter must be a string literal.");
static final DiagnosticType INVALID_FORWARD_DECLARE_NAMESPACE =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_FORWARD_DECLARE_NAMESPACE",
"goog.forwardDeclare parameter must be a string literal.");
static final DiagnosticType INVALID_GET_NAMESPACE =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_GET_NAMESPACE",
"goog.module.get parameter must be a string literal.");
static final DiagnosticType INVALID_PROVIDE_CALL =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_PROVIDE_CALL",
"goog.provide can not be called in goog.module.");
static final DiagnosticType INVALID_GET_CALL_SCOPE =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_GET_CALL_SCOPE",
"goog.module.get can not be called in global scope.");
static final DiagnosticType INVALID_GET_ALIAS =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_GET_ALIAS",
"goog.module.get should not be aliased.");
static final DiagnosticType INVALID_EXPORT_COMPUTED_PROPERTY =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_EXPORT_COMPUTED_PROPERTY",
"Computed properties are not yet supported in goog.module exports.");
static final DiagnosticType USELESS_USE_STRICT_DIRECTIVE =
DiagnosticType.disabled(
"JSC_USELESS_USE_STRICT_DIRECTIVE",
"'use strict' is unnecessary in goog.module files.");
static final DiagnosticType DUPLICATE_MODULE =
DiagnosticType.error(
"JSC_DUPLICATE_MODULE",
"Duplicate module: {0}");
static final DiagnosticType DUPLICATE_NAMESPACE =
DiagnosticType.error(
"JSC_DUPLICATE_NAMESPACE",
"Duplicate namespace: {0}");
static final DiagnosticType MISSING_MODULE_OR_PROVIDE =
DiagnosticType.error(
"JSC_MISSING_MODULE_OR_PROVIDE",
"Required namespace \"{0}\" never defined.");
static final DiagnosticType LATE_PROVIDE_ERROR =
DiagnosticType.error(
"JSC_LATE_PROVIDE_ERROR",
"Required namespace \"{0}\" not provided yet.");
static final DiagnosticType IMPORT_INLINING_SHADOWS_VAR =
DiagnosticType.error(
"JSC_IMPORT_INLINING_SHADOWS_VAR",
"Inlining of reference to import \"{1}\" shadows var \"{0}\".");
static final DiagnosticType QUALIFIED_REFERENCE_TO_GOOG_MODULE =
DiagnosticType.error(
"JSC_QUALIFIED_REFERENCE_TO_GOOG_MODULE",
"Fully qualified reference to name ''{0}'' provided by a goog.module.\n"
+ "Either use short import syntax or"
+ " convert module to use goog.module.declareLegacyNamespace.");
static final DiagnosticType ILLEGAL_DESTRUCTURING_DEFAULT_EXPORT =
DiagnosticType.error(
"JSC_ILLEGAL_DESTRUCTURING_DEFAULT_EXPORT",
"Destructuring import only allowed for importing module with named exports.\n"
+ "See https://github.com/google/closure-compiler/wiki/goog.module-style");
static final DiagnosticType ILLEGAL_DESTRUCTURING_NOT_EXPORTED =
DiagnosticType.error(
"JSC_ILLEGAL_DESTRUCTURING_NOT_EXPORTED",
"Destructuring import reference to name \"{0}\" was not exported in module {1}");
private static final ImmutableSet<String> USE_STRICT_ONLY = ImmutableSet.of("use strict");
private static final String MODULE_EXPORTS_PREFIX = "module$exports$";
private static final String MODULE_CONTENTS_PREFIX = "module$contents$";
// Prebuilt Nodes to speed up Node.matchesQualifiedName() calls
private static final Node GOOG_FORWARDDECLARE =
IR.getprop(IR.name("goog"), IR.string("forwardDeclare"));
private static final Node GOOG_LOADMODULE = IR.getprop(IR.name("goog"), IR.string("loadModule"));
private static final Node GOOG_MODULE = IR.getprop(IR.name("goog"), IR.string("module"));
private static final Node GOOG_MODULE_DECLARELEGACYNAMESPACE =
IR.getprop(GOOG_MODULE, IR.string("declareLegacyNamespace"));
private static final Node GOOG_MODULE_GET = IR.getprop(GOOG_MODULE.cloneTree(), IR.string("get"));
private static final Node GOOG_PROVIDE = IR.getprop(IR.name("goog"), IR.string("provide"));
private static final Node GOOG_REQUIRE = IR.getprop(IR.name("goog"), IR.string("require"));
private final AbstractCompiler compiler;
private final PreprocessorSymbolTable preprocessorSymbolTable;
/**
* Indicates where new nodes should be added in relation to some other node.
*/
private static enum AddAt {
BEFORE,
AFTER
}
private static enum ScopeType {
EXEC_CONTEXT,
BLOCK
}
/**
* Describes the context of an "unrecognized require" scenario so that it will be possible to
* categorize and report it as either a "not provided yet" or "not provided at all" error at the
* end.
*/
private static final class UnrecognizedRequire {
final Node requireNode;
final String legacyNamespace;
final boolean mustBeOrdered;
UnrecognizedRequire(Node requireNode, String legacyNamespace, boolean mustBeOrdered) {
this.requireNode = requireNode;
this.legacyNamespace = legacyNamespace;
this.mustBeOrdered = mustBeOrdered;
}
}
private static final class ExportDefinition {
// Null if the export is a default export (exports = expr)
@Nullable String exportName;
// Null if the export is of a @typedef
@Nullable Node rhs;
// Null if the export is of anything other than a name
@Nullable Var nameDecl;
public String toString() {
return MoreObjects.toStringHelper(this)
.add("exportName", exportName)
.add("rhs", rhs)
.add("nameDecl", nameDecl)
.omitNullValues()
.toString();
}
private static final ImmutableSet<Token> INLINABLE_NAME_PARENTS =
ImmutableSet.of(Token.VAR, Token.CONST, Token.LET, Token.FUNCTION, Token.CLASS);
static ExportDefinition newDefaultExport(NodeTraversal t, Node rhs) {
return newNamedExport(t, null, rhs);
}
static ExportDefinition newNamedExport(NodeTraversal t, String name, Node rhs) {
ExportDefinition newExport = new ExportDefinition();
newExport.exportName = name;
newExport.rhs = rhs;
if (rhs != null && (rhs.isName() || rhs.isStringKey())) {
newExport.nameDecl = t.getScope().getVar(rhs.getString());
}
return newExport;
}
String getExportPostfix() {
if (exportName == null) {
return "";
}
return "." + exportName;
}
boolean hasInlinableName(Set<Var> exportedNames) {
if (nameDecl == null
|| exportedNames.contains(nameDecl)
|| !INLINABLE_NAME_PARENTS.contains(nameDecl.getParentNode().getToken())) {
return false;
}
Node initialValue = nameDecl.getInitialValue();
if (initialValue == null || !initialValue.isCall()) {
return true;
}
Node method = initialValue.getFirstChild();
if (!method.isGetProp()) {
return true;
}
Node maybeGoog = method.getFirstChild();
if (!maybeGoog.isName() || !maybeGoog.getString().equals("goog")) {
return true;
}
String name = maybeGoog.getNext().getString();
return !name.equals("require") && !name.equals("forwardDeclare") && !name.equals("getMsg");
}
String getLocalName() {
return nameDecl.getName();
}
}
private static final class ScriptDescription {
boolean isModule;
boolean declareLegacyNamespace;
String legacyNamespace; // "a.b.c"
String contentsPrefix; // "module$contents$a$b$c_
final Set<String> topLevelNames = new HashSet<>(); // For prefixed content renaming.
final Deque<ScriptDescription> childScripts = new LinkedList<>();
final Map<String, String> namesToInlineByAlias = new HashMap<>(); // For alias inlining.
/**
* Transient state.
*/
boolean willCreateExportsObject;
boolean hasCreatedExportObject;
Node defaultExportRhs;
String defaultExportLocalName;
Set<String> namedExports = new HashSet<>();
Map<Var, ExportDefinition> exportsToInline = new HashMap<>();
// The root of the module. The MODULE_BODY node that contains the module contents.
// For recognizing top level names.
Node rootNode;
public void addChildScript(ScriptDescription childScript) {
childScripts.addLast(childScript);
}
public ScriptDescription removeFirstChildScript() {
return childScripts.removeFirst();
}
// "module$exports$a$b$c" for non-legacy modules
@Nullable String getBinaryNamespace() {
if (!this.isModule || this.declareLegacyNamespace) {
return null;
}
return MODULE_EXPORTS_PREFIX + this.legacyNamespace.replace('.', '$');
}
@Nullable
String getExportedNamespace() {
if (this.declareLegacyNamespace) {
return this.legacyNamespace;
}
return this.getBinaryNamespace();
}
}
private class ScriptRecorder implements Callback {
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (NodeUtil.isGoogModuleFile(n)) {
checkAndSetStrictModeDirective(t, n);
}
switch (n.getToken()) {
case MODULE_BODY:
recordModuleBody(n);
break;
case CALL:
Node method = n.getFirstChild();
if (!method.isGetProp()) {
break;
}
if (method.matchesQualifiedName(GOOG_MODULE)) {
recordGoogModule(t, n);
} else if (method.matchesQualifiedName(GOOG_MODULE_DECLARELEGACYNAMESPACE)) {
recordGoogDeclareLegacyNamespace();
} else if (method.matchesQualifiedName(GOOG_PROVIDE)) {
recordGoogProvide(t, n);
} else if (method.matchesQualifiedName(GOOG_REQUIRE)) {
recordGoogRequire(t, n, true /** mustBeOrdered */);
} else if (method.matchesQualifiedName(GOOG_FORWARDDECLARE) && !parent.isExprResult()) {
recordGoogForwardDeclare(t, n);
} else if (method.matchesQualifiedName(GOOG_MODULE_GET)) {
recordGoogModuleGet(t, n);
}
break;
case CLASS:
case FUNCTION:
if (isTopLevel(t, n, ScopeType.BLOCK)) {
recordTopLevelClassOrFunctionName(n);
}
break;
case CONST:
case LET:
case VAR:
if (isTopLevel(t, n, n.isVar() ? ScopeType.EXEC_CONTEXT : ScopeType.BLOCK)) {
recordTopLevelVarNames(n);
}
break;
case GETPROP:
if (isExportPropertyAssignment(n)) {
recordExportsPropertyAssignment(t, n);
}
break;
case STRING_KEY:
// Short objects must be converted first, so that we can rewrite module-global names.
if (currentScript.isModule) {
rewriteShortObjectKey(t, n);
}
break;
case NAME:
maybeRecordExportDeclaration(t, n);
break;
default:
break;
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isModuleBody()) {
popScript();
}
}
}
private class ScriptUpdater implements Callback {
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case MODULE_BODY:
if (parent.getBooleanProp(Node.GOOG_MODULE)) {
updateModuleBodyEarly(n);
} else {
return false;
}
break;
case CALL:
Node method = n.getFirstChild();
if (!method.isGetProp()) {
break;
}
if (method.matchesQualifiedName(GOOG_MODULE)) {
updateGoogModule(n);
} else if (method.matchesQualifiedName(GOOG_MODULE_DECLARELEGACYNAMESPACE)) {
updateGoogDeclareLegacyNamespace(n);
} else if (method.matchesQualifiedName(GOOG_REQUIRE)) {
updateGoogRequire(t, n);
} else if (method.matchesQualifiedName(GOOG_FORWARDDECLARE) && !parent.isExprResult()) {
updateGoogForwardDeclare(t, n);
} else if (method.matchesQualifiedName(GOOG_MODULE_GET)) {
updateGoogModuleGetCall(n);
}
break;
case GETPROP:
if (isExportPropertyAssignment(n)) {
updateExportsPropertyAssignment(n);
} else if (n.isQualifiedName()) {
checkQualifiedName(t, n);
}
break;
default:
break;
}
if (n.getJSDocInfo() != null) {
rewriteJsdoc(n.getJSDocInfo());
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case MODULE_BODY:
updateModuleBody(n);
break;
case NAME:
maybeUpdateTopLevelName(t, n);
maybeUpdateExportDeclaration(t, n);
maybeUpdateExportNameRef(n);
break;
default:
break;
}
}
}
/**
* Checks that imports of goog.module provided files are used correctly.
*/
private void checkQualifiedName(NodeTraversal t, Node qnameNode) {
String qname = qnameNode.getQualifiedName();
if (rewriteState.containsModule(qname) && !rewriteState.isLegacyModule(qname)) {
t.report(qnameNode, QUALIFIED_REFERENCE_TO_GOOG_MODULE, qname);
}
}
/**
* Rewrites JsDoc type references to match AST changes resulting from imported alias inlining,
* module content renaming of top level constructor functions and classes, and module renaming
* from fully qualified legacy namespace to its binary name.
*/
private void rewriteJsdoc(JSDocInfo info) {
for (Node typeNode : info.getTypeNodes()) {
NodeUtil.visitPreOrder(typeNode, replaceJsDocRefs, Predicates.<Node>alwaysTrue());
}
}
/**
* Rewrites JsDoc type references to match AST changes resulting from imported alias inlining,
* module content renaming of top level constructor functions and classes, and module renaming
* from fully qualified legacy namespace to its binary name.
*/
private final NodeUtil.Visitor replaceJsDocRefs =
new NodeUtil.Visitor() {
@Override
public void visit(Node typeRefNode) {
if (!typeRefNode.isString()) {
return;
}
// A type name that might be simple like "Foo" or qualified like "foo.Bar".
String typeName = typeRefNode.getString();
// Tries to rename progressively shorter type prefixes like "foo.Bar.Baz", "foo.Bar",
// "foo".
String prefixTypeName = typeName;
String suffix = "";
do {
// If the name is an alias for an imported namespace rewrite from
// "{Foo}" to
// "{module$exports$bar$Foo}" or
// "{bar.Foo}"
boolean nameIsAnAlias =
currentScript.namesToInlineByAlias.containsKey(prefixTypeName);
if (nameIsAnAlias) {
if (preprocessorSymbolTable != null) {
// Jsdoc type node is a single STRING node that spans the whole type. For example
// STRING node "bar.Foo". When rewriting modules potentially replace only "module"
// part of the type: "bar.Foo" => "module$exports$bar$Foo". So we need to remember
// that "bar" as alias. To do that we clone type node and make "bar" node from it.
Node moduleOnlyNode = typeRefNode.cloneNode();
safeSetString(moduleOnlyNode, prefixTypeName);
moduleOnlyNode.setLength(prefixTypeName.length());
maybeAddAliasToSymbolTable(moduleOnlyNode, currentScript.legacyNamespace);
}
String aliasedNamespace = currentScript.namesToInlineByAlias.get(prefixTypeName);
safeSetString(typeRefNode, aliasedNamespace + suffix);
return;
}
// If this is a module and the type name is the name of a top level var/function/class
// defined in this script then that var will have been previously renamed from Foo to
// module$contents$Foo_Foo. Update the JsDoc reference to match.
if (currentScript.isModule && currentScript.topLevelNames.contains(prefixTypeName)) {
safeSetString(typeRefNode, currentScript.contentsPrefix + typeName);
return;
}
String binaryNamespaceIfModule = rewriteState.getBinaryNamespace(prefixTypeName);
if (legacyScriptNamespacesAndPrefixes.contains(prefixTypeName)
&& binaryNamespaceIfModule == null) {
// This thing is definitely coming from a legacy script and so the fully qualified
// type name will always resolve as is.
return;
}
// If the typeName is a reference to a fully qualified legacy namespace like
// "foo.bar.Baz" of something that is actually a module then rewrite the JsDoc reference
// to "module$exports$Bar".
if (binaryNamespaceIfModule != null) {
safeSetString(typeRefNode, binaryNamespaceIfModule + suffix);
return;
}
if (prefixTypeName.contains(".")) {
prefixTypeName = prefixTypeName.substring(0, prefixTypeName.lastIndexOf('.'));
suffix = typeName.substring(prefixTypeName.length(), typeName.length());
} else {
return;
}
} while (true);
}
};
// Per script state needed for rewriting.
private Deque<ScriptDescription> scriptStack = new LinkedList<>();
private ScriptDescription currentScript = null;
// Global state tracking an association between the dotted names of goog.module()s and whether
// the goog.module declares itself as a legacy namespace.
// Allows for detecting duplicate goog.module()s and for rewriting fully qualified
// JsDoc type references to goog.module() types in legacy scripts.
static class GlobalRewriteState {
private Map<String, ScriptDescription> scriptDescriptionsByGoogModuleNamespace =
new HashMap<>();
private Multimap<Node, String> legacyNamespacesByScriptNode = HashMultimap.create();
private Set<String> legacyScriptNamespaces = new HashSet<>();
boolean containsModule(String legacyNamespace) {
return scriptDescriptionsByGoogModuleNamespace.containsKey(legacyNamespace);
}
boolean isLegacyModule(String legacyNamespace) {
checkArgument(containsModule(legacyNamespace));
return scriptDescriptionsByGoogModuleNamespace.get(legacyNamespace).declareLegacyNamespace;
}
@Nullable String getBinaryNamespace(String legacyNamespace) {
ScriptDescription script = scriptDescriptionsByGoogModuleNamespace.get(legacyNamespace);
return script == null ? null : script.getBinaryNamespace();
}
@Nullable
private String getExportedNamespaceOrScript(String legacyNamespace) {
if (legacyScriptNamespaces.contains(legacyNamespace)) {
return legacyNamespace;
}
ScriptDescription script = scriptDescriptionsByGoogModuleNamespace.get(legacyNamespace);
return script == null ? null : script.getExportedNamespace();
}
void removeRoot(Node toRemove) {
if (legacyNamespacesByScriptNode.containsKey(toRemove)) {
scriptDescriptionsByGoogModuleNamespace
.keySet()
.removeAll(legacyNamespacesByScriptNode.removeAll(toRemove));
}
}
}
private GlobalRewriteState rewriteState;
private Set<String> legacyScriptNamespacesAndPrefixes = new HashSet<>();
private List<UnrecognizedRequire> unrecognizedRequires = new ArrayList<>();
ClosureRewriteModule(
AbstractCompiler compiler,
PreprocessorSymbolTable preprocessorSymbolTable,
GlobalRewriteState moduleRewriteState) {
this.compiler = compiler;
this.preprocessorSymbolTable = preprocessorSymbolTable;
this.rewriteState = moduleRewriteState != null ? moduleRewriteState : new GlobalRewriteState();
}
private class UnwrapGoogLoadModule extends NodeTraversal.AbstractPreOrderCallback {
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case ROOT:
case SCRIPT:
return true;
case EXPR_RESULT:
Node call = n.getFirstChild();
if (isCallTo(call, GOOG_LOADMODULE) && call.getLastChild().isFunction()) {
parent.putBooleanProp(Node.GOOG_MODULE, true);
Node functionNode = call.getLastChild();
compiler.reportFunctionDeleted(functionNode);
Node moduleBody = functionNode.getLastChild().detach();
moduleBody.setToken(Token.MODULE_BODY);
n.replaceWith(moduleBody);
Node returnNode = moduleBody.getLastChild();
checkState(returnNode.isReturn(), returnNode);
returnNode.detach();
}
return false;
default:
return false;
}
}
}
@Override
public void process(Node externs, Node root) {
Deque<ScriptDescription> scriptDescriptions = new LinkedList<>();
processAllFiles(scriptDescriptions, externs);
processAllFiles(scriptDescriptions, root);
}
private void processAllFiles(Deque<ScriptDescription> scriptDescriptions, Node scriptParent) {
if (scriptParent == null) {
return;
}
NodeTraversal.traverseEs6(compiler, scriptParent, new UnwrapGoogLoadModule());
// Record all the scripts first so that the googModuleNamespaces global state can be complete
// before doing any updating also queue up scriptDescriptions for later use in ScriptUpdater
// runs.
for (Node c = scriptParent.getFirstChild(); c != null; c = c.getNext()) {
checkState(c.isScript(), c);
pushScript(new ScriptDescription());
currentScript.rootNode = c;
scriptDescriptions.addLast(currentScript);
NodeTraversal.traverseEs6(compiler, c, new ScriptRecorder());
popScript();
}
reportUnrecognizedRequires();
if (compiler.hasHaltingErrors()) {
return;
}
// Update scripts using the now complete googModuleNamespaces global state and unspool the
// scriptDescriptions that were queued up by all the recording.
for (Node c = scriptParent.getFirstChild(); c != null; c = c.getNext()) {
pushScript(scriptDescriptions.removeFirst());
NodeTraversal.traverseEs6(compiler, c, new ScriptUpdater());
popScript();
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
checkState(scriptRoot.isScript(), scriptRoot);
NodeTraversal.traverseEs6(compiler, scriptRoot, new UnwrapGoogLoadModule());
rewriteState.removeRoot(originalRoot);
pushScript(new ScriptDescription());
currentScript.rootNode = scriptRoot;
NodeTraversal.traverseEs6(compiler, scriptRoot, new ScriptRecorder());
if (compiler.hasHaltingErrors()) {
return;
}
NodeTraversal.traverseEs6(compiler, scriptRoot, new ScriptUpdater());
popScript();
reportUnrecognizedRequires();
}
private void recordModuleBody(Node moduleRoot) {
pushScript(new ScriptDescription());
currentScript.rootNode = moduleRoot;
currentScript.isModule = true;
}
private void recordGoogModule(NodeTraversal t, Node call) {
Node legacyNamespaceNode = call.getLastChild();
if (!legacyNamespaceNode.isString()) {
t.report(legacyNamespaceNode, INVALID_MODULE_NAMESPACE);
return;
}
String legacyNamespace = legacyNamespaceNode.getString();
currentScript.legacyNamespace = legacyNamespace;
currentScript.contentsPrefix = toModuleContentsPrefix(legacyNamespace);
// If some other script is advertising itself as a goog.module() with this same namespace.
if (rewriteState.containsModule(legacyNamespace)) {
t.report(call, DUPLICATE_MODULE, legacyNamespace);
}
if (rewriteState.legacyScriptNamespaces.contains(legacyNamespace)) {
t.report(call, DUPLICATE_NAMESPACE, legacyNamespace);
}
rewriteState.scriptDescriptionsByGoogModuleNamespace.put(legacyNamespace, currentScript);
rewriteState.legacyNamespacesByScriptNode.put(NodeUtil.getEnclosingScript(currentScript.rootNode), legacyNamespace);
}
private void recordGoogDeclareLegacyNamespace() {
currentScript.declareLegacyNamespace = true;
}
private void recordGoogProvide(NodeTraversal t, Node call) {
Node legacyNamespaceNode = call.getLastChild();
if (!legacyNamespaceNode.isString()) {
t.report(legacyNamespaceNode, INVALID_PROVIDE_NAMESPACE);
return;
}
String legacyNamespace = legacyNamespaceNode.getString();
if (currentScript.isModule) {
t.report(legacyNamespaceNode, INVALID_PROVIDE_CALL);
}
if (rewriteState.containsModule(legacyNamespace)) {
t.report(call, DUPLICATE_NAMESPACE, legacyNamespace);
}
// Log legacy namespaces and prefixes.
rewriteState.legacyScriptNamespaces.add(legacyNamespace);
rewriteState.legacyNamespacesByScriptNode.put(NodeUtil.getEnclosingScript(call), legacyNamespace);
LinkedList<String> parts = Lists.newLinkedList(Splitter.on('.').split(legacyNamespace));
while (!parts.isEmpty()) {
legacyScriptNamespacesAndPrefixes.add(Joiner.on('.').join(parts));
parts.removeLast();
}
}
private void recordGoogRequire(NodeTraversal t, Node call, boolean mustBeOrdered) {
maybeSplitMultiVar(call);
Node legacyNamespaceNode = call.getLastChild();
if (!legacyNamespaceNode.isString()) {
t.report(legacyNamespaceNode, INVALID_REQUIRE_NAMESPACE);
return;
}
String legacyNamespace = legacyNamespaceNode.getString();
// Maybe report an error if there is an attempt to import something that is expected to be a
// goog.module() but no such goog.module() has been defined.
boolean targetIsAModule = rewriteState.containsModule(legacyNamespace);
boolean targetIsALegacyScript = rewriteState.legacyScriptNamespaces.contains(legacyNamespace);
if (currentScript.isModule
&& !targetIsAModule
&& !targetIsALegacyScript) {
unrecognizedRequires.add(new UnrecognizedRequire(call, legacyNamespace, mustBeOrdered));
}
}
private void recordGoogForwardDeclare(NodeTraversal t, Node call) {
Node namespaceNode = call.getLastChild();
if (call.getChildCount() != 2 || !namespaceNode.isString()) {
t.report(namespaceNode, INVALID_FORWARD_DECLARE_NAMESPACE);
return;
}
// modules already require that goog.forwardDeclare() and goog.module.get() occur in matched
// pairs. If a "missing module" error were to occur here it would also occur in the matching
// goog.module.get(). To avoid reporting the error twice suppress it here.
boolean mustBeOrdered = false;
// For purposes of import collection goog.forwardDeclare is the same as goog.require;
recordGoogRequire(t, call, mustBeOrdered);
}
private void recordGoogModuleGet(NodeTraversal t, Node call) {
Node legacyNamespaceNode = call.getLastChild();
if (call.getChildCount() != 2 || !legacyNamespaceNode.isString()) {
t.report(legacyNamespaceNode, INVALID_GET_NAMESPACE);
return;
}
if (!currentScript.isModule && t.inGlobalScope()) {
t.report(legacyNamespaceNode, INVALID_GET_CALL_SCOPE);
return;
}
String legacyNamespace = legacyNamespaceNode.getString();
if (!rewriteState.containsModule(legacyNamespace)) {
unrecognizedRequires.add(
new UnrecognizedRequire(call, legacyNamespace, false /** mustBeOrderd */));
}
String aliasName = null;
Node maybeAssign = call.getParent();
boolean isFillingAnAlias = maybeAssign.isAssign() && maybeAssign.getFirstChild().isName()
&& maybeAssign.getParent().isExprResult();
if (isFillingAnAlias && currentScript.isModule) {
aliasName = call.getParent().getFirstChild().getString();
// If the assignment isn't into a var in our scope then it's not ok.
Var aliasVar = t.getScope().getVar(aliasName);
if (aliasVar == null) {
t.report(call, INVALID_GET_ALIAS);
return;
}
// Even if it was to a var in our scope it should still only rewrite if the var looked like:
// let x = goog.forwardDeclare('a.namespace');
Node aliasVarNodeRhs = NodeUtil.getRValueOfLValue(aliasVar.getNode());
if (aliasVarNodeRhs == null || !isCallTo(aliasVarNodeRhs, GOOG_FORWARDDECLARE)) {
t.report(call, INVALID_GET_ALIAS);
return;
}
if (!legacyNamespace.equals(aliasVarNodeRhs.getLastChild().getString())) {
t.report(call, INVALID_GET_ALIAS);
return;
}
// Each goog.module.get() calling filling an alias will have the alias importing logic
// handed at the goog.forwardDeclare call, and the corresponding goog.module.get can simply
// be removed.
compiler.reportChangeToEnclosingScope(maybeAssign);
maybeAssign.getParent().detach();
}
}
private void recordTopLevelClassOrFunctionName(Node classOrFunctionNode) {
Node nameNode = classOrFunctionNode.getFirstChild();
if (nameNode.isName() && !Strings.isNullOrEmpty(nameNode.getString())) {
String name = nameNode.getString();
currentScript.topLevelNames.add(name);
}
}
private void recordTopLevelVarNames(Node varNode) {
for (Node lhs : NodeUtil.getLhsNodesOfDeclaration(varNode)) {
String name = lhs.getString();
currentScript.topLevelNames.add(name);
}
}
private void rewriteShortObjectKey(NodeTraversal t, Node n) {
checkArgument(n.isStringKey(), n);
if (!n.hasChildren()) {
Node nameNode = IR.name(n.getString()).srcref(n);
n.addChildToBack(nameNode);
t.reportCodeChange();
}
}
private void maybeRecordExportDeclaration(NodeTraversal t, Node n) {
if (!currentScript.isModule
|| !n.getString().equals("exports")
|| !isAssignTarget(n)) {
return;
}
checkState(currentScript.defaultExportRhs == null, currentScript.defaultExportRhs);
Node exportRhs = n.getNext();
if (isNamedExportsLiteral(exportRhs)) {
boolean areAllExportsInlinable = true;
List<ExportDefinition> inlinableExports = new ArrayList<>();
for (Node key = exportRhs.getFirstChild(); key != null; key = key.getNext()) {
String exportName = key.getString();
Node rhs = key.hasChildren() ? key.getFirstChild() : key;
ExportDefinition namedExport = ExportDefinition.newNamedExport(t, exportName, rhs);
currentScript.namedExports.add(exportName);
if (currentScript.declareLegacyNamespace
|| !namedExport.hasInlinableName(currentScript.exportsToInline.keySet())) {
areAllExportsInlinable = false;
} else {
inlinableExports.add(namedExport);
}
}
if (areAllExportsInlinable) {
for (ExportDefinition export : inlinableExports) {
recordExportToInline(export);
}
NodeUtil.removeChild(n.getParent().getParent(), n.getParent());
} else {
currentScript.willCreateExportsObject = true;
}
return;
}
currentScript.defaultExportRhs = exportRhs;
currentScript.willCreateExportsObject = true;
ExportDefinition defaultExport = ExportDefinition.newDefaultExport(t, exportRhs);
if (!currentScript.declareLegacyNamespace
&& defaultExport.hasInlinableName(currentScript.exportsToInline.keySet())) {
String localName = defaultExport.getLocalName();
currentScript.defaultExportLocalName = localName;
recordExportToInline(defaultExport);
}
return;
}
private static boolean isNamedExportsLiteral(Node objLit) {
if (!objLit.isObjectLit() || !objLit.hasChildren()) {
return false;
}
for (Node key = objLit.getFirstChild(); key != null; key = key.getNext()) {
if (!key.isStringKey() || key.isQuotedString()) {
return false;
}
if (key.hasChildren() && !key.getFirstChild().isName()) {
return false;
}
}
return true;
}
private void updateModuleBodyEarly(Node moduleScopeRoot) {
pushScript(currentScript.removeFirstChildScript());
currentScript.rootNode = moduleScopeRoot;
}
private void updateGoogModule(Node call) {
checkState(currentScript.isModule, currentScript);
// If it's a goog.module() with a legacy namespace.
if (currentScript.declareLegacyNamespace) {
// Rewrite "goog.module('Foo');" as "goog.provide('Foo');".
call.getFirstChild().getLastChild().setString("provide");
compiler.reportChangeToEnclosingScope(call);
}
// If this script file isn't going to eventually create it's own exports object, then we know
// we'll need to do it ourselves, and so we might as well create it as early as possible to
// avoid ordering issues with goog.define().
if (!currentScript.willCreateExportsObject) {
checkState(!currentScript.hasCreatedExportObject, currentScript);
exportTheEmptyBinaryNamespaceAt(NodeUtil.getEnclosingStatement(call), AddAt.AFTER);
}
if (!currentScript.declareLegacyNamespace) {
// Otherwise it's a regular module and the goog.module() line can be removed.
compiler.reportChangeToEnclosingScope(call);
NodeUtil.getEnclosingStatement(call).detach();
}