forked from cromwellian/gwt-sandbox
/
UnifyAst.java
1974 lines (1751 loc) · 74.5 KB
/
UnifyAst.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2011 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 java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import com.google.gwt.core.ext.PropertyOracle;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.linker.ArtifactSet;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.dev.CompilerContext;
import com.google.gwt.dev.MinimalRebuildCache;
import com.google.gwt.dev.cfg.ConfigurationProperty;
import com.google.gwt.dev.cfg.Properties;
import com.google.gwt.dev.cfg.Property;
import com.google.gwt.dev.javac.CompilationProblemReporter;
import com.google.gwt.dev.javac.CompilationState;
import com.google.gwt.dev.javac.CompilationUnit;
import com.google.gwt.dev.javac.CompiledClass;
import com.google.gwt.dev.javac.GeneratedUnit;
import com.google.gwt.dev.javac.StandardGeneratorContext;
import com.google.gwt.dev.jdt.RebindPermutationOracle;
import com.google.gwt.dev.jjs.InternalCompilerException;
import com.google.gwt.dev.jjs.MagicMethodGenerator;
import com.google.gwt.dev.jjs.PrecompilationContext;
import com.google.gwt.dev.jjs.SourceInfo;
import com.google.gwt.dev.jjs.SourceOrigin;
import com.google.gwt.dev.jjs.UnifyAstListener;
import com.google.gwt.dev.jjs.UnifyAstView;
import com.google.gwt.dev.jjs.ast.*;
import com.google.gwt.dev.jjs.ast.JMethod.Specialization;
import com.google.gwt.dev.jjs.ast.js.JDebuggerStatement;
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.js.ast.JsNestingScope;
import com.google.gwt.dev.js.ast.JsProgram;
import com.google.gwt.dev.js.ast.JsRootScope;
import com.google.gwt.dev.util.JsniRef;
import com.google.gwt.dev.util.Name.BinaryName;
import com.google.gwt.dev.util.Name.InternalName;
import com.google.gwt.dev.util.StringInterner;
import com.google.gwt.dev.util.log.MetricName;
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.reflect.rebind.ReflectionUtilAst;
import com.google.gwt.thirdparty.guava.common.base.Predicates;
import com.google.gwt.thirdparty.guava.common.collect.ImmutableMap;
import com.google.gwt.thirdparty.guava.common.collect.Iterables;
import com.google.gwt.thirdparty.guava.common.collect.LinkedListMultimap;
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.Multimap;
import com.google.gwt.thirdparty.guava.common.collect.Sets;
import com.google.gwt.thirdparty.guava.common.collect.Sets.SetView;
/**
* Take independently-compiled types and merge them into a single AST.
*
* Works kind of like {@link ControlFlowAnalyzer} in terms of reachability,
* except that in some cases it's easier to be conservative and visit relatively
* more nodes than CFA would.
*
* Operates based on a work-queue to prevent recursion sickness.
*
* Must handle:
*
* - Type reference resolution
*
* - Field and method reference resolution
*
* - General code flow like ControlFlowAnalyzer
*
* - GWT.create(), GWT.runAsync(), Impl.getNameOf()
*
* - Stitch native methods into JsProgram
*
* - Class.desiredAssertionStatus, Class.isClassMetaDataEnabled, GWT.isClient,
* GWT.isProdMode, GWT.isScript.
*/
// TODO: SOYC correlations.
// TODO(stalcup): perform only binary name based lookups so that libraries
// don't need to index compilation units by both source and binary name
// TODO(stalcup): shrink the translate/flowInto graph for reference only types to eliminate
// unnecessary loading of types and increase performance.
public class UnifyAst implements UnifyAstView {
/**
* Embodies the access methods for the compiled class, compilation unit and type for a flavor of
* type name.
*/
private abstract class NameBasedTypeLocator {
private final Map<String, CompiledClass> compiledClassesByTypeName;
private NameBasedTypeLocator(Map<String, CompiledClass> compiledClassesByTypeName) {
this.compiledClassesByTypeName = compiledClassesByTypeName;
}
protected abstract boolean hasCompileErrors(String typeName);
protected abstract void logErrorTrace(TreeLogger branch, Type logLevel, String sourceName);
protected CompilationUnit getCompilationUnitFromSource(String typeName) {
return compiledClassesByTypeName.get(typeName).getUnit();
}
protected JDeclaredType getResolvedType(String typeName) {
JDeclaredType resolvedType = program.getFromTypeMap(typeName);
return resolvedType;
}
protected boolean resolvedTypeIsAvailable(String typeName) {
return program.getFromTypeMap(typeName) != null;
}
protected boolean sourceCompilationUnitIsAvailable(String typeName) {
return compiledClassesByTypeName.containsKey(typeName);
}
}
public class UnifyVisitor extends JModVisitor {
private JMethod currentMethod;
@Override
public void endVisit(JArrayType x, Context ctx) {
assert false : "Should not get here";
}
@Override
public void endVisit(JBinaryOperation x, Context ctx) {
// Concat ops need to resolve string type.
x.setType(translate(x.getType().getUnderlyingType()));
}
@Override
public void endVisit(JCastOperation x, Context ctx) {
x.resolve(translate(x.getCastType()));
}
@Override
public void endVisit(JClassLiteral x, Context ctx) {
JType refType = translate(x.getRefType());
x.resolve(refType);
// ImplementClassLiteralsAsFields: rescue enumType.values()/valueOf().
if (refType instanceof JArrayType) {
refType = ((JArrayType) refType).getLeafType();
}
JEnumType enumType = refType.isEnumOrSubclass();
if (enumType == null) {
return;
}
for (JMethod method : enumType.getMethods()) {
if (!method.isStatic()) {
continue;
}
if (method.getSignature().startsWith("values()") ||
method.getSignature().startsWith("valueOf(Ljava/lang/String;)")) {
flowInto(method);
}
}
}
@Override
public void endVisit(JClassType x, Context ctx) {
assert false : "Should not get here";
}
@Override
public void endVisit(JConditional x, Context ctx) {
x.setType(translate(x.getType()));
}
@Override
public void endVisit(JConstructor x, Context ctx) {
// Process as method.
super.endVisit(x, ctx);
instantiate(x.getEnclosingType());
}
@Override
public void endVisit(JDeclaredType x, Context ctx) {
assert false : "Should not get here";
}
@Override
public void endVisit(JExpression x, Context ctx) {
assert !x.getType().isExternal() || errorsFound;
}
@Override
public void endVisit(JField x, Context ctx) {
assert false : "Should not get here";
}
@Override
public void endVisit(JFieldRef x, Context ctx) {
JField field = translate(x.getSourceInfo(), x.getField());
flowInto(field);
x.resolve(field);
// Should not have an overridden type at this point.
assert x.getType() == x.getField().getType();
assert !x.getEnclosingType().isExternal();
}
@Override
public void endVisit(JInstanceOf x, Context ctx) {
x.resolve(translate(x.getTestType()));
}
@Override
public void endVisit(JInterfaceType x, Context ctx) {
assert false : "Should not get here";
}
@Override
public void endVisit(JMethod x, Context ctx) {
currentMethod = null;
}
@Override
public void endVisit(JMethodCall x, Context ctx) {
// Already resolved during visit().
JMethod target = x.getTarget();
if (target.isExternal()) {
assert errorsFound;
return;
}
String targetSignature = target.getQualifiedName();
if (magicMethodMap.containsKey(targetSignature)) {
if (GWT_DEBUGGER_METHOD_CALLS.contains(targetSignature)) {
return; // handled in endVisit for JExpressionStatement
}
JExpression result = handleMagicMethodCall(x, ctx);
if (result == null) {
// Error of some sort.
result = JNullLiteral.INSTANCE;
}
result = this.accept(result);
ctx.replaceMe(result);
return;
}
// Should not have an overridden type at this point.
assert x instanceof JNewInstance || x.getType() == target.getType();
flowInto(target);
}
@Override
public void endVisit(JNameOf x, Context ctx) {
HasName node = x.getNode();
if (node instanceof JType) {
node = translate((JType) node);
} else if (node instanceof JMember) {
node = translate(x.getSourceInfo(), (JMember) node);
} else {
assert false : "Should not get here";
}
x.resolve(node, (JClassType) translate(x.getType().getUnderlyingType()));
}
@Override
public void endVisit(JNewArray x, Context ctx) {
x.setType((JArrayType) translate(x.getArrayType()));
}
@Override
public void endVisit(JNewInstance x, Context ctx) {
JConstructor target = x.getTarget();
if (target.isExternal()) {
assert errorsFound;
return;
}
flowInto(target);
}
@Override
public void endVisit(JsniFieldRef x, Context ctx) {
endVisit((JFieldRef) x, ctx);
}
@Override
public void endVisit(JsniMethodBody x, Context ctx) {
JsNestingScope funcScope = (JsNestingScope) x.getFunc().getScope();
assert funcScope.getParent() == JsRootScope.INSTANCE;
funcScope.nestInto(jsProgram.getScope());
}
@Override
public void endVisit(JsniMethodRef x, Context ctx) {
JMethod target = translate(x.getSourceInfo(), x.getTarget());
x.resolve(target, program.getJavaScriptObject());
flowInto(target);
}
@Override
public void endVisit(JsonArray x, Context ctx) {
x.resolve(translate(x.getType()));
}
@Override
public void endVisit(JStringLiteral x, Context ctx) {
JClassType stringType = program.getTypeJavaLangString();
x.resolve(stringType);
instantiate(stringType);
}
@Override
public void endVisit(JThisRef x, Context ctx) {
assert !x.getType().isExternal();
}
@Override
public void endVisit(JTryStatement x, Context ctx) {
// Needs to resolve the Exceptions Types explicitly they are multiple in Java 7 and
// potentially different from the one in the exception variable.
for (JTryStatement.CatchClause clause : x.getCatchClauses()) {
List<JType> types = clause.getTypes();
for (int i = 0; i < types.size(); i++) {
JReferenceType resolvedType = translate((JReferenceType) types.get(i));
assert resolvedType.replaces(types.get(i));
types.set(i, resolvedType);
}
}
}
@Override
public void endVisit(JUnsafeTypeCoercion x, Context ctx) {
x.resolve(translate(x.getCoercionType()));
}
@Override
public void endVisit(JVariable x, Context ctx) {
x.setType(translate(x.getType()));
}
@Override
public boolean visit(JExpressionStatement x, Context ctx) {
if (x.getExpr() instanceof JMethodCall) {
JMethodCall call = (JMethodCall) x.getExpr();
JMethod target = call.getTarget();
if (GWT_DEBUGGER_METHOD_CALLS.contains(target.getQualifiedName())) {
// We should see all calls here because GWT.debugger() returns void.
ctx.replaceMe(new JDebuggerStatement(x.getSourceInfo()));
}
}
return true;
}
@Override
public boolean visit(JMethod x, Context ctx) {
currentMethod = x;
// Only visit contents of methods defined in types which are part of this compile. Visit
// also clinits that are reachable to make sure all the nodes that are needed for
// propagating compile time constants are available.
return !program.isReferenceOnly(x.getEnclosingType()) ||
x == x.getEnclosingType().getClinitMethod();
}
@Override
public boolean visit(final JMethodBody x, final Context ctx) {
final JMethod target = translate(x.getMethod());
// Special handling.
if (target.isDoNotVisit()) {
// Replace the body of the method with an empty block
JMethodBody newBody = new JMethodBody(x.getSourceInfo());
logger.log(Type.WARN, "Replacing magic method " + target.getSignature() + " body with a return null; " +
target.getOriginalReturnType()+" <--> " + target.getType() + " : " + x);
if (target.getOriginalReturnType().isPrimitiveType()) {
newBody.getBlock().addStmt(new JReturnStatement(x.getSourceInfo(), target.getOriginalReturnType().getDefaultValue()));
} else {
newBody.getBlock().addStmt(new JReturnStatement(x.getSourceInfo(), JNullLiteral.INSTANCE));
}
ctx.replaceMe(newBody);
return false;
}
return true;
}
@Override
public boolean visit(JMethodCall x, Context ctx) {
JMethod target = translate(x.getSourceInfo(), x.getTarget());
x.resolve(target);
// Special handling for magic method calls.
JExpression replacement = maybeHandleMagicMethodCall(x);
if (replacement != null) {
ctx.replaceMe(accept(replacement));
return false;
}
return true;
}
private JExpression maybeHandleMagicMethodCall(JMethodCall methodCall) {
JExpression result;
switch (methodCall.getTarget().getQualifiedName()) {
case GWT_CREATE:
case OLD_GWT_CREATE:
result = createRebindExpression(methodCall);
break;
case IMPL_GET_NAME_OF:
result = handleImplNameOf(methodCall);
break;
case SYSTEM_GET_PROPERTY:
case SYSTEM_GET_PROPERTY_WITH_DEFAULT:
case X_PROPERTIES_GET_PROPERTY:
case X_PROPERTIES_GET_PROPERTY_WITH_DEFAULT:
result = handleSystemGetProperty(methodCall);
break;
default:
// Not a magic method call, return null so that it does not get replaced.
return null;
}
if (result == null) {
logger.log(Type.WARN, "Magic method call returned null result " + methodCall);
// Handled magic call possibly with an error.
return JNullLiteral.INSTANCE;
}
return result;
}
private JExpression handleSystemGetProperty(JMethodCall gwtGetPropertyCall) {
assert (gwtGetPropertyCall.getArgs().size() == 1 || gwtGetPropertyCall.getArgs().size() == 2);
boolean defaultVersionCalled = gwtGetPropertyCall.getArgs().size() == 2;
JStringLiteral propertyNameExpression;
JExpression defaultValueExpression;
try {
propertyNameExpression = getStringLiteral(gwtGetPropertyCall.getArgs().get(0));
defaultValueExpression = defaultVersionCalled ?
getExpression(gwtGetPropertyCall.getArgs().get(1)) : null;
} catch (UnableToCompleteException e) {
error(gwtGetPropertyCall,
"Only string constants may be used as property names in System.getProperty()");
return null;
}
String propertyName = propertyNameExpression.getValue();
if (!defaultVersionCalled && !isPropertyDefined(propertyName)) {
error(gwtGetPropertyCall, "Property '" + propertyName + "' is not defined.");
return null;
}
if (isMultivaluedProperty(propertyName)) {
error(gwtGetPropertyCall,
"Property '" + propertyName + "' is multivalued. " +
"Multivalued properties are not supported by System.getProperty().");
return null;
}
if (defaultValueExpression != null) {
defaultValueExpression = accept(defaultValueExpression);
}
return JPermutationDependentValue.createRuntimeProperty(
program, gwtGetPropertyCall.getSourceInfo(), propertyName, defaultValueExpression);
}
private boolean isMultivaluedProperty(String propertyName) {
Property property = compilerContext.getModule().getProperties().find(propertyName);
if (!(property instanceof ConfigurationProperty)) {
return false;
}
return ((ConfigurationProperty) property).allowsMultipleValues();
}
private JStringLiteral getStringLiteral(JExpression inst) throws UnableToCompleteException {
return ReflectionUtilAst.extractImmutableNode(logger, JStringLiteral.class, inst, UnifyAst.this, true);
}
private JExpression getExpression(JExpression inst) throws UnableToCompleteException {
return ReflectionUtilAst.extractImmutableNode(logger, JExpression.class, inst, UnifyAst.this, true);
}
private JExpression createRebindExpression(JMethodCall gwtCreateCall) {
assert (gwtCreateCall.getArgs().size() == 1);
JExpression arg = gwtCreateCall.getArgs().get(0);
if (!(arg instanceof JClassLiteral)) {
error(gwtCreateCall, "Only class literals may be used as arguments to GWT.create()");
return null;
}
JClassLiteral classLiteral = (JClassLiteral) arg;
if (!(classLiteral.getRefType() instanceof JDeclaredType)) {
error(
gwtCreateCall,
"Only classes and interfaces may be used as arguments to GWT.create()"
);
return null;
}
Event event = SpeedTracerLogger.start(CompilerEventType.VISIT_GWT_CREATE,
"argument", classLiteral.getRefType().getName(),
"caller", gwtCreateCall.getSourceInfo().getFileName()
);
try {
return createStaticRebindExpression(gwtCreateCall, classLiteral);
} finally {
event.end();
}
}
private JExpression createStaticRebindExpression(
JMethodCall gwtCreateCall,
JClassLiteral classLiteral
) {
JDeclaredType type = (JDeclaredType) classLiteral.getRefType();
String reboundTypeName = type.getName();
// TODO(stalcup): below a MinimalRebuildCache pattern of "clear cache entries for a type" and
// "rebuild cache entries for that type" is followed. There is a danger that a compile error
// could occur between the two stages and leave the cache in an invalid state. Switch to a
// transactionally safe update pattern like always updating a copy and swapping out the
// original for the copy at the end of a successful compile.
if (incrementalCompile) {
// If this is the first time we've rebound this type during this compile.
if (reboundTypeNames.add(reboundTypeName)) {
// The rebinding of this type will accumulate rebound type to input resource associations,
// but the accumulation should start from scratch, so clear any existing associations that
// might have been collected in previous compiles.
minimalRebuildCache.clearReboundTypeAssociations(reboundTypeName);
}
minimalRebuildCache.recordRebinderTypeForReboundType(reboundTypeName,
currentMethod.getEnclosingType().getName());
rebindPermutationOracle
.getGeneratorContext().setCurrentRebindBinaryTypeName(reboundTypeName);
}
String requestedType = BinaryName.toSourceName(reboundTypeName);
List<String> answers;
try {
answers = Lists.newArrayList(
rebindPermutationOracle.getAllPossibleRebindAnswers(logger, requestedType));
if (incrementalCompile) {
// Accumulate generated artifacts so that they can be output on recompiles even if no
// generators are run.
ArtifactSet artifacts = rebindPermutationOracle.getGeneratorContext().getArtifacts();
minimalRebuildCache.addGeneratedArtifacts(artifacts);
}
rebindPermutationOracle.getGeneratorContext().finish(logger);
if (incrementalCompile) {
// There may be more types known to be modified after Generator execution, which would
// mean the previous stale types calculation was too small. Redo it.
staleTypeNames =
minimalRebuildCache.computeAndClearStaleTypesCache(logger, program.typeOracle);
checkPreambleTypesStillFresh(logger);
fullFlowIntoRemainingStaleTypes();
}
} catch (UnableToCompleteException e) {
error(gwtCreateCall, "Failed to resolve '" + requestedType + "' via deferred binding");
return null;
}
List<JExpression> instantiationExpressions =
Lists.newArrayListWithCapacity(answers.size());
for (String answer : answers) {
JDeclaredType answerType = internalFindType(answer, sourceNameBasedTypeLocator, true);
if (answerType == null) {
error(gwtCreateCall, "Rebind result '" + answer + "' could not be found");
return null;
}
if (!(answerType instanceof JClassType)) {
error(gwtCreateCall, "Rebind result '" + answer + "' must be a class");
return null;
}
if (answerType.isAbstract()) {
error(gwtCreateCall, "Rebind result '" + answer + "' cannot be abstract");
return null;
}
if (isJso(answerType)) {
error(gwtCreateCall, "Rebind result '" + answer + "' cannot be a JSO");
return null;
}
JExpression result = JjsUtils
.createDefaultConstructorInstantiation(
gwtCreateCall.getSourceInfo(),
(JClassType) answerType
);
if (result == null) {
error(
gwtCreateCall,
"Rebind result '" + answer + "' has no default (zero argument) constructors"
);
return null;
}
instantiationExpressions.add(result);
}
assert answers.size() == instantiationExpressions.size();
if (answers.size() == 1) {
return instantiationExpressions.get(0);
}
return JPermutationDependentValue
.createTypeRebind(program, gwtCreateCall.getSourceInfo(), requestedType,
answers, instantiationExpressions);
}
private JExpression handleImplNameOf(final JMethodCall x) {
assert (x.getArgs().size() == 1);
JExpression arg = x.getArgs().get(0);
if (!(arg instanceof JStringLiteral)) {
error(x, "Only string literals may be used as arguments to Impl.getNameOf()");
return null;
}
JStringLiteral stringLiteral = (JStringLiteral) arg;
String stringValue = stringLiteral.getValue();
JNode node = null;
JsniRef ref = JsniRef.parse(stringValue);
if (ref != null) {
node = JsniRefLookup.findJsniRefTarget(ref, program, new JsniRefLookup.ErrorReporter() {
@Override
public void reportError(String errMsg) {
error(x, errMsg);
}
});
}
if (node == null) {
// Not found, must be null
return null;
}
if (node instanceof JMethod) {
flowInto((JMethod) node);
program.addPinnedMethod((JMethod) node);
}
return new JNameOf(x.getSourceInfo(), program.getTypeJavaLangString(), (HasName) node);
}
private JExpression handleMagicMethodCall(JMethodCall x, Context ctx) {
JMethod target = x.getTarget();
String methodSignature = target.getQualifiedName();
switch (methodSignature) {
case GWT_CREATE:
case OLD_GWT_CREATE:
return createRebindExpression(x);
case IMPL_GET_NAME_OF:
return handleImplNameOf(x);
case SYSTEM_GET_PROPERTY:
case SYSTEM_GET_PROPERTY_WITH_DEFAULT:
case X_PROPERTIES_GET_PROPERTY:
case X_PROPERTIES_GET_PROPERTY_WITH_DEFAULT:
case PROPERTY_SERVICE_GET_PROPERTY:
case PROPERTY_SERVICE_GET_PROPERTY_WITH_DEFAULT:
return handleSystemGetProperty(x);
default:
if (magicMethodMap.containsKey(methodSignature)) {
MagicMethodGenerator method = magicMethodMap.get(methodSignature);
try {
PropertyOracle oldOracle = getGeneratorContext().getPropertyOracle();
getGeneratorContext().setPropertyOracle(getRebindPermutationOracle().getConfigurationPropertyOracle());
boolean oldMode = minimalRebuildCache.isInjectionMode();
minimalRebuildCache.setInjectionMode(true);
rebindPermutationOracle.getGeneratorContext().setCurrentRebindBinaryTypeName(null);
JExpression expr = method.injectMagic(logger, x, currentMethod, ctx, UnifyAst.this);
minimalRebuildCache.setInjectionMode(oldMode);
getGeneratorContext().setPropertyOracle(oldOracle);
if (logger.isLoggable(Type.DEBUG)) {
logger.log(Type.DEBUG, "Magic method " + method
+ " converted:\n" + x + "\ninto: " + expr);
}
return expr;
} catch (Exception e) {
logger.log(Type.ERROR, "Fatal error calling magic method " + method + " on " + x, e);
throw new InternalCompilerException("Unable to implement magic method " + method + "()", e);
}
}
throw new InternalCompilerException("Unknown magic method error");
}
}
}
private boolean isPropertyDefined(String propertyName) {
return compilerContext.getModule().getProperties().find(propertyName) != null;
}
private static final String CLASS_DESIRED_ASSERTION_STATUS =
"java.lang.Class.desiredAssertionStatus()Z";
private static final String CLASS_IS_CLASS_METADATA_ENABLED =
"java.lang.Class.isClassMetadataEnabled()Z";
public static final String GWT_CREATE =
"com.google.gwt.core.shared.GWT.create(Ljava/lang/Class;)Ljava/lang/Object;";
public static final String SYSTEM_GET_PROPERTY =
"java.lang.System.getProperty(Ljava/lang/String;)Ljava/lang/String;";
public static final String SYSTEM_GET_PROPERTY_WITH_DEFAULT =
"java.lang.System.getProperty(Ljava/lang/String;Ljava/lang/String;)" +
"Ljava/lang/String;";
public static final String X_PROPERTIES_GET_PROPERTY =
"xapi.util.X_Properties.getProperty(Ljava/lang/String;)Ljava/lang/String;";
public static final String X_PROPERTIES_GET_PROPERTY_WITH_DEFAULT =
"xapi.util.X_Properties.getProperty(Ljava/lang/String;Ljava/lang/String;)" +
"Ljava/lang/String;";
public static final String PROPERTY_SERVICE_GET_PROPERTY =
"xapi.util.impl.PropertyServiceDefault.getProperty(Ljava/lang/String;)Ljava/lang/String;";
public static final String PROPERTY_SERVICE_GET_PROPERTY_WITH_DEFAULT =
"xapi.util.impl.PropertyServiceDefault.getProperty(Ljava/lang/String;Ljava/lang/String;)" +
"Ljava/lang/String;";
private static final String GWT_DEBUGGER_SHARED = "com.google.gwt.core.shared.GWT.debugger()V";
private static final String GWT_DEBUGGER_CLIENT = "com.google.gwt.core.client.GWT.debugger()V";
private static final String GWT_IS_CLIENT = "com.google.gwt.core.shared.GWT.isClient()Z";
private static final String GWT_IS_PROD_MODE = "com.google.gwt.core.shared.GWT.isProdMode()Z";
private static final String GWT_IS_SCRIPT = "com.google.gwt.core.shared.GWT.isScript()Z";
private static final String IMPL_GET_NAME_OF =
"com.google.gwt.core.client.impl.Impl.getNameOf(Ljava/lang/String;)Ljava/lang/String;";
public static final String OLD_GWT_CREATE =
"com.google.gwt.core.client.GWT.create(Ljava/lang/Class;)Ljava/lang/Object;";
private static final String OLD_GWT_IS_CLIENT = "com.google.gwt.core.client.GWT.isClient()Z";
private static final String OLD_GWT_IS_PROD_MODE = "com.google.gwt.core.client.GWT.isProdMode()Z";
private static final String OLD_GWT_IS_SCRIPT = "com.google.gwt.core.client.GWT.isScript()Z";
/**
* Methods for which the call site must be replaced with magic AST nodes.
*/
private static final Set<String> GWT_DEBUGGER_METHOD_CALLS =
Sets.newLinkedHashSet(Arrays.asList(GWT_DEBUGGER_SHARED, GWT_DEBUGGER_CLIENT));
/**
* Methods for which the call site must be replaced with magic AST nodes.
*/
private static final LinkedHashSet<String> MAGIC_METHOD_CALLS = Sets.newLinkedHashSet(Arrays.asList(
GWT_CREATE, GWT_DEBUGGER_SHARED, GWT_DEBUGGER_CLIENT, SYSTEM_GET_PROPERTY,
SYSTEM_GET_PROPERTY_WITH_DEFAULT, X_PROPERTIES_GET_PROPERTY, X_PROPERTIES_GET_PROPERTY_WITH_DEFAULT,
PROPERTY_SERVICE_GET_PROPERTY, PROPERTY_SERVICE_GET_PROPERTY_WITH_DEFAULT,
OLD_GWT_CREATE, IMPL_GET_NAME_OF));
/**
* Methods with magic implementations that the compiler must insert.
*/
private final Map<String, JBooleanLiteral> replacementValueByMagicMethodQualifiedName;
private final CompilationState compilationState;
private final Map<String, CompiledClass> compiledClassesByInternalName;
private final Map<String, CompiledClass> compiledClassesBySourceName;
/**
* JVisitor interferes with any exceptions thrown inside of a visitor traversal call tree so any
* time UnifyAst wants to log an error and end operation care it should be done by manually
* logging an error line and setting errorsFound to true. Adequate checking is already in place to
* interpret this as ending further exploration and errorsFound = true is already being converted
* to an UnableToCompleteException at the UnifyAst public function boundaries
*/
private boolean errorsFound = false;
private final Set<CompilationUnit> unitsWithErrorsAlreadyReported = Sets.newIdentityHashSet();
/**
* The set of types currently known to be instantiable. Like
* {@link ControlFlowAnalyzer#instantiatedTypes}.
*/
private final Set<JDeclaredType> instantiatedTypes = Sets.newIdentityHashSet();
private final JsProgram jsProgram;
/**
* Fields and methods that are referenceable. Like
* {@link ControlFlowAnalyzer#liveFieldsAndMethods}.
*/
private final Set<JNode> liveFieldsAndMethods = Sets.newIdentityHashSet();
/**
* Types which have had all of their fields and methods resolved (as opposed to the default
* behavior of only resolving the reachable ones). Currently only used when performing per-file
* compilation/recompilation.
*/
private final Set<String> fullFlowTypes = Sets.newHashSet();
private final TreeLogger logger;
private final CompilerContext compilerContext;
private final Map<String, JMember> resolvedMembersByQualifiedName = Maps.newHashMap();
private final Map<String, MagicMethodGenerator> magicMethodMap = Maps.newHashMap();
private final JProgram program;
private final RebindPermutationOracle rebindPermutationOracle;
private final Set<String> reboundTypeNames = Sets.newHashSet();
/**
* The names of types whose per-file compilation cached Js and StatementRanges are known to no
* longer be valid.
* <p>
* Is initialized to the full initial list at the beginning of exec() and may be recalculated
* (larger) after Generator executions reveal more modified types.
*/
private Set<String> staleTypeNames = Sets.newHashSet();
/**
* The names of stale types that have been processed (fully traversed) so far.
*/
private Set<String> processedStaleTypeNames = Sets.newHashSet();
/**
* A work queue of methods whose bodies we need to traverse. Prevents
* excessive stack use.
*/
private final Queue<JMethod> methodsPending = Lists.newLinkedList();
private final Set<String> liveVirtualMethods = Sets.newHashSet();
private final Multimap<String, JMethod> pendingVirtualMethodsBySignature =
LinkedListMultimap.create();
private NameBasedTypeLocator sourceNameBasedTypeLocator;
private NameBasedTypeLocator binaryNameBasedTypeLocator;
private NameBasedTypeLocator internalNameBasedTypeLocator;
private MinimalRebuildCache minimalRebuildCache;
private boolean incrementalCompile;
private final List<String> rootTypeSourceNames = Lists.newArrayList();
public UnifyAst(TreeLogger logger, CompilerContext compilerContext, JProgram program,
JsProgram jsProgram, PrecompilationContext precompilationContext) {
this.incrementalCompile = compilerContext.getOptions().isIncrementalCompileEnabled();
this.logger = logger;
this.compilerContext = compilerContext;
this.program = program;
this.jsProgram = jsProgram;
this.rebindPermutationOracle = precompilationContext.getRebindPermutationOracle();
this.compilationState = rebindPermutationOracle.getCompilationState();
this.compiledClassesByInternalName = compilationState.getClassFileMap();
this.compiledClassesBySourceName = compilationState.getClassFileMapBySource();
initializeNameBasedLocators();
this.minimalRebuildCache = compilerContext.getMinimalRebuildCache();
if (incrementalCompile) {
minimalRebuildCache.addInjectedUnitCallback(program.getReferenceTypeOnlyRemover());
minimalRebuildCache.refreshInjectedUnits();
this.staleTypeNames =
minimalRebuildCache.computeAndClearStaleTypesCache(logger, program.typeOracle);
checkPreambleTypesStillFresh(logger);
}
// Magical methods are implemented by replacing their bodies during unification.
replacementValueByMagicMethodQualifiedName =
ImmutableMap.<String, JBooleanLiteral>builder()
.put(GWT_IS_CLIENT, JBooleanLiteral.TRUE)
.put(OLD_GWT_IS_CLIENT, JBooleanLiteral.TRUE)
.put(GWT_IS_PROD_MODE, JBooleanLiteral.TRUE)
.put(OLD_GWT_IS_PROD_MODE, JBooleanLiteral.TRUE)
.put(GWT_IS_SCRIPT, JBooleanLiteral.TRUE)
.put(OLD_GWT_IS_SCRIPT, JBooleanLiteral.TRUE)
.put(
CLASS_DESIRED_ASSERTION_STATUS,
JBooleanLiteral.get(compilerContext.getOptions().isEnableAssertions()))
.put(
CLASS_IS_CLASS_METADATA_ENABLED,
JBooleanLiteral.get(!compilerContext.getOptions().isClassMetadataDisabled()))
.build();
}
public void addRootTypes(Collection<String> rootTypeSourceNames) {
assert this.rootTypeSourceNames.isEmpty();
this.rootTypeSourceNames.addAll(rootTypeSourceNames);
}
/**
* Special AST construction, useful for tests. Everything is resolved,
* translated, and unified.
*/
public void buildEverything() throws UnableToCompleteException {
for (String internalName : compiledClassesByInternalName.keySet()) {
String typeName = InternalName.toBinaryName(internalName);
internalFindType(typeName, binaryNameBasedTypeLocator, true);
}
for (JDeclaredType type : program.getDeclaredTypes()) {
fullFlowIntoType(type);
}
mainLoop();
computeOverrides();
if (errorsFound) {
throw new UnableToCompleteException();
}
JavaAstVerifier.assertProgramIsConsistent(program);
}
/**
* Translates and stitches (unifies) type ASTs into one connected graph.<br />
*
* Only types reachable from entry points are traversed. This speeds, saves memory trims
* unreferenced elements.
*/
public void exec() throws UnableToCompleteException {
// Trace execution from entry points and resolve references.
List<String> entryMethodNames = Lists.newArrayList();
for (JMethod entryMethod : program.getEntryMethods()) {
flowInto(entryMethod);
entryMethodNames.add(entryMethod.getJsniSignature(true, true));
}
// Ensure that root types are loaded and possibly (depending on mode) traversed.
List<String> rootTypeBinaryNames = Lists.newArrayList();
for (String rootTypeSourceName : rootTypeSourceNames) {
JDeclaredType rootType =
internalFindType(rootTypeSourceName, sourceNameBasedTypeLocator, true);
if (rootType == null) {
continue;
}
rootTypeBinaryNames.add(rootType.getName());
if (rootType.hasJsInteropEntryPoints()) {
fullFlowIntoType(rootType);
}
}
minimalRebuildCache.setRootTypeNames(rootTypeBinaryNames);
minimalRebuildCache.setEntryMethodNames(entryMethodNames);
// Some fields and methods in codegen types might only become referenced as the result of
// visitor execution after unification. Since we don't want those fields are methods to be
// prematurely pruned here we defensively trace them now.
for (JClassType type : program.codeGenTypes) {
flowInto(type);
}
// Make sure that the rewriting pass for the types that are represented as natives have the
// needed members available.
for (JDeclaredType type : program.getRepresentedAsNativeTypes()) {
flowInto(type);
}
if (incrementalCompile) {
fullFlowIntoRemainingStaleTypes();
}
/*
* Since we're not actually optimizing here, it's easier to just visit
* certain things up front instead of duplicating the exacting semantics of
* ControlFlowAnalyzer.
*/
// String literals.
instantiate(program.getTypeJavaLangString());
// ControlFlowAnalyzer.rescueByConcat().
flowInto(program.getIndexedMethod(RuntimeConstants.OBJECT_TO_STRING));
flowInto((JMethod)
resolvedMembersByQualifiedName.get("java.lang.String.valueOf(C)Ljava/lang/String;"));
// FixAssignmentsToUnboxOrCast
AutoboxUtils autoboxUtils = new AutoboxUtils(program);
for (JMethod method : autoboxUtils.getBoxMethods()) {
flowInto(method);
}
for (JMethod method : autoboxUtils.getUnboxMethods()) {
flowInto(method);
}
// ReplaceRunAsyncs
if (compilerContext.getOptions().isRunAsyncEnabled()) {
flowInto(program.getIndexedMethod(RuntimeConstants.ASYNC_FRAGMENT_LOADER_ON_LOAD));
flowInto(program.getIndexedMethod(RuntimeConstants.ASYNC_FRAGMENT_LOADER_RUN_ASYNC));
}
// ImplementClassLiteralsAsFields
staticInitialize(program.getTypeClassLiteralHolder());
for (JMethod method : program.getTypeJavaLangClass().getMethods()) {
if (method.isStatic() && method.getName().startsWith("createFor")) {
flowInto(method);
}
}
mainLoop();
if (incrementalCompile) {
int declaredTypesInModule = program.getModuleDeclaredTypes().size();
MetricName.DECLARED_TYPES_IN_MODULE.setAmount(logger, declaredTypesInModule);