-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ProcessClosurePrimitives.java
1659 lines (1483 loc) · 56.3 KB
/
ProcessClosurePrimitives.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 2006 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.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Replaces goog.provide calls, removes goog.require calls, verifies that
* goog.require has a corresponding goog.provide and some closure specific
* simplifications.
*
* @author chrisn@google.com (Chris Nokleberg)
*/
class ProcessClosurePrimitives extends AbstractPostOrderCallback
implements HotSwapCompilerPass {
static final DiagnosticType NULL_ARGUMENT_ERROR = DiagnosticType.error(
"JSC_NULL_ARGUMENT_ERROR",
"method \"{0}\" called without an argument");
static final DiagnosticType EXPECTED_OBJECTLIT_ERROR = DiagnosticType.error(
"JSC_EXPECTED_OBJECTLIT_ERROR",
"method \"{0}\" expected an object literal argument");
static final DiagnosticType EXPECTED_STRING_ERROR = DiagnosticType.error(
"JSC_EXPECTED_STRING_ERROR",
"method \"{0}\" expected an object string argument");
static final DiagnosticType INVALID_ARGUMENT_ERROR = DiagnosticType.error(
"JSC_INVALID_ARGUMENT_ERROR",
"method \"{0}\" called with invalid argument");
static final DiagnosticType INVALID_STYLE_ERROR = DiagnosticType.error(
"JSC_INVALID_CSS_NAME_MAP_STYLE_ERROR",
"Invalid CSS name map style {0}");
static final DiagnosticType TOO_MANY_ARGUMENTS_ERROR = DiagnosticType.error(
"JSC_TOO_MANY_ARGUMENTS_ERROR",
"method \"{0}\" called with more than one argument");
static final DiagnosticType DUPLICATE_NAMESPACE_ERROR = DiagnosticType.error(
"JSC_DUPLICATE_NAMESPACE_ERROR",
"namespace \"{0}\" cannot be provided twice");
static final DiagnosticType WEAK_NAMESPACE_TYPE = DiagnosticType.warning(
"JSC_WEAK_NAMESPACE_TYPE",
"Provided symbol declared with type Object. This is rarely useful. "
+ "For more information see "
+ "https://github.com/google/closure-compiler/wiki/A-word-about-the-type-Object");
static final DiagnosticType CLASS_NAMESPACE_ERROR = DiagnosticType.error(
"JSC_CLASS_NAMESPACE_ERROR",
"\"{0}\" cannot be both provided and declared as a class. Try var {0} = class '{'...'}'");
static final DiagnosticType FUNCTION_NAMESPACE_ERROR = DiagnosticType.error(
"JSC_FUNCTION_NAMESPACE_ERROR",
"\"{0}\" cannot be both provided and declared as a function");
static final DiagnosticType MISSING_PROVIDE_ERROR = DiagnosticType.error(
"JSC_MISSING_PROVIDE_ERROR",
"required \"{0}\" namespace never provided");
static final DiagnosticType LATE_PROVIDE_ERROR = DiagnosticType.error(
"JSC_LATE_PROVIDE_ERROR",
"required \"{0}\" namespace not provided yet");
static final DiagnosticType INVALID_PROVIDE_ERROR = DiagnosticType.error(
"JSC_INVALID_PROVIDE_ERROR",
"\"{0}\" is not a valid {1} qualified name");
static final DiagnosticType INVALID_DEFINE_NAME_ERROR = DiagnosticType.error(
"JSC_INVALID_DEFINE_NAME_ERROR",
"\"{0}\" is not a valid JS identifier name");
static final DiagnosticType MISSING_DEFINE_ANNOTATION = DiagnosticType.error(
"JSC_INVALID_MISSING_DEFINE_ANNOTATION",
"Missing @define annotation");
static final DiagnosticType XMODULE_REQUIRE_ERROR =
DiagnosticType.warning(
"JSC_XMODULE_REQUIRE_ERROR",
"namespace \"{0}\" is required in module {2} but provided in module {1}."
+ " Is module {2} missing a dependency on module {1}?");
static final DiagnosticType INVALID_CLOSURE_CALL_ERROR = DiagnosticType.error(
"JSC_INVALID_CLOSURE_CALL_ERROR",
"Closure dependency methods(goog.provide, goog.require, etc) must be called at file scope.");
static final DiagnosticType NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR =
DiagnosticType.error(
"JSC_NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR",
"goog.setCssNameMapping only takes an object literal with string values");
static final DiagnosticType INVALID_CSS_RENAMING_MAP = DiagnosticType.warning(
"INVALID_CSS_RENAMING_MAP",
"Invalid entries in css renaming map: {0}");
static final DiagnosticType GOOG_BASE_CLASS_ERROR = DiagnosticType.error(
"JSC_BASE_CLASS_ERROR",
"incorrect use of goog.base: {0}");
static final DiagnosticType BASE_CLASS_ERROR = DiagnosticType.error(
"JSC_BASE_CLASS_ERROR",
"incorrect use of {0}.base: {1}");
static final DiagnosticType CLOSURE_DEFINES_ERROR = DiagnosticType.error(
"JSC_CLOSURE_DEFINES_ERROR",
"Invalid CLOSURE_DEFINES definition");
static final DiagnosticType INVALID_FORWARD_DECLARE = DiagnosticType.error(
"JSC_INVALID_FORWARD_DECLARE",
"Malformed goog.forwardDeclaration");
static final DiagnosticType USE_OF_GOOG_BASE = DiagnosticType.disabled(
"JSC_USE_OF_GOOG_BASE",
"goog.base is not compatible with ES5 strict mode.\n"
+ "Please use an alternative.\n"
+ "For EcmaScript classes use the super keyword, for traditional Closure classes\n"
+ "use the class specific base method instead. For example, for the constructor MyClass:\n"
+ " MyClass.base(this, 'constructor')");
/** The root Closure namespace */
static final String GOOG = "goog";
private final AbstractCompiler compiler;
private final JSModuleGraph moduleGraph;
// The goog.provides must be processed in a deterministic order.
private final Map<String, ProvidedName> providedNames = new LinkedHashMap<>();
private final Set<String> knownClosureSubclasses = new HashSet<>();
private final List<UnrecognizedRequire> unrecognizedRequires = new ArrayList<>();
private final Set<String> exportedVariables = new HashSet<>();
private final CheckLevel requiresLevel;
private final PreprocessorSymbolTable preprocessorSymbolTable;
private final List<Node> defineCalls = new ArrayList<>();
private final boolean preserveGoogProvidesAndRequires;
private final List<Node> requiresToBeRemoved = new ArrayList<>();
private final Set<Node> maybeTemporarilyLiveNodes = new HashSet<>();
ProcessClosurePrimitives(AbstractCompiler compiler,
@Nullable PreprocessorSymbolTable preprocessorSymbolTable,
CheckLevel requiresLevel,
boolean preserveGoogProvidesAndRequires) {
this.compiler = compiler;
this.preprocessorSymbolTable = preprocessorSymbolTable;
this.moduleGraph = compiler.getModuleGraph();
this.requiresLevel = requiresLevel;
this.preserveGoogProvidesAndRequires = preserveGoogProvidesAndRequires;
// goog is special-cased because it is provided in Closure's base library.
providedNames.put(GOOG,
new ProvidedName(GOOG, null, null, false /* implicit */));
}
Set<String> getExportedVariableNames() {
return exportedVariables;
}
@Override
public void process(Node externs, Node root) {
NodeTraversal.traverseRootsEs6(compiler, this, externs, root);
for (Node n : defineCalls) {
replaceGoogDefines(n);
}
for (ProvidedName pn : providedNames.values()) {
pn.replace();
}
if (requiresLevel.isOn()) {
for (UnrecognizedRequire r : unrecognizedRequires) {
DiagnosticType error;
ProvidedName expectedName = providedNames.get(r.namespace);
if (expectedName != null && expectedName.firstNode != null) {
// The namespace ended up getting provided after it was required.
error = LATE_PROVIDE_ERROR;
} else {
error = MISSING_PROVIDE_ERROR;
}
compiler.report(JSError.make(
r.requireNode, requiresLevel, error, r.namespace));
}
}
for (Node closureRequire : requiresToBeRemoved) {
compiler.reportChangeToEnclosingScope(closureRequire);
closureRequire.detach();
}
for (Node liveNode : maybeTemporarilyLiveNodes) {
compiler.reportChangeToEnclosingScope(liveNode);
}
}
private Node getAnyValueOfType(JSDocInfo jsdoc) {
checkArgument(jsdoc.hasType());
Node typeAst = jsdoc.getType().getRoot();
checkState(typeAst.isString());
switch (typeAst.getString()) {
case "boolean":
return IR.falseNode();
case "string":
return IR.string("");
case "number":
return IR.number(0);
default:
throw new RuntimeException(typeAst.getString());
}
}
/**
* @param n
*/
private void replaceGoogDefines(Node n) {
Node parent = n.getParent();
checkState(parent.isExprResult());
String name = n.getSecondChild().getString();
JSDocInfo jsdoc = n.getJSDocInfo();
Node value =
n.isFromExterns() ? getAnyValueOfType(jsdoc).srcref(n) : n.getChildAtIndex(2).detach();
Node replacement = NodeUtil.newQNameDeclaration(compiler, name, value, jsdoc);
replacement.useSourceInfoIfMissingFromForTree(parent);
parent.replaceWith(replacement);
compiler.reportChangeToEnclosingScope(replacement);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
// TODO(bashir): Implement a real hot-swap version instead and make it fully
// consistent with the full version.
this.compiler.process(this);
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case CALL:
Node left = n.getFirstChild();
if (left.isGetProp()) {
Node name = left.getFirstChild();
if (name.isName() && GOOG.equals(name.getString())) {
// For the sake of simplicity, we report code changes
// when we see a provides/requires, and don't worry about
// reporting the change when we actually do the replacement.
String methodName = name.getNext().getString();
switch (methodName) {
case "base":
processBaseClassCall(t, n);
break;
case "define":
if (validPrimitiveCall(t, n)) {
processDefineCall(t, n, parent);
}
break;
case "require":
if (validPrimitiveCall(t, n)) {
processRequireCall(t, n, parent);
}
break;
case "provide":
if (validPrimitiveCall(t, n)) {
processProvideCall(t, n, parent);
}
break;
case "inherits":
// Note: inherits is allowed in local scope
processInheritsCall(n);
break;
case "exportSymbol":
// Note: exportSymbol is allowed in local scope
Node arg = left.getNext();
if (arg.isString()) {
String argString = arg.getString();
int dot = argString.indexOf('.');
if (dot == -1) {
exportedVariables.add(argString);
} else {
exportedVariables.add(argString.substring(0, dot));
}
}
break;
case "forwardDeclare":
if (validPrimitiveCall(t, n)) {
processForwardDeclare(t, n, parent);
}
break;
case "addDependency":
if (validPrimitiveCall(t, n)) {
processAddDependency(n, parent);
}
break;
case "setCssNameMapping":
processSetCssNameMapping(t, n, parent);
break;
default: // fall out
}
} else if (left.getLastChild().getString().equals("base")) {
// maybe an "base" setup by goog.inherits
maybeProcessClassBaseCall(t, n);
}
}
break;
case ASSIGN:
case NAME:
if (n.isName() && n.getString().equals("CLOSURE_DEFINES")) {
handleClosureDefinesValues(t, n);
} else {
// If this is an assignment to a provided name, remove the provided
// object.
handleCandidateProvideDefinition(t, n, parent);
}
break;
case EXPR_RESULT:
handleStubDefinition(t, n);
break;
case CLASS:
if (t.inGlobalHoistScope() && !NodeUtil.isClassExpression(n)) {
String name = n.getFirstChild().getString();
ProvidedName pn = providedNames.get(name);
if (pn != null) {
compiler.report(t.makeError(n, CLASS_NAMESPACE_ERROR, name));
}
}
break;
case FUNCTION:
// If this is a declaration of a provided named function, this is an
// error. Hoisted functions will explode if they're provided.
if (t.inGlobalHoistScope() && !NodeUtil.isFunctionExpression(n)) {
String name = n.getFirstChild().getString();
ProvidedName pn = providedNames.get(name);
if (pn != null) {
compiler.report(t.makeError(n, FUNCTION_NAMESPACE_ERROR, name));
}
}
break;
case GETPROP:
if (n.getFirstChild().isName()
&& !parent.isCall()
&& !parent.isAssign()
&& n.matchesQualifiedName("goog.base")) {
reportBadGoogBaseUse(t, n, "May only be called directly.");
}
break;
default:
break;
}
}
private boolean validPrimitiveCall(NodeTraversal t, Node n) {
if (!n.getParent().isExprResult() || !t.inGlobalHoistScope()) {
// Ignore invalid primitives if we didn't strip module sugar.
if (!compiler.getOptions().shouldPreserveGoogModule()) {
compiler.report(t.makeError(n, INVALID_CLOSURE_CALL_ERROR));
return false;
}
}
return true;
}
private void handleClosureDefinesValues(NodeTraversal t, Node n) {
// var CLOSURE_DEFINES = {};
if (NodeUtil.isNameDeclaration(n.getParent())
&& n.hasOneChild()
&& n.getFirstChild().isObjectLit()) {
HashMap<String, Node> builder = new HashMap<>();
builder.putAll(compiler.getDefaultDefineValues());
for (Node c : n.getFirstChild().children()) {
if (c.isStringKey()
&& c.getFirstChild() != null // Shorthand assignment
&& isValidDefineValue(c.getFirstChild())) {
builder.put(c.getString(), c.getFirstChild().cloneTree());
} else {
reportBadClosureCommonDefinesDefinition(t, c);
}
}
compiler.setDefaultDefineValues(ImmutableMap.copyOf(builder));
}
}
static boolean isValidDefineValue(Node val) {
switch (val.getToken()) {
case STRING:
case NUMBER:
case TRUE:
case FALSE:
return true;
case NEG:
return val.getFirstChild().isNumber();
default:
return false;
}
}
/**
* Handles a goog.require call.
*/
private void processRequireCall(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node arg = left.getNext();
if (verifyLastArgumentIsString(t, left, arg)) {
String ns = arg.getString();
ProvidedName provided = providedNames.get(ns);
if (provided == null || !provided.isExplicitlyProvided()) {
unrecognizedRequires.add(new UnrecognizedRequire(n, ns));
} else {
JSModule providedModule = provided.explicitModule;
if (!provided.isFromExterns()) {
checkNotNull(providedModule, n);
JSModule module = t.getModule();
if (moduleGraph != null
&& module != providedModule
&& !moduleGraph.dependsOn(module, providedModule)) {
compiler.report(
t.makeError(n, XMODULE_REQUIRE_ERROR, ns,
providedModule.getName(),
module.getName()));
}
}
}
maybeAddToSymbolTable(left);
maybeAddStringNodeToSymbolTable(arg);
// Requires should be removed before further processing.
// Some clients run closure pass multiple times, first with
// the checks for broken requires turned off. In these cases, we
// allow broken requires to be preserved by the first run to
// let them be caught in the subsequent run.
if (!preserveGoogProvidesAndRequires && (provided != null || requiresLevel.isOn())) {
requiresToBeRemoved.add(parent);
}
}
}
/**
* Handles a goog.provide call.
*/
private void processProvideCall(NodeTraversal t, Node n, Node parent) {
checkState(n.isCall());
Node left = n.getFirstChild();
Node arg = left.getNext();
if (verifyProvide(t, left, arg)) {
String ns = arg.getString();
maybeAddToSymbolTable(left);
maybeAddStringNodeToSymbolTable(arg);
if (providedNames.containsKey(ns)) {
ProvidedName previouslyProvided = providedNames.get(ns);
if (!previouslyProvided.isExplicitlyProvided()) {
previouslyProvided.addProvide(parent, t.getModule(), true);
} else {
compiler.report(
t.makeError(n, DUPLICATE_NAMESPACE_ERROR, ns));
}
} else {
registerAnyProvidedPrefixes(ns, parent, t.getModule());
providedNames.put(
ns, new ProvidedName(ns, parent, t.getModule(), true));
}
}
}
/**
* Handles a goog.define call.
*/
private void processDefineCall(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node args = left.getNext();
if (verifyDefine(t, parent, left, args)) {
Node nameNode = args;
maybeAddToSymbolTable(left);
maybeAddStringNodeToSymbolTable(nameNode);
this.defineCalls.add(n);
}
}
/**
* Handles a stub definition for a goog.provided name
* (e.g. a @typedef or a definition from externs)
*
* @param n EXPR_RESULT node.
*/
private void handleStubDefinition(NodeTraversal t, Node n) {
if (!t.inGlobalHoistScope()) {
return;
}
JSDocInfo info = n.getFirstChild().getJSDocInfo();
boolean hasStubDefinition = info != null && (n.isFromExterns() || info.hasTypedefType());
if (hasStubDefinition) {
if (n.getFirstChild().isQualifiedName()) {
String name = n.getFirstChild().getQualifiedName();
ProvidedName pn = providedNames.get(name);
if (pn != null) {
n.putBooleanProp(Node.WAS_PREVIOUSLY_PROVIDED, true);
pn.addDefinition(n, t.getModule());
} else if (n.getBooleanProp(Node.WAS_PREVIOUSLY_PROVIDED)) {
// We didn't find it in the providedNames, but it was previously marked as provided.
// This implies we're in hotswap pass and the current typedef is a provided namespace.
ProvidedName provided = new ProvidedName(name, n, t.getModule(), true);
providedNames.put(name, provided);
}
}
}
}
/**
* Handles a candidate definition for a goog.provided name.
*/
private void handleCandidateProvideDefinition(
NodeTraversal t, Node n, Node parent) {
if (t.inGlobalHoistScope()) {
String name = null;
if (n.isName() && NodeUtil.isNameDeclaration(parent)) {
name = n.getString();
} else if (n.isAssign() && parent.isExprResult()) {
name = n.getFirstChild().getQualifiedName();
}
if (name != null) {
if (parent.getBooleanProp(Node.IS_NAMESPACE)) {
processProvideFromPreviousPass(t, name, parent);
} else {
ProvidedName pn = providedNames.get(name);
if (pn != null) {
pn.addDefinition(parent, t.getModule());
}
}
}
}
}
/**
* Processes the base class call.
*/
private void processBaseClassCall(NodeTraversal t, Node n) {
// Two things must hold for every goog.base call:
// 1) We must be calling it on "this".
// 2) We must be calling it on a prototype method of the same name as
// the one we're in, OR we must be calling it from a constructor.
// If both of those things are true, then we can rewrite:
// <pre>
// function Foo() {
// goog.base(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// goog.base(this, 'bar', 1);
// };
// </pre>
// as the easy-to-optimize:
// <pre>
// function Foo() {
// BaseFoo.call(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// Foo.superClass_.bar.call(this, 1);
// };
//
// Most of the logic here is just to make sure the AST's
// structure is what we expect it to be.
// If requested report uses of goog.base.
t.report(n, USE_OF_GOOG_BASE);
if (baseUsedInClass(n)){
reportBadGoogBaseUse(t, n, "goog.base in ES6 class is not allowed. Use super instead.");
return;
}
Node callee = n.getFirstChild();
Node thisArg = callee.getNext();
if (thisArg == null || !thisArg.isThis()) {
reportBadGoogBaseUse(t, n, "First argument must be 'this'.");
return;
}
Node enclosingFnNameNode = getEnclosingDeclNameNode(n);
if (enclosingFnNameNode == null) {
reportBadGoogBaseUse(t, n, "Could not find enclosing method.");
return;
}
String enclosingQname = enclosingFnNameNode.getQualifiedName();
if (!enclosingQname.contains(".prototype.")) {
// Handle constructors.
Node enclosingParent = enclosingFnNameNode.getParent();
Node maybeInheritsExpr =
(enclosingParent.isAssign() ? enclosingParent.getParent() : enclosingParent).getNext();
Node baseClassNode = null;
if (maybeInheritsExpr != null
&& maybeInheritsExpr.isExprResult()
&& maybeInheritsExpr.getFirstChild().isCall()) {
Node callNode = maybeInheritsExpr.getFirstChild();
if (callNode.getFirstChild().matchesQualifiedName("goog.inherits")
&& callNode.getLastChild().isQualifiedName()) {
baseClassNode = callNode.getLastChild();
}
}
if (baseClassNode == null) {
reportBadGoogBaseUse(
t, n, "Could not find goog.inherits for base class");
return;
}
// We're good to go.
Node newCallee =
NodeUtil.newQName(
compiler, baseClassNode.getQualifiedName() + ".call", callee, "goog.base");
n.replaceChild(callee, newCallee);
compiler.reportChangeToEnclosingScope(newCallee);
} else {
// Handle methods.
Node methodNameNode = thisArg.getNext();
if (methodNameNode == null || !methodNameNode.isString()) {
reportBadGoogBaseUse(t, n, "Second argument must name a method.");
return;
}
String methodName = methodNameNode.getString();
String ending = ".prototype." + methodName;
if (enclosingQname == null || !enclosingQname.endsWith(ending)) {
reportBadGoogBaseUse(
t, n, "Enclosing method does not match " + methodName);
return;
}
// We're good to go.
Node className =
enclosingFnNameNode.getFirstFirstChild();
n.replaceChild(
callee,
NodeUtil.newQName(
compiler,
className.getQualifiedName() + ".superClass_." + methodName + ".call",
callee, "goog.base"));
n.removeChild(methodNameNode);
compiler.reportChangeToEnclosingScope(n);
}
}
private void maybeProcessClassBaseCall(NodeTraversal t, Node n) {
// Two things must hold for every base call:
// 1) We must be calling it on "this".
// 2) We must be calling it on a prototype method of the same name as
// the one we're in, OR we must be calling it from a constructor.
// If both of those things are true, then we can rewrite:
// <pre>
// function Foo() {
// Foo.base(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// Foo.base(this, 'bar', 1);
// };
// </pre>
// as the easy-to-optimize:
// <pre>
// function Foo() {
// BaseFoo.call(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// Foo.superClass_.bar.call(this, 1);
// };
//
// Most of the logic here is just to make sure the AST's
// structure is what we expect it to be.
if (baseUsedInClass(n)){
reportBadGoogBaseUse(t, n, "goog.base in ES6 class is not allowed. Use super instead.");
return;
}
Node callTarget = n.getFirstChild();
Node baseContainerNode = callTarget.getFirstChild();
if (!baseContainerNode.isUnscopedQualifiedName()) {
// Some unknown "base" method.
return;
}
String baseContainer = callTarget.getFirstChild().getQualifiedName();
Node enclosingFnNameNode = getEnclosingDeclNameNode(n);
if (enclosingFnNameNode == null
|| !enclosingFnNameNode.isUnscopedQualifiedName()) {
// some unknown container method.
if (knownClosureSubclasses.contains(baseContainer)) {
reportBadBaseMethodUse(t, n, baseContainer,
"Could not find enclosing method.");
}
return;
}
String enclosingQname = enclosingFnNameNode.getQualifiedName();
if (!enclosingQname.contains(".prototype.")) {
// Handle constructors.
// Check if this is some other "base" method.
if (!enclosingQname.equals(baseContainer)) {
// Report misuse of "base" methods from other known classes.
if (knownClosureSubclasses.contains(baseContainer)) {
reportBadBaseMethodUse(t, n, baseContainer, "Must be used within "
+ baseContainer + " methods");
}
return;
}
// Determine if this is a class with a "base" method created by
// goog.inherits.
Node enclosingParent = enclosingFnNameNode.getParent();
Node maybeInheritsExpr =
(enclosingParent.isAssign() ? enclosingParent.getParent() : enclosingParent).getNext();
while (maybeInheritsExpr != null && maybeInheritsExpr.isEmpty()) {
maybeInheritsExpr = maybeInheritsExpr.getNext();
}
Node baseClassNode = null;
if (maybeInheritsExpr != null
&& maybeInheritsExpr.isExprResult()
&& maybeInheritsExpr.getFirstChild().isCall()) {
Node callNode = maybeInheritsExpr.getFirstChild();
if (callNode.getFirstChild().matchesQualifiedName("goog.inherits")
&& callNode.getLastChild().isQualifiedName()) {
baseClassNode = callNode.getLastChild();
}
}
if (baseClassNode == null) {
// If there is no "goog.inherits", this might be some other "base"
// method.
return;
}
// This is the expected method, validate its parameters.
Node callee = n.getFirstChild();
Node thisArg = callee.getNext();
if (thisArg == null || !thisArg.isThis()) {
reportBadBaseMethodUse(t, n, baseContainer,
"First argument must be 'this'.");
return;
}
// Handle methods.
Node methodNameNode = thisArg.getNext();
if (methodNameNode == null
|| !methodNameNode.isString()
|| !methodNameNode.getString().equals("constructor")) {
reportBadBaseMethodUse(t, n, baseContainer,
"Second argument must be 'constructor'.");
return;
}
// We're good to go.
n.replaceChild(
callee,
NodeUtil.newQName(
compiler,
baseClassNode.getQualifiedName() + ".call",
callee, enclosingQname + ".base"));
n.removeChild(methodNameNode);
compiler.reportChangeToEnclosingScope(n);
} else {
if (!knownClosureSubclasses.contains(baseContainer)) {
// Can't determine if this is a known "class" that has a known "base"
// method.
return;
}
boolean misuseOfBase = !enclosingFnNameNode.
getFirstFirstChild().matchesQualifiedName(baseContainer);
if (misuseOfBase) {
// Report misuse of "base" methods from other known classes.
reportBadBaseMethodUse(t, n, baseContainer, "Must be used within "
+ baseContainer + " methods");
return;
}
// The super class is known.
Node callee = n.getFirstChild();
Node thisArg = callee.getNext();
if (thisArg == null || !thisArg.isThis()) {
reportBadBaseMethodUse(t, n, baseContainer,
"First argument must be 'this'.");
return;
}
// Handle methods.
Node methodNameNode = thisArg.getNext();
if (methodNameNode == null || !methodNameNode.isString()) {
reportBadBaseMethodUse(t, n, baseContainer,
"Second argument must name a method.");
return;
}
String methodName = methodNameNode.getString();
String ending = ".prototype." + methodName;
if (enclosingQname == null || !enclosingQname.endsWith(ending)) {
reportBadBaseMethodUse(t, n, baseContainer,
"Enclosing method does not match " + methodName);
return;
}
// We're good to go.
Node className =
enclosingFnNameNode.getFirstFirstChild();
n.replaceChild(
callee,
NodeUtil.newQName(
compiler,
className.getQualifiedName() + ".superClass_." + methodName + ".call",
callee, enclosingQname + ".base"));
n.removeChild(methodNameNode);
compiler.reportChangeToEnclosingScope(n);
}
}
/**
* Processes the goog.inherits call.
*/
private void processInheritsCall(Node n) {
if (n.getChildCount() == 3) {
Node subClass = n.getSecondChild();
Node superClass = subClass.getNext();
if (subClass.isUnscopedQualifiedName() && superClass.isUnscopedQualifiedName()) {
knownClosureSubclasses.add(subClass.getQualifiedName());
}
}
}
/**
* Returns the qualified name node of the function whose scope we're in,
* or null if it cannot be found.
*/
private static Node getEnclosingDeclNameNode(Node n) {
Node fn = NodeUtil.getEnclosingFunction(n);
return fn == null ? null : NodeUtil.getNameNode(fn);
}
/** Verify if goog.base call is used in a class */
private boolean baseUsedInClass(Node n){
for (Node curr = n; curr != null; curr = curr.getParent()){
if (curr.isClassMembers()) {
return true;
}
}
return false;
}
/** Reports an incorrect use of super-method calling. */
private void reportBadGoogBaseUse(
NodeTraversal t, Node n, String extraMessage) {
compiler.report(t.makeError(n, GOOG_BASE_CLASS_ERROR, extraMessage));
}
/** Reports an incorrect use of super-method calling. */
private void reportBadBaseMethodUse(
NodeTraversal t, Node n, String className, String extraMessage) {
compiler.report(t.makeError(n, BASE_CLASS_ERROR, className, extraMessage));
}
/** Reports an incorrect CLOSURE_DEFINES definition. */
private void reportBadClosureCommonDefinesDefinition(
NodeTraversal t, Node n) {
compiler.report(t.makeError(n, CLOSURE_DEFINES_ERROR));
}
/**
* Processes the output of processed-provide from a previous pass. This will
* update our data structures in the same manner as if the provide had been
* processed in this pass.
*/
private void processProvideFromPreviousPass(
NodeTraversal t, String name, Node parent) {
if (!providedNames.containsKey(name)) {
// Record this provide created on a previous pass, and create a dummy
// EXPR node as a placeholder to simulate an explicit provide.
Node expr = new Node(Token.EXPR_RESULT);
expr.useSourceInfoWithoutLengthIfMissingFromForTree(parent);
parent.getParent().addChildBefore(expr, parent);
/**
* 'expr' has been newly added to the AST, but it might be removed again before this pass
* finishes. Keep it in a list for later change reporting if it doesn't get removed again
* before the end of the pass.
*/
maybeTemporarilyLiveNodes.add(expr);
JSModule module = t.getModule();
registerAnyProvidedPrefixes(name, expr, module);
// If registerAnyProvidedPrefixes didn't add any children, add a no-op child so that
// the AST is valid.
if (!expr.hasChildren()) {
expr.addChildToBack(NodeUtil.newUndefinedNode(parent));
}
ProvidedName provided = new ProvidedName(name, expr, module, true);
providedNames.put(name, provided);
provided.addDefinition(parent, module);
} else {
// Remove this provide if it came from a previous pass since we have an
// replacement already.
if (isNamespacePlaceholder(parent)) {
compiler.reportChangeToEnclosingScope(parent);
parent.detach();
}
}
}
/**
* Processes a call to goog.setCssNameMapping(). Either the argument to
* goog.setCssNameMapping() is valid, in which case it will be used to create
* a CssRenamingMap for the compiler of this CompilerPass, or it is invalid
* and a JSCompiler error will be reported.
* @see #visit(NodeTraversal, Node, Node)
*/
private void processSetCssNameMapping(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node arg = left.getNext();
if (verifySetCssNameMapping(t, left, arg)) {
// Translate OBJECTLIT into SubstitutionMap. All keys and
// values must be strings, or an error will be thrown.
final Map<String, String> cssNames = new HashMap<>();
for (Node key = arg.getFirstChild(); key != null;
key = key.getNext()) {
Node value = key.getFirstChild();
if (!key.isStringKey()
|| value == null
|| !value.isString()) {
compiler.report(
t.makeError(n,
NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR));
return;
}
cssNames.put(key.getString(), value.getString());
}
String styleStr = "BY_PART";
if (arg.getNext() != null) {
styleStr = arg.getNext().getString();
}
final CssRenamingMap.Style style;
try {
style = CssRenamingMap.Style.valueOf(styleStr);
} catch (IllegalArgumentException e) {
compiler.report(
t.makeError(n, INVALID_STYLE_ERROR, styleStr));
return;
}