-
Notifications
You must be signed in to change notification settings - Fork 370
/
GenerateJavaScriptAST.java
3039 lines (2640 loc) · 118 KB
/
GenerateJavaScriptAST.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 2008 Google Inc.
*
* 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.gwt.dev.jjs.impl;
import static com.google.gwt.dev.js.JsUtils.createAssignment;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.linker.impl.StandardSymbolData;
import com.google.gwt.dev.CompilerContext;
import com.google.gwt.dev.MinimalRebuildCache;
import com.google.gwt.dev.PrecompileTaskOptions;
import com.google.gwt.dev.cfg.PermutationProperties;
import com.google.gwt.dev.common.InliningMode;
import com.google.gwt.dev.jjs.HasSourceInfo;
import com.google.gwt.dev.jjs.InternalCompilerException;
import com.google.gwt.dev.jjs.SourceInfo;
import com.google.gwt.dev.jjs.SourceOrigin;
import com.google.gwt.dev.jjs.ast.Context;
import com.google.gwt.dev.jjs.ast.HasEnclosingType;
import com.google.gwt.dev.jjs.ast.HasName;
import com.google.gwt.dev.jjs.ast.JAbstractMethodBody;
import com.google.gwt.dev.jjs.ast.JArrayLength;
import com.google.gwt.dev.jjs.ast.JArrayRef;
import com.google.gwt.dev.jjs.ast.JArrayType;
import com.google.gwt.dev.jjs.ast.JBinaryOperation;
import com.google.gwt.dev.jjs.ast.JBinaryOperator;
import com.google.gwt.dev.jjs.ast.JBlock;
import com.google.gwt.dev.jjs.ast.JBreakStatement;
import com.google.gwt.dev.jjs.ast.JCaseStatement;
import com.google.gwt.dev.jjs.ast.JCastMap;
import com.google.gwt.dev.jjs.ast.JCastOperation;
import com.google.gwt.dev.jjs.ast.JClassLiteral;
import com.google.gwt.dev.jjs.ast.JClassType;
import com.google.gwt.dev.jjs.ast.JConditional;
import com.google.gwt.dev.jjs.ast.JConstructor;
import com.google.gwt.dev.jjs.ast.JContinueStatement;
import com.google.gwt.dev.jjs.ast.JDeclarationStatement;
import com.google.gwt.dev.jjs.ast.JDeclaredType;
import com.google.gwt.dev.jjs.ast.JDoStatement;
import com.google.gwt.dev.jjs.ast.JExpression;
import com.google.gwt.dev.jjs.ast.JExpressionStatement;
import com.google.gwt.dev.jjs.ast.JField;
import com.google.gwt.dev.jjs.ast.JFieldRef;
import com.google.gwt.dev.jjs.ast.JForStatement;
import com.google.gwt.dev.jjs.ast.JIfStatement;
import com.google.gwt.dev.jjs.ast.JInterfaceType;
import com.google.gwt.dev.jjs.ast.JLabel;
import com.google.gwt.dev.jjs.ast.JLabeledStatement;
import com.google.gwt.dev.jjs.ast.JLiteral;
import com.google.gwt.dev.jjs.ast.JLocal;
import com.google.gwt.dev.jjs.ast.JLocalRef;
import com.google.gwt.dev.jjs.ast.JMember;
import com.google.gwt.dev.jjs.ast.JMethod;
import com.google.gwt.dev.jjs.ast.JMethodBody;
import com.google.gwt.dev.jjs.ast.JMethodCall;
import com.google.gwt.dev.jjs.ast.JNameOf;
import com.google.gwt.dev.jjs.ast.JNewInstance;
import com.google.gwt.dev.jjs.ast.JNode;
import com.google.gwt.dev.jjs.ast.JNullLiteral;
import com.google.gwt.dev.jjs.ast.JNumericEntry;
import com.google.gwt.dev.jjs.ast.JParameter;
import com.google.gwt.dev.jjs.ast.JParameterRef;
import com.google.gwt.dev.jjs.ast.JPermutationDependentValue;
import com.google.gwt.dev.jjs.ast.JPostfixOperation;
import com.google.gwt.dev.jjs.ast.JPrefixOperation;
import com.google.gwt.dev.jjs.ast.JPrimitiveType;
import com.google.gwt.dev.jjs.ast.JProgram;
import com.google.gwt.dev.jjs.ast.JReferenceType;
import com.google.gwt.dev.jjs.ast.JReturnStatement;
import com.google.gwt.dev.jjs.ast.JRunAsync;
import com.google.gwt.dev.jjs.ast.JStatement;
import com.google.gwt.dev.jjs.ast.JSwitchStatement;
import com.google.gwt.dev.jjs.ast.JThisRef;
import com.google.gwt.dev.jjs.ast.JThrowStatement;
import com.google.gwt.dev.jjs.ast.JTransformer;
import com.google.gwt.dev.jjs.ast.JTryStatement;
import com.google.gwt.dev.jjs.ast.JType;
import com.google.gwt.dev.jjs.ast.JUnaryOperator;
import com.google.gwt.dev.jjs.ast.JVariable;
import com.google.gwt.dev.jjs.ast.JVisitor;
import com.google.gwt.dev.jjs.ast.JWhileStatement;
import com.google.gwt.dev.jjs.ast.js.JDebuggerStatement;
import com.google.gwt.dev.jjs.ast.js.JMultiExpression;
import com.google.gwt.dev.jjs.ast.js.JsniClassLiteral;
import com.google.gwt.dev.jjs.ast.js.JsniFieldRef;
import com.google.gwt.dev.jjs.ast.js.JsniMethodBody;
import com.google.gwt.dev.jjs.ast.js.JsniMethodRef;
import com.google.gwt.dev.jjs.ast.js.JsonArray;
import com.google.gwt.dev.jjs.impl.ResolveRuntimeTypeReferences.TypeMapper;
import com.google.gwt.dev.js.JsStackEmulator;
import com.google.gwt.dev.js.JsUtils;
import com.google.gwt.dev.js.ast.JsArrayAccess;
import com.google.gwt.dev.js.ast.JsArrayLiteral;
import com.google.gwt.dev.js.ast.JsBinaryOperation;
import com.google.gwt.dev.js.ast.JsBinaryOperator;
import com.google.gwt.dev.js.ast.JsBlock;
import com.google.gwt.dev.js.ast.JsBreak;
import com.google.gwt.dev.js.ast.JsCase;
import com.google.gwt.dev.js.ast.JsCatch;
import com.google.gwt.dev.js.ast.JsConditional;
import com.google.gwt.dev.js.ast.JsContext;
import com.google.gwt.dev.js.ast.JsContinue;
import com.google.gwt.dev.js.ast.JsDebugger;
import com.google.gwt.dev.js.ast.JsDefault;
import com.google.gwt.dev.js.ast.JsDoWhile;
import com.google.gwt.dev.js.ast.JsEmpty;
import com.google.gwt.dev.js.ast.JsExprStmt;
import com.google.gwt.dev.js.ast.JsExpression;
import com.google.gwt.dev.js.ast.JsFor;
import com.google.gwt.dev.js.ast.JsFunction;
import com.google.gwt.dev.js.ast.JsIf;
import com.google.gwt.dev.js.ast.JsInvocation;
import com.google.gwt.dev.js.ast.JsLabel;
import com.google.gwt.dev.js.ast.JsLiteral;
import com.google.gwt.dev.js.ast.JsModVisitor;
import com.google.gwt.dev.js.ast.JsName;
import com.google.gwt.dev.js.ast.JsNameOf;
import com.google.gwt.dev.js.ast.JsNameRef;
import com.google.gwt.dev.js.ast.JsNew;
import com.google.gwt.dev.js.ast.JsNode;
import com.google.gwt.dev.js.ast.JsNormalScope;
import com.google.gwt.dev.js.ast.JsNullLiteral;
import com.google.gwt.dev.js.ast.JsNumberLiteral;
import com.google.gwt.dev.js.ast.JsNumericEntry;
import com.google.gwt.dev.js.ast.JsObjectLiteral;
import com.google.gwt.dev.js.ast.JsParameter;
import com.google.gwt.dev.js.ast.JsPositionMarker;
import com.google.gwt.dev.js.ast.JsPositionMarker.Type;
import com.google.gwt.dev.js.ast.JsPostfixOperation;
import com.google.gwt.dev.js.ast.JsPrefixOperation;
import com.google.gwt.dev.js.ast.JsProgram;
import com.google.gwt.dev.js.ast.JsPropertyInitializer;
import com.google.gwt.dev.js.ast.JsReturn;
import com.google.gwt.dev.js.ast.JsRootScope;
import com.google.gwt.dev.js.ast.JsScope;
import com.google.gwt.dev.js.ast.JsStatement;
import com.google.gwt.dev.js.ast.JsStringLiteral;
import com.google.gwt.dev.js.ast.JsSwitch;
import com.google.gwt.dev.js.ast.JsSwitchMember;
import com.google.gwt.dev.js.ast.JsThisRef;
import com.google.gwt.dev.js.ast.JsThrow;
import com.google.gwt.dev.js.ast.JsTry;
import com.google.gwt.dev.js.ast.JsUnaryOperator;
import com.google.gwt.dev.js.ast.JsVars;
import com.google.gwt.dev.js.ast.JsVars.JsVar;
import com.google.gwt.dev.js.ast.JsWhile;
import com.google.gwt.dev.util.Pair;
import com.google.gwt.dev.util.StringInterner;
import com.google.gwt.dev.util.arg.OptionMethodNameDisplayMode;
import com.google.gwt.dev.util.arg.OptionOptimize;
import com.google.gwt.dev.util.collect.Stack;
import com.google.gwt.dev.util.log.speedtracer.CompilerEventType;
import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger;
import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event;
import com.google.gwt.thirdparty.guava.common.base.Function;
import com.google.gwt.thirdparty.guava.common.base.Joiner;
import com.google.gwt.thirdparty.guava.common.base.Predicate;
import com.google.gwt.thirdparty.guava.common.base.Predicates;
import com.google.gwt.thirdparty.guava.common.collect.FluentIterable;
import com.google.gwt.thirdparty.guava.common.collect.ImmutableList;
import com.google.gwt.thirdparty.guava.common.collect.ImmutableSortedSet;
import com.google.gwt.thirdparty.guava.common.collect.Iterables;
import com.google.gwt.thirdparty.guava.common.collect.Lists;
import com.google.gwt.thirdparty.guava.common.collect.Maps;
import com.google.gwt.thirdparty.guava.common.collect.Sets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
/**
* Creates a JavaScript AST from a <code>JProgram</code> node.
*/
public class GenerateJavaScriptAST {
/**
* Finds the nodes that are targets of JNameOf so that a name is assigned to them.
*/
private class FindNameOfTargets extends JVisitor {
@Override
public void endVisit(JNameOf x, Context ctx) {
nameOfTargets.add(x.getNode());
}
}
private class CreateNamesAndScopesVisitor extends JVisitor {
/**
* Cache of computed Java source file names to URI strings for symbol
* export. By using a cache we also ensure the miminum number of String
* instances are serialized.
*/
private final Map<String, String> fileNameToUriString = Maps.newHashMap();
private final Stack<JsScope> scopeStack = new Stack<JsScope>();
@Override
public boolean visit(JProgram x, Context ctx) {
// Scopes and name objects need to be calculated within all types, even reference-only ones.
// This information is used to be able to detect and avoid name collisions during pretty or
// obfuscated JS variable name generation.
x.visitAllTypes(this);
return false;
}
@Override
public void endVisit(JArrayType x, Context ctx) {
JsName name = topScope.declareName(x.getName());
names.put(x, name);
recordSymbol(x, name);
}
@Override
public void endVisit(JClassType x, Context ctx) {
scopeStack.pop();
}
@Override
public void endVisit(JField x, Context ctx) {
JsName jsName;
if (x.isStatic()) {
jsName = topScope.declareName(mangleName(x), x.getName());
} else {
jsName =
x.isJsProperty()
? scopeStack.peek().declareUnobfuscatableName(x.getJsName())
: scopeStack.peek().declareName(mangleName(x), x.getName());
}
names.put(x, jsName);
if (program.getIndexedFields().contains(x)) {
indexedFields.put(JjsUtils.getIndexedName(x), jsName);
}
recordSymbol(x, jsName);
}
@Override
public void endVisit(JInterfaceType x, Context ctx) {
scopeStack.pop();
}
@Override
public void endVisit(JLabel x, Context ctx) {
if (names.get(x) != null) {
return;
}
names.put(x, scopeStack.peek().declareName(x.getName()));
}
@Override
public void endVisit(JLocal x, Context ctx) {
// locals can conflict, that's okay just reuse the same variable
JsScope scope = scopeStack.peek();
JsName jsName = scope.declareName(x.getName());
names.put(x, jsName);
}
@Override
public void endVisit(JMethod x, Context ctx) {
if (doesNotHaveConcreteImplementation(x)) {
return;
}
scopeStack.pop();
}
@Override
public void endVisit(JParameter x, Context ctx) {
names.put(x, scopeStack.peek().declareName(x.getName()));
}
@Override
public void endVisit(JProgram x, Context ctx) {
/*
* put the null method and field into objectScope since they can be
* referenced as instance on null-types (as determined by type flow)
*/
JMethod nullMethod = x.getNullMethod();
polymorphicNames.put(nullMethod, objectScope.declareName("$_nullMethod"));
JField nullField = x.getNullField();
JsName nullFieldName = objectScope.declareName("$_nullField");
names.put(nullField, nullFieldName);
/*
* Create names for instantiable array types since JProgram.traverse()
* doesn't iterate over them.
*/
for (JArrayType arrayType : program.getAllArrayTypes()) {
if (program.typeOracle.isInstantiatedType(arrayType)) {
accept(arrayType);
}
}
}
@Override
public boolean visit(JClassType x, Context ctx) {
// have I already been visited as a super type?
JsScope myScope = classScopes.get(x);
if (myScope != null) {
scopeStack.push(myScope);
return false;
}
// My seed function name
JsName jsName = topScope.declareName(JjsUtils.mangledNameString(x), x.getShortName());
names.put(x, jsName);
recordSymbol(x, jsName);
// My class scope
if (x.getSuperClass() == null) {
myScope = objectScope;
} else {
JsScope parentScope = classScopes.get(x.getSuperClass());
// Run my superclass first!
if (parentScope == null) {
accept(x.getSuperClass());
}
parentScope = classScopes.get(x.getSuperClass());
assert (parentScope != null);
/*
* WEIRD: we wedge the global interface scope in between object and all
* of its subclasses; this ensures that interface method names trump all
* (except Object method names)
*/
if (parentScope == objectScope) {
parentScope = interfaceScope;
}
myScope = new JsNormalScope(parentScope, "class " + x.getShortName());
}
classScopes.put(x, myScope);
scopeStack.push(myScope);
return true;
}
@Override
public boolean visit(JInterfaceType x, Context ctx) {
// interfaces have no name at run time
scopeStack.push(interfaceScope);
return true;
}
@Override
public boolean visit(JMethod x, Context ctx) {
// my polymorphic name
String name = x.getName();
if (x.needsDynamicDispatch()) {
if (polymorphicNames.get(x) == null) {
JsName polyName;
if (x.isPrivate()) {
polyName = interfaceScope.declareName(mangleNameForPrivatePoly(x), name);
} else if (x.isPackagePrivate()) {
polyName = interfaceScope.declareName(mangleNameForPackagePrivatePoly(x), name);
} else {
boolean isJsMethod = x.isOrOverridesJsMethod() && !x.isJsPropertyAccessor();
polyName =
isJsMethod
? interfaceScope.declareUnobfuscatableName(x.getJsName())
: interfaceScope.declareName(mangleNameForPoly(x), name);
}
polymorphicNames.put(x, polyName);
}
}
if (doesNotHaveConcreteImplementation(x)) {
return false;
}
// my global name
JsName globalName = null;
assert x.getEnclosingType() != null;
String mangleName = mangleNameForGlobal(x);
if (JProgram.isClinit(x)) {
name = name + "_" + x.getEnclosingType().getShortName();
}
/*
* Only allocate a name for a function if it is native, not polymorphic,
* is a JNameOf target or stack-stripping is disabled.
*/
if (!stripStack || !polymorphicNames.containsKey(x) || x.isNative()
|| nameOfTargets.contains(x)) {
globalName = topScope.declareName(mangleName, name);
names.put(x, globalName);
recordSymbol(x, globalName);
}
JsFunction function;
if (x.isNative()) {
// set the global name of the JSNI peer
JsniMethodBody body = (JsniMethodBody) x.getBody();
function = body.getFunc();
function.setName(globalName);
} else {
/*
* It would be more correct here to check for an inline assignment, such
* as var foo = function blah() {} and introduce a separate scope for
* the function's name according to EcmaScript-262, but this would mess
* up stack traces by allowing two inner scope function names to
* obfuscate to the same identifier, making function names no longer a
* 1:1 mapping to obfuscated symbols. Leaving them in global scope
* causes no harm.
*/
function = new JsFunction(x.getSourceInfo(), topScope, globalName, !x.isJsNative());
}
jsFunctionsByJavaMethodBody.put(x.getBody(), function);
scopeStack.push(function.getScope());
if (program.getIndexedMethods().contains(x)) {
indexedFunctions.put(JjsUtils.getIndexedName(x), function);
}
// Don't traverse the method body of methods in referenceOnly types since those method bodies
// only exist in JS output of other modules it is their responsibility to handle their naming.
return !program.isReferenceOnly(x.getEnclosingType());
}
@Override
public boolean visit(JTryStatement x, Context ctx) {
accept(x.getTryBlock());
for (JTryStatement.CatchClause clause : x.getCatchClauses()) {
JLocalRef arg = clause.getArg();
JBlock catchBlock = clause.getBlock();
JsCatch jsCatch =
new JsCatch(x.getSourceInfo(), scopeStack.peek(), arg.getTarget().getName());
JsParameter jsParam = jsCatch.getParameter();
names.put(arg.getTarget(), jsParam.getName());
catchMap.put(catchBlock, jsCatch);
catchParamIdentifiers.add(jsParam.getName());
scopeStack.push(jsCatch.getScope());
accept(catchBlock);
scopeStack.pop();
}
// TODO: normalize this so it's never null?
if (x.getFinallyBlock() != null) {
accept(x.getFinallyBlock());
}
return false;
}
/**
* Generate a file name URI string for a source info, for symbol data
* export.
*/
private String makeUriString(HasSourceInfo x) {
String fileName = x.getSourceInfo().getFileName();
if (fileName == null) {
return null;
}
String uriString = fileNameToUriString.get(fileName);
if (uriString == null) {
uriString = StandardSymbolData.toUriString(fileName);
fileNameToUriString.put(fileName, uriString);
}
return uriString;
}
private void recordSymbol(JReferenceType type, JsName jsName) {
if (getRuntimeTypeReference(type) == null || !program.typeOracle.isInstantiatedType(type)) {
return;
}
String typeId = getRuntimeTypeReference(type).toSource();
StandardSymbolData symbolData =
StandardSymbolData.forClass(type.getName(), type.getSourceInfo().getFileName(),
type.getSourceInfo().getStartLine(), typeId);
assert !symbolTable.containsKey(symbolData);
symbolTable.put(symbolData, jsName);
}
private <T extends HasEnclosingType & HasName & HasSourceInfo> void recordSymbol(T member,
JsName jsName) {
/*
* NB: The use of member.getName() can produce confusion in cases where a type
* has both polymorphic and static dispatch for a method, because you
* might see HashSet::$add() and HashSet::add(). Logically, these methods
* should be treated equally, however they will be implemented with
* separate global functions and must be recorded independently.
*
* Automated systems that process the symbol information can easily map
* the statically-dispatched function by looking for method names that
* begin with a dollar-sign and whose first parameter is the enclosing
* type.
*/
String methodSignature = null;
if (member instanceof JMethod) {
JMethod method = ((JMethod) member);
methodSignature =
StringInterner.get().intern(method.getSignature().substring(method.getName().length()));
}
StandardSymbolData symbolData =
StandardSymbolData.forMember(member.getEnclosingType().getName(), member.getName(),
methodSignature, makeUriString(member), member.getSourceInfo().getStartLine());
assert !symbolTable.containsKey(symbolData) : "Duplicate symbol recorded " + jsName.getIdent()
+ " for " + member.getName() + " and key " + symbolData.getJsniIdent();
symbolTable.put(symbolData, jsName);
}
}
private class GenerateJavaScriptTransformer extends JTransformer<JsNode> {
public static final String GOOG_INHERITS = "goog.inherits";
public static final String GOOG_ABSTRACT_METHOD = "goog.abstractMethod";
public static final String GOOG_OBJECT_CREATE_SET = "goog.object.createSet";
private final Set<JDeclaredType> alreadyRan = Sets.newLinkedHashSet();
private final Map<String, Object> exportedMembersByExportName = new TreeMap<String, Object>();
private final Map<JDeclaredType, JsFunction> clinitFunctionForType = Maps.newHashMap();
private JMethod currentMethod = null;
private final JsName arrayLength = objectScope.declareUnobfuscatableName("length");
private final JsName globalTemp = topScope.declareUnobfuscatableName("_");
private final JsName prototype = objectScope.declareUnobfuscatableName("prototype");
private final JsName call = objectScope.declareUnobfuscatableName("call");
@Override
public JsExpression transformArrayLength(JArrayLength expression) {
assert expression.getInstance() != null : "Can't access the length of a null array";
return arrayLength.makeQualifiedRef(expression.getSourceInfo(),
transform(expression.getInstance()));
}
@Override
public JsExpression transformArrayRef(JArrayRef arrayRef) {
JsArrayAccess jsArrayAccess = new JsArrayAccess(arrayRef.getSourceInfo());
jsArrayAccess.setIndexExpr(transform(arrayRef.getIndexExpr()));
jsArrayAccess.setArrayExpr(transform(arrayRef.getInstance()));
return jsArrayAccess;
}
@Override
public JsExpression transformBinaryOperation(JBinaryOperation binaryOperation) {
JsExpression lhs = transform(binaryOperation.getLhs());
JsExpression rhs = transform(binaryOperation.getRhs());
JsBinaryOperator op = JavaToJsOperatorMap.get(binaryOperation.getOp());
/*
* Use === and !== on reference types, or else you can get wrong answers
* when Object.toString() == 'some string'.
*/
if (binaryOperation.getLhs().getType() instanceof JReferenceType
&& binaryOperation.getRhs().getType() instanceof JReferenceType) {
switch (op) {
case EQ:
op = JsBinaryOperator.REF_EQ;
break;
case NEQ:
op = JsBinaryOperator.REF_NEQ;
break;
}
}
return new JsBinaryOperation(binaryOperation.getSourceInfo(), op, lhs, rhs);
}
@Override
public JsStatement transformBlock(JBlock block) {
JsBlock jsBlock = new JsBlock(block.getSourceInfo());
List<JsStatement> stmts = jsBlock.getStatements();
transformIntoExcludingNulls(block.getStatements(), stmts);
Iterables.removeIf(stmts, Predicates.instanceOf(JsEmpty.class));
return jsBlock;
}
@Override
public JsNode transformBreakStatement(JBreakStatement breakStatement) {
SourceInfo info = breakStatement.getSourceInfo();
return new JsBreak(info, transformIntoLabelReference(info, breakStatement.getLabel()));
}
@Override
public JsNode transformCaseStatement(JCaseStatement caseStatement) {
if (caseStatement.getExpr() == null) {
return new JsDefault(caseStatement.getSourceInfo());
} else {
JsCase jsCase = new JsCase(caseStatement.getSourceInfo());
jsCase.setCaseExpr(transform(caseStatement.getExpr()));
return jsCase;
}
}
@Override
public JsNode transformCastOperation(JCastOperation castOperation) {
// These are left in when cast checking is disabled.
return transform(castOperation.getExpr());
}
@Override
public JsNode transformClassLiteral(JClassLiteral classLiteral) {
JsName classLit = names.get(classLiteral.getField());
return classLit.makeRef(classLiteral.getSourceInfo());
}
@Override
public JsNode transformDeclaredType(JDeclaredType type) {
// Don't generate JS for types not in current module if separate compilation is on.
if (program.isReferenceOnly(type)) {
return null;
}
if (alreadyRan.contains(type)) {
return null;
}
alreadyRan.add(type);
if (type.isJsNative()) {
// Don't generate JS for native JsType.
return null;
}
checkForDuplicateMethods(type);
assert program.getTypeClassLiteralHolder() != type;
assert !program.immortalCodeGenTypes.contains(type);
// Super classes should be emitted before the actual class.
assert type.getSuperClass() == null || program.isReferenceOnly(type.getSuperClass()) ||
alreadyRan.contains(type.getSuperClass());
emitStaticMethods(type);
generateTypeSetup(type);
emitFields(type);
collectExports(type);
return null;
}
@Override
public JsNode transformConditional(JConditional conditional) {
JsExpression ifTest = transform(conditional.getIfTest());
JsExpression thenExpr = transform(conditional.getThenExpr());
JsExpression elseExpr = transform(conditional.getElseExpr());
return new JsConditional(conditional.getSourceInfo(), ifTest, thenExpr, elseExpr);
}
@Override
public JsNode transformContinueStatement(JContinueStatement continueStatement) {
SourceInfo info = continueStatement.getSourceInfo();
return new JsContinue(info, transformIntoLabelReference(info, continueStatement.getLabel()));
}
@Override
public JsNode transformDebuggerStatement(JDebuggerStatement debuggerStatement) {
return new JsDebugger(debuggerStatement.getSourceInfo());
}
@Override
public JsNode transformDeclarationStatement(JDeclarationStatement declarationStatement) {
if (declarationStatement.getInitializer() == null) {
return null;
}
JVariable target = declarationStatement.getVariableRef().getTarget();
if (target instanceof JField && initializeAtTopScope((JField) target)) {
// Will initialize at top scope; no need to double-initialize.
return null;
}
JsExpression initializer = transform(declarationStatement.getInitializer());
JsNameRef localRef = transform(declarationStatement.getVariableRef());
SourceInfo info = declarationStatement.getSourceInfo();
return JsUtils.createAssignment(info, localRef, initializer).makeStmt();
}
@Override
public JsNode transformDoStatement(JDoStatement doStatement) {
JsDoWhile stmt = new JsDoWhile(doStatement.getSourceInfo());
stmt.setCondition(transform(doStatement.getTestExpr()));
stmt.setBody(jsEmptyIfNull(doStatement.getSourceInfo(), transform(doStatement.getBody())));
return stmt;
}
@Override
public JsNode transformExpressionStatement(JExpressionStatement statement) {
return ((JsExpression) transform(statement.getExpr())).makeStmt();
}
@Override
public JsNode transformFieldRef(JFieldRef fieldRef) {
JsExpression qualifier = transform(fieldRef.getInstance());
boolean isStatic = fieldRef.getField().isStatic();
return isStatic ? dispatchToStaticField(fieldRef, qualifier)
: dispatchToInstanceField(fieldRef, qualifier);
}
private JsExpression dispatchToStaticField(
JFieldRef fieldRef, JsExpression unnecessaryQualifier) {
/*
* Note: the comma expressions here would cause an illegal tree state if
* the result expression ended up on the lhs of an assignment.
* {@link JsNormalizer} will fix this situation.
*/
JsExpression result = createStaticReference(fieldRef.getField(), fieldRef.getSourceInfo());
return JsUtils.createCommaExpression(
unnecessaryQualifier, maybeCreateClinitCall(fieldRef.getField()), result);
}
private JsExpression dispatchToInstanceField(JFieldRef x, JsExpression instance) {
return names.get(x.getField()).makeQualifiedRef(x.getSourceInfo(), instance);
}
@Override
public JsNode transformForStatement(JForStatement forStatement) {
JsFor result = new JsFor(forStatement.getSourceInfo());
JsExpression initExpr = null;
List<JsExprStmt> initStmts = transform(forStatement.getInitializers());
for (int i = 0; i < initStmts.size(); ++i) {
JsExprStmt initStmt = initStmts.get(i);
if (initStmt != null) {
initExpr = JsUtils.createCommaExpression(initExpr, initStmt.getExpression());
}
}
result.setInitExpr(initExpr);
result.setCondition(transform(forStatement.getCondition()));
result.setIncrExpr(transform(forStatement.getIncrements()));
result.setBody(jsEmptyIfNull(forStatement.getSourceInfo(), transform(forStatement.getBody())));
return result;
}
@Override
public JsNode transformIfStatement(JIfStatement ifStatement) {
JsIf result = new JsIf(ifStatement.getSourceInfo());
result.setIfExpr(transform(ifStatement.getIfExpr()));
result.setThenStmt(jsEmptyIfNull(ifStatement.getSourceInfo(),
transform(ifStatement.getThenStmt())));
result.setElseStmt(transform(ifStatement.getElseStmt()));
return result;
}
@Override
public JsLabel transformLabel(JLabel label) {
return new JsLabel(label.getSourceInfo(), names.get(label));
}
@Override
public JsStatement transformLabeledStatement(JLabeledStatement labeledStatement) {
JsLabel label = transform(labeledStatement.getLabel());
label.setStmt(transform(labeledStatement.getBody()));
return label;
}
@Override
public JsLiteral transformLiteral(JLiteral literal) {
return JjsUtils.translateLiteral(literal);
}
@Override
public JsNode transformLocalRef(JLocalRef localRef) {
return names.get(localRef.getTarget()).makeRef(localRef.getSourceInfo());
}
@Override
public JsNode transformMethod(JMethod method) {
if (method.isAbstract()) {
return generateAbstractMethodDefinition(method);
} else if (doesNotHaveConcreteImplementation(method)) {
return null;
}
currentMethod = method;
JsFunction function = transform(method.getBody());
function.setInliningMode(method.getInliningMode());
if (!method.isNative()) {
// Setup params on the generated function. A native method already got
// its jsParams set when parsed from JSNI.
transformInto(method.getParams(), function.getParameters());
}
JsInvocation jsInvocation = maybeCreateClinitCall(method);
if (jsInvocation != null) {
function.getBody().getStatements().add(0, jsInvocation.makeStmt());
}
if (JProgram.isClinit(method)) {
function.markAsClinit();
}
currentMethod = null;
return function;
}
@Override
public JsNode transformMethodBody(JMethodBody methodBody) {
JsBlock body = transform(methodBody.getBlock());
JsFunction function = jsFunctionsByJavaMethodBody.get(methodBody);
function.setBody(body);
/*
* Emit a statement to declare the method's complete set of local
* variables. JavaScript doesn't have the same concept of lexical scoping
* as Java, so it's okay to just predeclare all local vars at the top of
* the function, which saves us having to use the "var" keyword over and
* over.
*
* Note: it's fine to use the same JS ident to represent two different
* Java locals of the same name since they could never conflict with each
* other in Java. We use the alreadySeen set to make sure we don't declare
* the same-named local var twice.
*/
JsVars vars = new JsVars(methodBody.getSourceInfo());
Set<String> alreadySeen = Sets.newHashSet();
for (JLocal local : methodBody.getLocals()) {
JsName name = names.get(local);
String ident = name.getIdent();
if (!alreadySeen.contains(ident)
// Catch block params don't need var declarations
&& !catchParamIdentifiers.contains(name)) {
alreadySeen.add(ident);
vars.add(new JsVar(methodBody.getSourceInfo(), name));
}
}
if (!vars.isEmpty()) {
function.getBody().getStatements().add(0, vars);
}
return function;
}
@Override
public JsNode transformMethodCall(JMethodCall methodCall) {
JMethod method = methodCall.getTarget();
if (JProgram.isClinit(method)) {
/*
* It is possible for clinits to be referenced here that have actually
* been retargeted (see {@link
* JTypeOracle.recomputeAfterOptimizations}). Most of the time, these
* will get cleaned up by other optimization passes prior to this point,
* but it's not guaranteed. In this case we need to replace the method
* call with the replaced clinit, unless the replacement is null, in
* which case we generate a JsNullLiteral as a place-holder expression.
*/
JDeclaredType type = method.getEnclosingType();
JDeclaredType clinitTarget = type.getClinitTarget();
if (clinitTarget == null) {
// generate a null expression, which will get optimized out
return JsNullLiteral.INSTANCE;
}
method = clinitTarget.getClinitMethod();
}
JsExpression qualifier = transform(methodCall.getInstance());
List<JsExpression> args = transform(methodCall.getArgs());
if (method.isStatic()) {
return dispatchToStatic(qualifier, method, args, methodCall.getSourceInfo());
} else if (methodCall.isStaticDispatchOnly()) {
return dispatchToSuper(qualifier, method, args, methodCall.getSourceInfo());
} else if (method.isOrOverridesJsFunctionMethod()) {
return dispatchToJsFunction(qualifier, args, methodCall.getSourceInfo());
} else {
return dispatchToInstanceMethod(qualifier, method, args, methodCall.getSourceInfo());
}
}
private JsExpression dispatchToStatic(JsExpression unnecessaryQualifier, JMethod method,
List<JsExpression> args, SourceInfo sourceInfo) {
JsNameRef methodName = createStaticReference(method, sourceInfo);
JsExpression result = new JsInvocation(sourceInfo, methodName, args);
return JsUtils.createCommaExpression(unnecessaryQualifier, result);
}
private JsExpression dispatchToSuper(
JsExpression instance, JMethod method, List<JsExpression> args, SourceInfo sourceInfo) {
JsNameRef methodNameRef;
if (method.isConstructor()) {
// We don't generate calls to super native constructors (yet).
if (method.isJsNative()) {
return JsNullLiteral.INSTANCE;
}
/*
* Constructor calls through {@code this} and {@code super} are always dispatched statically
* using the constructor function name (constructors are always defined as top level
* functions).
*
* Because constructors are modeled like instance methods they have an implicit {@code this}
* parameter, hence they are invoked like: "constructor.call(this, ...)".
*/
methodNameRef = names.get(method).makeRef(sourceInfo);
} else {
// These are regular super method call. These calls are always dispatched statically and
// optimizations will statify them (except in a few cases, like being target of
// {@link Impl.getNameOf} or calls to the native classes.
JDeclaredType superClass = method.getEnclosingType();
if (method.isJsNative()) {
// Construct jsPrototype.prototype.jsname
methodNameRef = createJsQualifier(method.getQualifiedJsName(), sourceInfo);
} else {
JsExpression protoRef = getPrototypeQualifierViaLookup(superClass, sourceInfo);
methodNameRef = polymorphicNames.get(method).makeQualifiedRef(sourceInfo, protoRef);
}
}
// <method_qualifier>.call(instance, args);
JsNameRef qualifiedMethodName = call.makeQualifiedRef(sourceInfo, methodNameRef);
JsInvocation jsInvocation = new JsInvocation(sourceInfo, qualifiedMethodName);
jsInvocation.getArguments().add(instance);
jsInvocation.getArguments().addAll(args);
return jsInvocation;
}
private JsExpression getPrototypeQualifierViaLookup(JDeclaredType type, SourceInfo sourceInfo) {
if (closureCompilerFormatEnabled) {
return getPrototypeQualifierOf(type, type.getSourceInfo());
} else {
// Construct JCHSU.getPrototypeFor(type).polyname
// TODO(rluble): Ideally we would want to construct the inheritance chain the JS way and
// then we could do Type.prototype.polyname.call(this, ...). Currently prototypes do not
// have global names instead they are stuck into the prototypesByTypeId array.
return constructInvocation(sourceInfo, "JavaClassHierarchySetupUtil.getClassPrototype",
(JsExpression) transform(getRuntimeTypeReference(type)));
}
}
private JsExpression dispatchToJsFunction(
JsExpression instance, List<JsExpression> args, SourceInfo sourceInfo) {
return new JsInvocation(sourceInfo, instance, args);
}
private JsExpression dispatchToInstanceMethod(
JsExpression instance, JMethod method, List<JsExpression> args, SourceInfo sourceInfo) {
JsNameRef reference =
method.isJsPropertyAccessor()
? new JsNameRef(sourceInfo, method.getJsName())
: polymorphicNames.get(method).makeRef(sourceInfo);
reference.setQualifier(instance);
switch (method.getJsPropertyAccessorType()) {
case SETTER:
return createAssignment(reference, args.get(0));
case GETTER:
return reference;
default:
return new JsInvocation(sourceInfo, reference, args);
}
}
@Override
public JsNode transformMultiExpression(JMultiExpression multiExpression) {
if (multiExpression.isEmpty()) {
// the multi-expression was empty; use undefined
return JsRootScope.INSTANCE.getUndefined().makeRef(multiExpression.getSourceInfo());
}
List<JsExpression> exprs = transform(multiExpression.getExpressions());
JsExpression cur = null;
for (int i = 0; i < exprs.size(); ++i) {
JsExpression next = exprs.get(i);
cur = JsUtils.createCommaExpression(cur, next);
}
return cur;
}
@Override
public JsNode transformNameOf(JNameOf nameof) {
JsName name = names.get(nameof.getNode());
if (name == null) {
return JsRootScope.INSTANCE.getUndefined().makeRef(nameof.getSourceInfo());
}
return new JsNameOf(nameof.getSourceInfo(), name);
}