-
Notifications
You must be signed in to change notification settings - Fork 370
/
JavaToJavaScriptCompiler.java
1614 lines (1433 loc) · 68.8 KB
/
JavaToJavaScriptCompiler.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;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.linker.Artifact;
import com.google.gwt.core.ext.linker.ArtifactSet;
import com.google.gwt.core.ext.linker.CompilationMetricsArtifact;
import com.google.gwt.core.ext.linker.EmittedArtifact;
import com.google.gwt.core.ext.linker.EmittedArtifact.Visibility;
import com.google.gwt.core.ext.linker.ModuleMetricsArtifact;
import com.google.gwt.core.ext.linker.PrecompilationMetricsArtifact;
import com.google.gwt.core.ext.linker.StatementRanges;
import com.google.gwt.core.ext.linker.SymbolData;
import com.google.gwt.core.ext.linker.SyntheticArtifact;
import com.google.gwt.core.ext.linker.impl.StandardSymbolData;
import com.google.gwt.core.ext.soyc.SourceMapRecorder;
import com.google.gwt.core.ext.soyc.coderef.DependencyGraphRecorder;
import com.google.gwt.core.ext.soyc.coderef.EntityRecorder;
import com.google.gwt.core.ext.soyc.impl.DependencyRecorder;
import com.google.gwt.core.ext.soyc.impl.SizeMapRecorder;
import com.google.gwt.core.ext.soyc.impl.SplitPointRecorder;
import com.google.gwt.core.ext.soyc.impl.StoryRecorder;
import com.google.gwt.core.linker.SoycReportLinker;
import com.google.gwt.dev.CompilerContext;
import com.google.gwt.dev.MinimalRebuildCache;
import com.google.gwt.dev.Permutation;
import com.google.gwt.dev.PrecompileTaskOptions;
import com.google.gwt.dev.cfg.ConfigurationProperties;
import com.google.gwt.dev.cfg.EntryMethodHolderGenerator;
import com.google.gwt.dev.cfg.ModuleDef;
import com.google.gwt.dev.cfg.PermutationProperties;
import com.google.gwt.dev.javac.CompilationProblemReporter;
import com.google.gwt.dev.javac.CompilationState;
import com.google.gwt.dev.javac.StandardGeneratorContext;
import com.google.gwt.dev.javac.typemodel.TypeOracle;
import com.google.gwt.dev.jdt.RebindPermutationOracle;
import com.google.gwt.dev.jjs.UnifiedAst.AST;
import com.google.gwt.dev.jjs.ast.Context;
import com.google.gwt.dev.jjs.ast.JBlock;
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.JDeclaredType;
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.JProgram;
import com.google.gwt.dev.jjs.ast.JTypeOracle.StandardTypes;
import com.google.gwt.dev.jjs.ast.JVisitor;
import com.google.gwt.dev.jjs.impl.ArrayNormalizer;
import com.google.gwt.dev.jjs.impl.AssertionNormalizer;
import com.google.gwt.dev.jjs.impl.AssertionRemover;
import com.google.gwt.dev.jjs.impl.AstDumper;
import com.google.gwt.dev.jjs.impl.CatchBlockNormalizer;
import com.google.gwt.dev.jjs.impl.CompileTimeConstantsReplacer;
import com.google.gwt.dev.jjs.impl.ComputeCastabilityInformation;
import com.google.gwt.dev.jjs.impl.ComputeExhaustiveCastabilityInformation;
import com.google.gwt.dev.jjs.impl.ControlFlowAnalyzer;
import com.google.gwt.dev.jjs.impl.ControlFlowRecorder;
import com.google.gwt.dev.jjs.impl.DeadCodeElimination;
import com.google.gwt.dev.jjs.impl.Devirtualizer;
import com.google.gwt.dev.jjs.impl.EnumNameObfuscator;
import com.google.gwt.dev.jjs.impl.EnumOrdinalizer;
import com.google.gwt.dev.jjs.impl.EqualityNormalizer;
import com.google.gwt.dev.jjs.impl.Finalizer;
import com.google.gwt.dev.jjs.impl.FixAssignmentsToUnboxOrCast;
import com.google.gwt.dev.jjs.impl.FullOptimizerContext;
import com.google.gwt.dev.jjs.impl.GenerateJavaScriptAST;
import com.google.gwt.dev.jjs.impl.HandleCrossFragmentReferences;
import com.google.gwt.dev.jjs.impl.ImplementCastsAndTypeChecks;
import com.google.gwt.dev.jjs.impl.ImplementClassLiteralsAsFields;
import com.google.gwt.dev.jjs.impl.JavaAstVerifier;
import com.google.gwt.dev.jjs.impl.JavaToJavaScriptMap;
import com.google.gwt.dev.jjs.impl.JjsUtils;
import com.google.gwt.dev.jjs.impl.JsAbstractTextTransformer;
import com.google.gwt.dev.jjs.impl.JsFunctionClusterer;
import com.google.gwt.dev.jjs.impl.JsInteropRestrictionChecker;
import com.google.gwt.dev.jjs.impl.JsNoopTransformer;
import com.google.gwt.dev.jjs.impl.JsTypeLinker;
import com.google.gwt.dev.jjs.impl.JsniRestrictionChecker;
import com.google.gwt.dev.jjs.impl.LongCastNormalizer;
import com.google.gwt.dev.jjs.impl.LongEmulationNormalizer;
import com.google.gwt.dev.jjs.impl.MakeCallsStatic;
import com.google.gwt.dev.jjs.impl.MethodCallSpecializer;
import com.google.gwt.dev.jjs.impl.MethodCallTightener;
import com.google.gwt.dev.jjs.impl.MethodInliner;
import com.google.gwt.dev.jjs.impl.OptimizerContext;
import com.google.gwt.dev.jjs.impl.OptimizerStats;
import com.google.gwt.dev.jjs.impl.PostOptimizationCompoundAssignmentNormalizer;
import com.google.gwt.dev.jjs.impl.Pruner;
import com.google.gwt.dev.jjs.impl.RecordRebinds;
import com.google.gwt.dev.jjs.impl.RemoveEmptySuperCalls;
import com.google.gwt.dev.jjs.impl.RemoveSpecializations;
import com.google.gwt.dev.jjs.impl.ReplaceDefenderMethodReferences;
import com.google.gwt.dev.jjs.impl.ReplaceGetClassOverrides;
import com.google.gwt.dev.jjs.impl.ResolvePermutationDependentValues;
import com.google.gwt.dev.jjs.impl.ResolveRuntimeTypeReferences;
import com.google.gwt.dev.jjs.impl.ResolveRuntimeTypeReferences.ClosureUniqueIdTypeMapper;
import com.google.gwt.dev.jjs.impl.ResolveRuntimeTypeReferences.IntTypeMapper;
import com.google.gwt.dev.jjs.impl.ResolveRuntimeTypeReferences.StringTypeMapper;
import com.google.gwt.dev.jjs.impl.ResolveRuntimeTypeReferences.TypeMapper;
import com.google.gwt.dev.jjs.impl.ResolveRuntimeTypeReferences.TypeOrder;
import com.google.gwt.dev.jjs.impl.RewriteConstructorCallsForUnboxedTypes;
import com.google.gwt.dev.jjs.impl.SameParameterValueOptimizer;
import com.google.gwt.dev.jjs.impl.SourceInfoCorrelator;
import com.google.gwt.dev.jjs.impl.TypeCoercionNormalizer;
import com.google.gwt.dev.jjs.impl.TypeReferencesRecorder;
import com.google.gwt.dev.jjs.impl.TypeTightener;
import com.google.gwt.dev.jjs.impl.UnifyAst;
import com.google.gwt.dev.jjs.impl.codesplitter.CodeSplitter;
import com.google.gwt.dev.jjs.impl.codesplitter.CodeSplitters;
import com.google.gwt.dev.jjs.impl.codesplitter.MultipleDependencyGraphRecorder;
import com.google.gwt.dev.jjs.impl.codesplitter.ReplaceRunAsyncs;
import com.google.gwt.dev.jjs.impl.gflow.DataflowOptimizer;
import com.google.gwt.dev.js.BaselineCoverageGatherer;
import com.google.gwt.dev.js.ClosureJsRunner;
import com.google.gwt.dev.js.CoverageInstrumentor;
import com.google.gwt.dev.js.DuplicateClinitRemover;
import com.google.gwt.dev.js.EvalFunctionsAtTopScope;
import com.google.gwt.dev.js.FreshNameGenerator;
import com.google.gwt.dev.js.JsBreakUpLargeVarStatements;
import com.google.gwt.dev.js.JsDuplicateCaseFolder;
import com.google.gwt.dev.js.JsDuplicateFunctionRemover;
import com.google.gwt.dev.js.JsForceInliningChecker;
import com.google.gwt.dev.js.JsIncrementalNamer;
import com.google.gwt.dev.js.JsInliner;
import com.google.gwt.dev.js.JsLiteralInterner;
import com.google.gwt.dev.js.JsNamer.IllegalNameException;
import com.google.gwt.dev.js.JsNamespaceChooser;
import com.google.gwt.dev.js.JsNamespaceOption;
import com.google.gwt.dev.js.JsNormalizer;
import com.google.gwt.dev.js.JsObfuscateNamer;
import com.google.gwt.dev.js.JsPrettyNamer;
import com.google.gwt.dev.js.JsReportGenerationVisitor;
import com.google.gwt.dev.js.JsStackEmulator;
import com.google.gwt.dev.js.JsStaticEval;
import com.google.gwt.dev.js.JsSymbolResolver;
import com.google.gwt.dev.js.JsUnusedFunctionRemover;
import com.google.gwt.dev.js.JsVerboseNamer;
import com.google.gwt.dev.js.SizeBreakdown;
import com.google.gwt.dev.js.ast.JavaScriptVerifier;
import com.google.gwt.dev.js.ast.JsContext;
import com.google.gwt.dev.js.ast.JsForIn;
import com.google.gwt.dev.js.ast.JsFunction;
import com.google.gwt.dev.js.ast.JsLabel;
import com.google.gwt.dev.js.ast.JsLiteral;
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.JsNode;
import com.google.gwt.dev.js.ast.JsParameter;
import com.google.gwt.dev.js.ast.JsProgram;
import com.google.gwt.dev.js.ast.JsVars;
import com.google.gwt.dev.js.ast.JsVisitor;
import com.google.gwt.dev.util.DefaultTextOutput;
import com.google.gwt.dev.util.Memory;
import com.google.gwt.dev.util.Name.SourceName;
import com.google.gwt.dev.util.Pair;
import com.google.gwt.dev.util.Util;
import com.google.gwt.dev.util.arg.OptionOptimize;
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.soyc.SoycDashboard;
import com.google.gwt.soyc.io.ArtifactsOutputDirectory;
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.Lists;
import com.google.gwt.thirdparty.guava.common.collect.Multimap;
import com.google.gwt.thirdparty.guava.common.collect.Sets;
import org.xml.sax.SAXException;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.ParserConfigurationException;
/**
* A base for classes that compile Java <code>JProgram</code> representations into corresponding Js
* source.<br />
*
* Work is split between a precompile() stage which is only called once and compilePerms() stage
* which is called once per permutation. This allow build systems the option of distributing and
* parallelizing some of the work.
*/
public final class JavaToJavaScriptCompiler {
/**
* Ending optimization passes when the rate of change has reached this value results in gaining
* nearly all of the impact while avoiding the long tail of costly but low-impact passes.
*/
private static final float EFFICIENT_CHANGE_RATE = 0.01f;
/**
* Continuing to apply optimizations till the rate of change reaches this value causes the AST to
* reach a fixed point.
*/
private static final int FIXED_POINT_CHANGE_RATE = 0;
/**
* Limits the number of optimization passes against the possible danger of an AST that does not
* converge.
*/
private static final int MAX_PASSES = 100;
static {
// Preload the internal compiler exception just in case we run out of memory?.
InternalCompilerException.preload();
}
private final CompilerContext compilerContext;
private final TreeLogger logger;
private final ModuleDef module;
private final PrecompileTaskOptions options;
private JsProgram jsProgram;
private JProgram jprogram;
public JavaToJavaScriptCompiler(TreeLogger logger, CompilerContext compilerContext) {
this.logger = logger;
this.compilerContext = compilerContext;
this.module = compilerContext.getModule();
this.options = compilerContext.getOptions();
}
public static UnifiedAst precompile(TreeLogger logger, CompilerContext compilerContext,
PrecompilationContext precompilationContext)
throws UnableToCompleteException {
return new JavaToJavaScriptCompiler(logger, compilerContext).precompile(precompilationContext);
}
/**
* Compiles a particular permutation.
*
* @param logger the logger to use
* @param compilerContext shared read only compiler state
* @param permutation the permutation to compile
* @return the permutation result
* @throws UnableToCompleteException if an error other than {@link OutOfMemoryError} occurs
*/
public static PermutationResult compilePermutation(UnifiedAst unifiedAst,
TreeLogger logger, CompilerContext compilerContext, Permutation permutation)
throws UnableToCompleteException {
JavaToJavaScriptCompiler javaToJavaScriptCompiler =
new JavaToJavaScriptCompiler(logger, compilerContext);
return javaToJavaScriptCompiler.compilePermutation(permutation, unifiedAst);
}
/**
* Takes as input an unresolved Java AST (a Java AST wherein all rebind result classes are
* available and have not yet been pruned down to the set applicable for a particular permutation)
* that was previously constructed by the Precompiler and from that constructs output Js source
* code and related information. This Js source and related information is packaged into a
* Permutation instance and then returned.
*
* Permutation compilation is INTENDED to progress as a series of stages:
*
* <pre>
* 1. initialize local state
* 2. transform unresolved Java AST to resolved Java AST
* 3. normalize the resolved Java AST
* 4. optimize the resolved Java AST
* 5. construct the Js AST
* 6. normalize the Js AST
* 7. optimize the Js AST
* 8. generate Js source
* 9. construct and return a value
* </pre>
*
* There are some other types of work here (mostly metrics and data gathering) which do not serve
* the goal of output program construction. This work should really be moved into subclasses or
* some sort of callback or plugin system so as not to visually pollute the real compile logic.<br
* />
*
* Significant amounts of visitors implementing the intended above stages are triggered here but
* in the wrong order. They have been noted for future cleanup.
*/
private PermutationResult compilePermutation(Permutation permutation, UnifiedAst unifiedAst)
throws UnableToCompleteException {
Event jjsCompilePermutationEvent = SpeedTracerLogger.start(
CompilerEventType.JJS_COMPILE_PERMUTATION, "name", permutation.getProperties().prettyPrint()
);
/*
* Do not introduce any new pass here unless it is logically a part of one of the 9 defined
* stages and is physically located in that stage.
*/
long permStartMs = System.currentTimeMillis();
try {
Event javaEvent = SpeedTracerLogger.start(CompilerEventType.PERMUTATION_JAVA);
// (1) Initialize local state.
long startTimeMs = System.currentTimeMillis();
PermutationProperties properties = permutation.getProperties();
int permutationId = permutation.getId();
AST ast = unifiedAst.getFreshAst();
jprogram = ast.getJProgram();
jsProgram = ast.getJsProgram();
Map<StandardSymbolData, JsName> symbolTable =
new TreeMap<StandardSymbolData, JsName>(new SymbolData.ClassIdentComparator());
// TODO(stalcup): hide metrics gathering in a callback or subclass
logger.log(TreeLogger.INFO, "Compiling permutation " + permutationId + "...");
// Rewrite calls to from boxed constructor types to specialized unboxed methods
RewriteConstructorCallsForUnboxedTypes.exec(jprogram);
// (2) Transform unresolved Java AST to resolved Java AST
ResolvePermutationDependentValues
.exec(jprogram, properties, permutation.getPropertyAndBindingInfos());
// TODO(stalcup): hide metrics gathering in a callback or subclass
// This has to happen before optimizations because functions might
// be optimized out; we want those marked as "not executed", not "not
// instrumentable".
Multimap<String, Integer> instrumentableLines = null;
if (System.getProperty("gwt.coverage") != null) {
instrumentableLines = BaselineCoverageGatherer.exec(jprogram);
}
// Record initial set of type->type references.
// type->type references need to be collected in two phases, 1) before any process to the
// AST has happened (to record for example reference to types declaring compile-time
// constants) and 2) after all normalizations to collect synthetic references (e.g. to
// record references to runtime classes like LongLib).
maybeRecordReferencesAndControlFlow(false);
// Replace compile time constants by their values.
// TODO(rluble): eventually move to normizeSemantics.
CompileTimeConstantsReplacer.exec(jprogram);
// TODO(stalcup): move to after normalize.
// (3) Optimize the resolved Java AST
optimizeJava();
// TODO(stalcup): move to before optimize.
// (4) Normalize the resolved Java AST
TypeMapper<?> typeMapper = normalizeSemantics();
// TODO(stalcup): this stage shouldn't exist, move into optimize.
postNormalizationOptimizeJava();
// Now that the AST has stopped mutating update with the final references.
maybeRecordReferencesAndControlFlow(true);
javaEvent.end();
Event javaScriptEvent = SpeedTracerLogger.start(CompilerEventType.PERMUTATION_JAVASCRIPT);
// (5) Construct the Js AST
Pair<? extends JavaToJavaScriptMap, Set<JsNode>> jjsMapAndInlineableFunctions =
GenerateJavaScriptAST.exec(logger, jprogram, jsProgram,
compilerContext, typeMapper, symbolTable, properties);
JavaToJavaScriptMap jjsmap = jjsMapAndInlineableFunctions.getLeft();
// TODO(stalcup): hide metrics gathering in a callback or subclass
if (System.getProperty("gwt.coverage") != null) {
CoverageInstrumentor.exec(jsProgram, instrumentableLines);
}
// (6) Normalize the Js AST
JsNormalizer.exec(jsProgram);
// TODO(stalcup): move to AST construction
JsSymbolResolver.exec(jsProgram);
if (options.getNamespace() == JsNamespaceOption.PACKAGE) {
if (!jprogram.getRunAsyncs().isEmpty()) {
options.setNamespace(JsNamespaceOption.NONE);
logger.log(TreeLogger.Type.WARN,
"Namespace option is not compatible with CodeSplitter, turning it off.");
} else {
JsNamespaceChooser.exec(jsProgram, jjsmap);
}
}
// TODO(stalcup): move to normalization
EvalFunctionsAtTopScope.exec(jsProgram, jjsmap);
// (7) Optimize the JS AST.
final Set<JsNode> inlinableJsFunctions = jjsMapAndInlineableFunctions.getRight();
optimizeJs(inlinableJsFunctions);
if (options.getOptimizationLevel() > OptionOptimize.OPTIMIZE_LEVEL_DRAFT) {
JsForceInliningChecker.check(logger, jjsmap, jsProgram);
}
// TODO(stalcup): move to normalization
// Must run before code splitter and namer.
JsStackEmulator.exec(jprogram, jsProgram, properties, jjsmap);
// TODO(stalcup): move to normalization
Pair<SyntheticArtifact, MultipleDependencyGraphRecorder> dependenciesAndRecorder =
splitJsIntoFragments(properties, permutationId, jjsmap);
// TODO(stalcup): move to optimize.
Map<JsName, JsLiteral> internedLiteralByVariableName = renameJsSymbols(properties, jjsmap);
// TODO(stalcup): move to normalization
JsBreakUpLargeVarStatements.exec(jsProgram, properties.getConfigurationProperties());
if (!options.isIncrementalCompileEnabled()) {
// Verifies consistency between jsProgram and jjsmap if assertions are enabled.
// TODO(rluble): make it work for incremental compiles.
JavaScriptVerifier.verify(jsProgram, jjsmap);
}
// (8) Generate Js source
List<JsSourceMap> sourceInfoMaps = new ArrayList<JsSourceMap>();
boolean isSourceMapsEnabled = properties.isTrueInAnyPermutation("compiler.useSourceMaps");
String[] jsFragments = new String[jsProgram.getFragmentCount()];
StatementRanges[] ranges = new StatementRanges[jsFragments.length];
SizeBreakdown[] sizeBreakdowns = options.isJsonSoycEnabled() || options.isSoycEnabled()
|| options.isCompilerMetricsEnabled() ? new SizeBreakdown[jsFragments.length] : null;
generateJavaScriptCode(jjsmap, jsFragments, ranges, sizeBreakdowns, sourceInfoMaps,
isSourceMapsEnabled || options.isJsonSoycEnabled());
javaScriptEvent.end();
// (9) Construct and return a value
PermutationResult permutationResult =
new PermutationResultImpl(jsFragments, permutation, makeSymbolMap(symbolTable), ranges);
// TODO(stalcup): hide metrics gathering in a callback or subclass
addSyntheticArtifacts(unifiedAst, permutation, startTimeMs, permutationId, jjsmap,
dependenciesAndRecorder, internedLiteralByVariableName, isSourceMapsEnabled, jsFragments,
sizeBreakdowns, sourceInfoMaps, permutationResult);
return permutationResult;
} catch (Throwable e) {
throw CompilationProblemReporter.logAndTranslateException(logger, e);
} finally {
jjsCompilePermutationEvent.end();
if (logger.isLoggable(TreeLogger.TRACE)) {
logger.log(TreeLogger.TRACE,
"Permutation took " + (System.currentTimeMillis() - permStartMs) + " ms");
}
}
}
private void maybeRecordReferencesAndControlFlow(boolean onlyUpdate) {
if (options.isIncrementalCompileEnabled()) {
// Per file compilation needs the type reference graph to construct the set of reachable
// types when linking.
TypeReferencesRecorder.exec(jprogram, getMinimalRebuildCache(), onlyUpdate);
ControlFlowRecorder.exec(jprogram, getMinimalRebuildCache().getTypeEnvironment(),
onlyUpdate);
}
}
/**
* Transform patterns that can't be represented in JS (such as multiple catch blocks) into
* equivalent but compatible patterns and take JVM semantics (such as numeric casts) that are not
* explicit in the AST and make them explicit.<br />
*
* These passes can not be reordering because of subtle interdependencies.
*/
protected TypeMapper<?> normalizeSemantics() {
Event event = SpeedTracerLogger.start(CompilerEventType.JAVA_NORMALIZERS);
try {
Devirtualizer.exec(jprogram);
CatchBlockNormalizer.exec(jprogram);
PostOptimizationCompoundAssignmentNormalizer.exec(jprogram);
LongCastNormalizer.exec(jprogram);
LongEmulationNormalizer.exec(jprogram);
TypeCoercionNormalizer.exec(jprogram);
if (options.isIncrementalCompileEnabled()) {
// Per file compilation reuses type JS even as references (like casts) in other files
// change, which means all legal casts need to be allowed now before they are actually
// used later.
ComputeExhaustiveCastabilityInformation.exec(jprogram);
} else {
// If trivial casts are pruned then one can use smaller runtime castmaps.
ComputeCastabilityInformation.exec(jprogram, !shouldOptimize() /* recordTrivialCasts */);
}
ImplementCastsAndTypeChecks.exec(jprogram, shouldOptimize() /* pruneTrivialCasts */);
ArrayNormalizer.exec(jprogram);
EqualityNormalizer.exec(jprogram);
TypeMapper<?> typeMapper = getTypeMapper();
ResolveRuntimeTypeReferences.exec(jprogram, typeMapper, getTypeOrder());
return typeMapper;
} finally {
event.end();
}
}
private void optimizeJava() throws InterruptedException {
if (shouldOptimize()) {
optimizeJavaToFixedPoint();
RemoveEmptySuperCalls.exec(jprogram);
}
}
private void optimizeJs(Set<JsNode> inlinableJsFunctions) throws InterruptedException {
if (shouldOptimize()) {
optimizeJsLoop(inlinableJsFunctions);
JsDuplicateCaseFolder.exec(jsProgram);
}
}
private void postNormalizationOptimizeJava() {
Event event = SpeedTracerLogger.start(CompilerEventType.JAVA_POST_NORMALIZER_OPTIMIZERS);
try {
if (shouldOptimize()) {
RemoveSpecializations.exec(jprogram);
Pruner.exec(jprogram, false);
// Last Java optimization step, update type oracle accordingly.
jprogram.typeOracle.recomputeAfterOptimizations(jprogram.getDeclaredTypes());
}
ReplaceGetClassOverrides.exec(jprogram);
} finally {
event.end();
}
}
private Map<JsName, JsLiteral> runDetailedNamer(ConfigurationProperties config)
throws IllegalNameException {
Map<JsName, JsLiteral> internedTextByVariableName =
maybeInternLiterals(JsLiteralInterner.INTERN_ALL);
JsVerboseNamer.exec(jsProgram, config);
return internedTextByVariableName;
}
private Map<JsName, JsLiteral> maybeInternLiterals(int interningMask) {
if (!shouldOptimize()) {
return null;
}
// Only perform the interning optimization when optimizations are enabled.
if (options.isClosureCompilerFormatEnabled()) {
// Do no intern strings in closure format as it breaks goog.provides, etc.
interningMask &= ~JsLiteralInterner.INTERN_STRINGS;
}
return JsLiteralInterner.exec(jprogram, jsProgram, interningMask);
}
private Pair<SyntheticArtifact, MultipleDependencyGraphRecorder> splitJsIntoFragments(
PermutationProperties properties, int permutationId, JavaToJavaScriptMap jjsmap) {
Pair<SyntheticArtifact, MultipleDependencyGraphRecorder> dependenciesAndRecorder;
MultipleDependencyGraphRecorder dependencyRecorder = null;
SyntheticArtifact dependencies = null;
if (options.isRunAsyncEnabled()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int expectedFragmentCount = options.getFragmentCount();
// -1 is the default value, we trap 0 just in case (0 is not a legal value in any case)
if (expectedFragmentCount <= 0) {
// Fragment count not set check fragments merge.
int numberOfMerges = options.getFragmentsMerge();
if (numberOfMerges > 0) {
// + 1 for left over, + 1 for initial gave us the total number
// of fragments without splitting.
expectedFragmentCount =
Math.max(0, jprogram.getRunAsyncs().size() + 2 - numberOfMerges);
}
}
int minFragmentSize = properties.getConfigurationProperties()
.getInteger(CodeSplitters.MIN_FRAGMENT_SIZE, 0);
dependencyRecorder = chooseDependencyRecorder(baos);
CodeSplitter.exec(logger, jprogram, jsProgram, jjsmap, expectedFragmentCount,
minFragmentSize, dependencyRecorder);
if (baos.size() == 0) {
dependencyRecorder = recordNonSplitDependencies(baos);
}
if (baos.size() > 0) {
dependencies = new SyntheticArtifact(
SoycReportLinker.class, "dependencies" + permutationId + ".xml.gz",
baos.toByteArray());
}
} else if (options.isSoycEnabled() || options.isJsonSoycEnabled()) {
dependencyRecorder = recordNonSplitDependencies(new ByteArrayOutputStream());
}
dependenciesAndRecorder = Pair.create(
dependencies, dependencyRecorder);
// No new JsNames or references to JSNames can be introduced after this
// point.
HandleCrossFragmentReferences.exec(jsProgram, properties);
return dependenciesAndRecorder;
}
private MultipleDependencyGraphRecorder chooseDependencyRecorder(OutputStream out) {
MultipleDependencyGraphRecorder dependencyRecorder =
MultipleDependencyGraphRecorder.NULL_RECORDER;
if (options.isSoycEnabled() && options.isJsonSoycEnabled()) {
dependencyRecorder = new DependencyGraphRecorder(out, jprogram);
} else if (options.isSoycEnabled()) {
dependencyRecorder = new DependencyRecorder(out);
} else if (options.isJsonSoycEnabled()) {
dependencyRecorder = new DependencyGraphRecorder(out, jprogram);
}
return dependencyRecorder;
}
/**
* Dependency information is normally recorded during code splitting, and it results in multiple
* dependency graphs. If the code splitter doesn't run, then this method can be used instead to
* record a single dependency graph for the whole program.
*/
private DependencyRecorder recordNonSplitDependencies(OutputStream out) {
DependencyRecorder deps;
if (options.isSoycEnabled() && options.isJsonSoycEnabled()) {
deps = new DependencyGraphRecorder(out, jprogram);
} else if (options.isSoycEnabled()) {
deps = new DependencyRecorder(out);
} else if (options.isJsonSoycEnabled()) {
deps = new DependencyGraphRecorder(out, jprogram);
} else {
return null;
}
deps.open();
deps.startDependencyGraph("initial", null);
ControlFlowAnalyzer cfa = new ControlFlowAnalyzer(jprogram);
cfa.setDependencyRecorder(deps);
cfa.traverseEntryMethods();
deps.endDependencyGraph();
deps.close();
return deps;
}
private CompilationMetricsArtifact addCompilerMetricsArtifact(UnifiedAst unifiedAst,
Permutation permutation, long startTimeMs, SizeBreakdown[] sizeBreakdowns,
PermutationResult permutationResult) {
CompilationMetricsArtifact compilationMetrics = null;
// TODO: enable this when ClosureCompiler is enabled
if (options.isCompilerMetricsEnabled()) {
if (options.isClosureCompilerEnabled()) {
logger.log(TreeLogger.WARN, "Incompatible options: -XenableClosureCompiler and "
+ "-XcompilerMetric; ignoring -XcompilerMetric.");
} else {
compilationMetrics = new CompilationMetricsArtifact(permutation.getId());
compilationMetrics.setCompileElapsedMilliseconds(
System.currentTimeMillis() - startTimeMs);
compilationMetrics.setElapsedMilliseconds(
System.currentTimeMillis() - ManagementFactory.getRuntimeMXBean().getStartTime());
compilationMetrics.setJsSize(sizeBreakdowns);
compilationMetrics.setPermutationDescription(permutation.getProperties().prettyPrint());
permutationResult.addArtifacts(Lists.newArrayList(
unifiedAst.getModuleMetrics(), unifiedAst.getPrecompilationMetrics(),
compilationMetrics));
}
}
return compilationMetrics;
}
private void addSourceMapArtifacts(int permutationId, JavaToJavaScriptMap jjsmap,
Pair<SyntheticArtifact, MultipleDependencyGraphRecorder> dependenciesAndRecorder,
boolean isSourceMapsEnabled, SizeBreakdown[] sizeBreakdowns,
List<JsSourceMap> sourceInfoMaps, PermutationResult permutationResult) {
if (options.isJsonSoycEnabled()) {
// TODO: enable this when ClosureCompiler is enabled
if (options.isClosureCompilerEnabled()) {
logger.log(TreeLogger.WARN, "Incompatible options: -XenableClosureCompiler and "
+ "-XjsonSoyc; ignoring -XjsonSoyc.");
} else {
// Is a super set of SourceMapRecorder.makeSourceMapArtifacts().
permutationResult.addArtifacts(EntityRecorder.makeSoycArtifacts(
permutationId, sourceInfoMaps, options.getSourceMapFilePrefix(),
jjsmap, sizeBreakdowns,
((DependencyGraphRecorder) dependenciesAndRecorder.getRight()), jprogram));
}
} else if (isSourceMapsEnabled) {
// TODO: enable this when ClosureCompiler is enabled
if (options.isClosureCompilerEnabled()) {
logger.log(TreeLogger.WARN, "Incompatible options: -XenableClosureCompiler and "
+ "compiler.useSourceMaps=true; ignoring compiler.useSourceMaps=true.");
} else {
logger.log(TreeLogger.INFO, "Source Maps Enabled");
permutationResult.addArtifacts(SourceMapRecorder.exec(permutationId, sourceInfoMaps,
options.getSourceMapFilePrefix()));
}
}
}
/**
* Adds generated artifacts from previous compiles when doing per-file compiles. <p> All
* generators are run on first compile but only some very small subset are rerun on recompiles.
* Care must be taken to ensure that all generated artifacts (such as png/html/css files) are
* still registered for output even when no generators are run in the current compile.
*/
private void maybeAddGeneratedArtifacts(PermutationResult permutationResult) {
if (options.isIncrementalCompileEnabled()) {
permutationResult.addArtifacts(
compilerContext.getMinimalRebuildCache().getGeneratedArtifacts());
}
}
private void addSoycArtifacts(UnifiedAst unifiedAst, int permutationId,
JavaToJavaScriptMap jjsmap,
Pair<SyntheticArtifact, MultipleDependencyGraphRecorder> dependenciesAndRecorder,
Map<JsName, JsLiteral> internedLiteralByVariableName, String[] js,
SizeBreakdown[] sizeBreakdowns,
List<JsSourceMap> sourceInfoMaps, PermutationResult permutationResult,
CompilationMetricsArtifact compilationMetrics)
throws IOException, UnableToCompleteException {
// TODO: enable this when ClosureCompiler is enabled
if (options.isClosureCompilerEnabled()) {
if (options.isSoycEnabled()) {
logger.log(TreeLogger.WARN, "Incompatible options: -XenableClosureCompiler and "
+ "-compileReport; ignoring -compileReport.");
}
} else {
permutationResult.addArtifacts(makeSoycArtifacts(permutationId, js, sizeBreakdowns,
options.isSoycExtra() ? sourceInfoMaps : null, dependenciesAndRecorder.getLeft(),
jjsmap, internedLiteralByVariableName, unifiedAst.getModuleMetrics(),
unifiedAst.getPrecompilationMetrics(), compilationMetrics,
options.isSoycHtmlDisabled()));
}
}
private void addSyntheticArtifacts(UnifiedAst unifiedAst, Permutation permutation,
long startTimeMs, int permutationId, JavaToJavaScriptMap jjsmap,
Pair<SyntheticArtifact, MultipleDependencyGraphRecorder> dependenciesAndRecorder,
Map<JsName, JsLiteral> internedLiteralByVariableName, boolean isSourceMapsEnabled,
String[] jsFragments, SizeBreakdown[] sizeBreakdowns,
List<JsSourceMap> sourceInfoMaps, PermutationResult permutationResult)
throws IOException, UnableToCompleteException {
assert internedLiteralByVariableName != null;
Event event = SpeedTracerLogger.start(CompilerEventType.PERMUTATION_ARTIFACTS);
CompilationMetricsArtifact compilationMetrics = addCompilerMetricsArtifact(
unifiedAst, permutation, startTimeMs, sizeBreakdowns, permutationResult);
addSoycArtifacts(unifiedAst, permutationId, jjsmap, dependenciesAndRecorder,
internedLiteralByVariableName, jsFragments, sizeBreakdowns, sourceInfoMaps,
permutationResult, compilationMetrics);
addSourceMapArtifacts(permutationId, jjsmap, dependenciesAndRecorder, isSourceMapsEnabled,
sizeBreakdowns, sourceInfoMaps, permutationResult);
maybeAddGeneratedArtifacts(permutationResult);
event.end();
}
/**
* Generate Js code from the given Js ASTs. Also produces information about that transformation.
*/
private void generateJavaScriptCode(JavaToJavaScriptMap jjsMap, String[] jsFragments,
StatementRanges[] ranges, SizeBreakdown[] sizeBreakdowns,
List<JsSourceMap> sourceInfoMaps, boolean sourceMapsEnabled) {
Event generateJavascriptEvent =
SpeedTracerLogger.start(CompilerEventType.GENERATE_JAVASCRIPT);
boolean useClosureCompiler = options.isClosureCompilerEnabled();
if (useClosureCompiler) {
ClosureJsRunner runner = new ClosureJsRunner();
runner.compile(jprogram, jsProgram, jsFragments, options.getOutput());
generateJavascriptEvent.end();
return;
}
for (int i = 0; i < jsFragments.length; i++) {
DefaultTextOutput out = new DefaultTextOutput(!options.isIncrementalCompileEnabled() &&
options.getOutput().shouldMinimize());
JsReportGenerationVisitor v = new JsReportGenerationVisitor(out, jjsMap,
options.isJsonSoycEnabled());
v.accept(jsProgram.getFragmentBlock(i));
StatementRanges statementRanges = v.getStatementRanges();
String code = out.toString();
JsSourceMap infoMap = (sourceInfoMaps != null) ? v.getSourceInfoMap() : null;
JsAbstractTextTransformer transformer =
new JsNoopTransformer(code, statementRanges, infoMap);
/**
* Cut generated JS up on class boundaries and re-link the source (possibly making use of
* source from previous compiles, thus making it possible to perform partial recompiles).
*/
if (options.isIncrementalCompileEnabled()) {
transformer = new JsTypeLinker(logger, transformer, v.getClassRanges(),
v.getProgramClassRange(), getMinimalRebuildCache(), jprogram.typeOracle);
transformer.exec();
}
/**
* Reorder function decls to improve compression ratios. Also restructures the top level
* blocks into sub-blocks if they exceed 32767 statements.
*/
Event functionClusterEvent = SpeedTracerLogger.start(CompilerEventType.FUNCTION_CLUSTER);
// TODO(cromwellian) move to the Js AST optimization, re-enable sourcemaps + clustering
if (!sourceMapsEnabled && !options.isClosureCompilerFormatEnabled()
&& options.shouldClusterSimilarFunctions()
&& options.getNamespace() == JsNamespaceOption.NONE
&& options.getOutput() == JsOutputOption.OBFUSCATED) {
transformer = new JsFunctionClusterer(transformer);
transformer.exec();
}
functionClusterEvent.end();
jsFragments[i] = transformer.getJs();
ranges[i] = transformer.getStatementRanges();
if (sizeBreakdowns != null) {
sizeBreakdowns[i] = v.getSizeBreakdown();
}
if (sourceInfoMaps != null) {
sourceInfoMaps.add(transformer.getSourceInfoMap());
}
}
generateJavascriptEvent.end();
}
private Collection<? extends Artifact<?>> makeSoycArtifacts(int permutationId, String[] js,
SizeBreakdown[] sizeBreakdowns, List<JsSourceMap> sourceInfoMaps,
SyntheticArtifact dependencies, JavaToJavaScriptMap jjsmap,
Map<JsName, JsLiteral> internedLiteralByVariableName,
ModuleMetricsArtifact moduleMetricsArtifact,
PrecompilationMetricsArtifact precompilationMetricsArtifact,
CompilationMetricsArtifact compilationMetrics, boolean htmlReportsDisabled)
throws IOException, UnableToCompleteException {
Memory.maybeDumpMemory("makeSoycArtifactsStart");
List<SyntheticArtifact> soycArtifacts = new ArrayList<SyntheticArtifact>();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Event soycEvent = SpeedTracerLogger.start(CompilerEventType.MAKE_SOYC_ARTIFACTS);
Event recordSplitPoints = SpeedTracerLogger.start(
CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSplitPoints");
SplitPointRecorder.recordSplitPoints(jprogram, baos, logger);
SyntheticArtifact splitPoints = new SyntheticArtifact(
SoycReportLinker.class, "splitPoints" + permutationId + ".xml.gz", baos.toByteArray());
soycArtifacts.add(splitPoints);
recordSplitPoints.end();
SyntheticArtifact sizeMaps = null;
if (sizeBreakdowns != null) {
Event recordSizeMap = SpeedTracerLogger.start(
CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSizeMap");
baos.reset();
SizeMapRecorder.recordMap(logger, baos, sizeBreakdowns, jjsmap,
internedLiteralByVariableName);
sizeMaps = new SyntheticArtifact(
SoycReportLinker.class, "stories" + permutationId + ".xml.gz", baos.toByteArray());
soycArtifacts.add(sizeMaps);
recordSizeMap.end();
}
if (sourceInfoMaps != null) {
Event recordStories = SpeedTracerLogger.start(
CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordStories");
baos.reset();
StoryRecorder.recordStories(logger, baos, sourceInfoMaps, js);
soycArtifacts.add(new SyntheticArtifact(
SoycReportLinker.class, "detailedStories" + permutationId + ".xml.gz",
baos.toByteArray()));
recordStories.end();
}
if (dependencies != null) {
soycArtifacts.add(dependencies);
}
// Set all of the main SOYC artifacts private.
for (SyntheticArtifact soycArtifact : soycArtifacts) {
soycArtifact.setVisibility(Visibility.Private);
}
if (!htmlReportsDisabled && sizeBreakdowns != null) {
Event generateCompileReport = SpeedTracerLogger.start(
CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "generateCompileReport");
ArtifactsOutputDirectory outDir = new ArtifactsOutputDirectory();
SoycDashboard dashboard = new SoycDashboard(outDir);
dashboard.startNewPermutation(Integer.toString(permutationId));
try {
dashboard.readSplitPoints(openWithGunzip(splitPoints));
if (sizeMaps != null) {
dashboard.readSizeMaps(openWithGunzip(sizeMaps));
}
if (dependencies != null) {
dashboard.readDependencies(openWithGunzip(dependencies));
}
Memory.maybeDumpMemory("soycReadDependenciesEnd");
} catch (ParserConfigurationException e) {
throw new InternalCompilerException(
"Error reading compile report information that was just generated", e);
} catch (SAXException e) {
throw new InternalCompilerException(
"Error reading compile report information that was just generated", e);
}
dashboard.generateForOnePermutation();
if (moduleMetricsArtifact != null && precompilationMetricsArtifact != null
&& compilationMetrics != null) {
dashboard.generateCompilerMetricsForOnePermutation(
moduleMetricsArtifact, precompilationMetricsArtifact, compilationMetrics);
}
soycArtifacts.addAll(outDir.getArtifacts());
generateCompileReport.end();
}
soycEvent.end();
return soycArtifacts;
}
private SymbolData[] makeSymbolMap(Map<StandardSymbolData, JsName> symbolTable) {
// Keep tracks of a list of referenced name. If it is not used, don't
// add it to symbol map.
final Set<String> nameUsed = new HashSet<String>();
final Map<JsName, Integer> nameToFragment = new HashMap<JsName, Integer>();
for (int i = 0; i < jsProgram.getFragmentCount(); i++) {
final Integer fragId = i;
new JsVisitor() {
@Override
public void endVisit(JsForIn x, JsContext ctx) {
if (x.getIterVarName() != null) {
nameUsed.add(x.getIterVarName().getIdent());
}
}
@Override
public void endVisit(JsFunction x, JsContext ctx) {
if (x.getName() != null) {
nameToFragment.put(x.getName(), fragId);
nameUsed.add(x.getName().getIdent());
}
}
@Override
public void endVisit(JsLabel x, JsContext ctx) {
nameUsed.add(x.getName().getIdent());
}
@Override
public void endVisit(JsNameOf x, JsContext ctx) {
if (x.getName() != null) {
nameUsed.add(x.getName().getIdent());
}
}
@Override
public void endVisit(JsNameRef x, JsContext ctx) {
// Obviously this isn't even that accurate. Some of them are
// variable names, some of the are property. At least this
// this give us a safe approximation. Ideally we need
// the code removal passes to remove stuff in the scope objects.
if (x.isResolved()) {
nameUsed.add(x.getName().getIdent());
}
}
@Override
public void endVisit(JsParameter x, JsContext ctx) {
nameUsed.add(x.getName().getIdent());
}
@Override
public void endVisit(JsVars.JsVar x, JsContext ctx) {
nameUsed.add(x.getName().getIdent());
}
}.accept(jsProgram.getFragmentBlock(i));
}
// TODO(acleung): This is a temp fix. Once we know this is safe. We
// new to rewrite it to avoid extra ArrayList creations.
// Or we should just consider serializing it as an ArrayList if
// it is that much trouble to determine the true size.
List<SymbolData> result = new ArrayList<SymbolData>();
for (Map.Entry<StandardSymbolData, JsName> entry : symbolTable.entrySet()) {
StandardSymbolData symbolData = entry.getKey();
symbolData.setSymbolName(entry.getValue().getShortIdent());
Integer fragNum = nameToFragment.get(entry.getValue());
if (fragNum != null) {
symbolData.setFragmentNumber(fragNum);
}