-
Notifications
You must be signed in to change notification settings - Fork 159
/
Java2TypeScriptTranslator.java
7018 lines (6411 loc) · 319 KB
/
Java2TypeScriptTranslator.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
/*
* JSweet transpiler - http://www.jsweet.org
* Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jsweet.transpiler;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.jsweet.JSweetConfig.ANNOTATION_ERASED;
import static org.jsweet.JSweetConfig.ANNOTATION_STRING_ENUM;
import static org.jsweet.JSweetConfig.ANNOTATION_FUNCTIONAL_INTERFACE;
import static org.jsweet.JSweetConfig.ANNOTATION_OBJECT_TYPE;
import static org.jsweet.JSweetConfig.ANNOTATION_STRING_TYPE;
import static org.jsweet.JSweetConfig.GLOBALS_CLASS_NAME;
import static org.jsweet.JSweetConfig.GLOBALS_PACKAGE_NAME;
import static org.jsweet.JSweetConfig.TS_IDENTIFIER_FORBIDDEN_CHARS;
import static org.jsweet.JSweetConfig.TUPLE_CLASSES_PACKAGE;
import static org.jsweet.JSweetConfig.UNION_CLASS_NAME;
import static org.jsweet.JSweetConfig.UTIL_CLASSNAME;
import static org.jsweet.JSweetConfig.UTIL_PACKAGE;
import static org.jsweet.transpiler.util.Util.CONSTRUCTOR_METHOD_NAME;
import static org.jsweet.transpiler.util.Util.firstOrDefault;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.jsweet.JSweetConfig;
import org.jsweet.transpiler.JSweetContext.DefaultMethodEntry;
import org.jsweet.transpiler.JSweetContext.GlobalMethodInfos;
import org.jsweet.transpiler.OverloadScanner.Overload;
import org.jsweet.transpiler.OverloadScanner.OverloadMethodEntry;
import org.jsweet.transpiler.extension.PrinterAdapter;
import org.jsweet.transpiler.model.ExtendedElement;
import org.jsweet.transpiler.model.MethodInvocationElement;
import org.jsweet.transpiler.model.support.CompilationUnitElementSupport;
import org.jsweet.transpiler.model.support.NewArrayElementSupport;
import org.jsweet.transpiler.util.AbstractTreePrinter;
import org.jsweet.transpiler.util.JSDoc;
import org.jsweet.transpiler.util.Util;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.ArrayTypeTree;
import com.sun.source.tree.AssertTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.BreakTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ContinueTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.IntersectionTypeTree;
import com.sun.source.tree.LabeledStatementTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.tree.SynchronizedTree;
import com.sun.source.tree.ThrowTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.tree.WildcardTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
/**
* This is a TypeScript printer for translating the Java AST to a TypeScript
* program.
*
* @author Renaud Pawlak
* @author Louis Grignon
*/
public class Java2TypeScriptTranslator extends AbstractTreePrinter {
/**
* The name of the field where the parent class is stored in the generated
* TypeScript code.
*/
public static final String PARENT_CLASS_FIELD_NAME = "__parent";
/**
* The name of the field where the implemented interface names are stored in the
* generated TypeScript code (for <code>instanceof</code> operator).
*/
public static final String INTERFACES_FIELD_NAME = "__interfaces";
/**
* The suffix added to static field initialization methods (for Java semantics).
*/
public static final String STATIC_INITIALIZATION_SUFFIX = "_$LI$";
/**
* The name of the field where the class name is stored in the class
* constructor.
*/
public static final String CLASS_NAME_IN_CONSTRUCTOR = "__class";
/**
* A prefix/separator for anonymous classes.
*/
public static final String ANONYMOUS_PREFIX = "$";
/**
* A suffix for name of classes that wrap regular TypeScript enums.
*/
public static final String ENUM_WRAPPER_CLASS_SUFFIX = "_$WRAPPER";
/**
* The name of the variable that contains the enum wrapper instances.
*/
public static final String ENUM_WRAPPER_CLASS_WRAPPERS = "_$wrappers";
/**
* The field name for storing the enum's name.
*/
public static final String ENUM_WRAPPER_CLASS_NAME = "_$name";
/**
* The field name for storing the enum's ordinal.
*/
public static final String ENUM_WRAPPER_CLASS_ORDINAL = "_$ordinal";
/**
* The default keyword for declaring variables.
*/
public static final String VAR_DECL_KEYWORD = "let";
/**
* A regular expression for matching body markers in <code>@Replace</code>
* expression.
*/
public static final Pattern BODY_MARKER = Pattern.compile("\\{\\{\\s*body\\s*\\}\\}");
/**
* A regular expression for matching base indent markers in
* <code>@Replace</code> expression.
*/
public static final Pattern BASE_INDENT_MARKER = Pattern.compile("\\{\\{\\s*baseIndent\\s*\\}\\}");
/**
* A regular expression for matching indent markers in <code>@Replace</code>
* expression.
*/
public static final Pattern INDENT_MARKER = Pattern.compile("\\{\\{\\s*indent\\s*\\}\\}");
/**
* A regular expression for matching method name markers in
* <code>@Replace</code> expression.
*/
public static final Pattern METHOD_NAME_MARKER = Pattern.compile("\\{\\{\\s*methodName\\s*\\}\\}");
/**
* A regular expression for matching class name markers in <code>@Replace</code>
* expression.
*/
public static final Pattern CLASS_NAME_MARKER = Pattern.compile("\\{\\{\\s*className\\s*\\}\\}");
/**
* A prefix for generators.
*/
public static final String GENERATOR_PREFIX = "__generator_";
/**
* A logger for internal messages.
*/
protected static Logger logger = Logger.getLogger(Java2TypeScriptTranslator.class);
/**
* A state flag indicating the comparison mode to be used by this printer for
* printing comparison operators.
*
* @author Renaud Pawlak
*/
public static enum ComparisonMode {
/**
* Forces the strict comparison operators (===, >==, <==), even for null
* literals.
*/
FORCE_STRICT,
/**
* Uses the strict comparison operators (===, >==, <==), except for null
* literals, where loose operators are used to match better the Java semantics.
* This is the default behavior.
*/
STRICT,
/**
* Uses the loose comparison operators (==, >=, <=).
*/
LOOSE;
}
private final Stack<ComparisonMode> comparisonModeStack = new Stack<>();
/**
* Selects a comparison mode for subsequently printed comparison operators.
*
* @see #exitComparisonMode()
*/
public void enterComparisonMode(ComparisonMode comparisonMode) {
comparisonModeStack.push(comparisonMode);
}
/**
* Exits a comparison mode and go back to the previous one.
*
* @see #enterComparisonMode(ComparisonMode)
*/
public void exitComparisonMode() {
comparisonModeStack.pop();
}
private ComparisonMode getComparisonMode() {
if (comparisonModeStack.isEmpty()) {
return ComparisonMode.STRICT;
} else {
if (comparisonModeStack.peek() == ComparisonMode.STRICT) {
return ComparisonMode.FORCE_STRICT;
} else {
return ComparisonMode.LOOSE;
}
}
}
public static class ClassScope {
private String name;
private MethodTree mainMethod;
private boolean interfaceScope = false;
private boolean enumScope = false;
private boolean isComplexEnum = false;
private boolean enumWrapperClassScope = false;
private boolean stringEnumScope = false;
private boolean removedSuperclass = false;
private boolean declareClassScope;
private boolean skipTypeAnnotations = false;
private boolean defaultMethodScope = false;
private boolean eraseVariableTypes = false;
private boolean hasDeclaredConstructor = false;
private boolean innerClass = false;
private boolean innerClassNotStatic = false;
private boolean hasInnerClass = false;
private List<ClassTree> anonymousClasses = new ArrayList<>();
private List<NewClassTree> anonymousClassesConstructors = new ArrayList<>();
private List<LinkedHashSet<VariableElement>> finalVariables = new ArrayList<>();
private boolean hasConstructorOverloadWithSuperClass;
private List<VariableTree> fieldsWithInitializers = new ArrayList<>();
private List<String> inlinedConstructorArgs = null;
private List<ClassTree> localClasses = new ArrayList<>();
private List<String> generatedMethodNames = new ArrayList<>();
// to be accessed in the parent scope
private boolean isAnonymousClass = false;
// to be accessed in the parent scope
private boolean isInnerClass = false;
// to be accessed in the parent scope
private boolean isLocalClass = false;
private boolean constructor = false;
private boolean decoratorScope = false;
public Stack<ForeachLoopScope> foreachLoopContext;
private final JSweetContext context;
private final CompilationUnitTree compilationUnit;
private ClassScope(JSweetContext context, CompilationUnitTree compilationUnit) {
this.context = context;
this.compilationUnit = compilationUnit;
}
public String getName() {
return name;
}
public MethodTree getMainMethod() {
return mainMethod;
}
public ExecutableElement getMainMethodElement() {
return Util.getElement(mainMethod);
}
public List<DeclaredType> getLocalClassesTypes() {
return getLocalClasses().stream() //
.map((ClassTree localClassTree) -> (DeclaredType) context.util.getType(localClassTree))
.collect(toList());
}
public boolean isLocalClassType(TypeMirror type) {
return getLocalClassesTypes().stream().anyMatch(localClassType -> localClassType.equals(type));
}
public boolean isInterfaceScope() {
return interfaceScope;
}
public boolean isEnumScope() {
return enumScope;
}
public boolean isComplexEnum() {
return isComplexEnum;
}
public boolean isEnumWrapperClassScope() {
return enumWrapperClassScope;
}
public boolean isRemovedSuperclass() {
return removedSuperclass;
}
public boolean isDeclareClassScope() {
return declareClassScope;
}
public boolean isSkipTypeAnnotations() {
return skipTypeAnnotations;
}
public boolean isDefaultMethodScope() {
return defaultMethodScope;
}
public boolean isEraseVariableTypes() {
return eraseVariableTypes;
}
public void setEraseVariableTypes(boolean eraseVariableTypes) {
this.eraseVariableTypes = eraseVariableTypes;
}
public boolean isHasDeclaredConstructor() {
return hasDeclaredConstructor;
}
public boolean getInnerClass() {
return innerClass;
}
public boolean isInnerClassNotStatic() {
return innerClassNotStatic;
}
public boolean isHasInnerClass() {
return hasInnerClass;
}
public List<ClassTree> getAnonymousClasses() {
return anonymousClasses;
}
public List<NewClassTree> getAnonymousClassesConstructors() {
return anonymousClassesConstructors;
}
public NewClassTree getAnonymousClassConstructorFromClassTree(ClassTree classTree) {
int anonymousClassIndex = anonymousClasses.indexOf(classTree);
if (anonymousClassIndex == -1) {
return null;
}
return anonymousClassesConstructors.get(anonymousClassIndex);
}
public List<LinkedHashSet<VariableElement>> getFinalVariables() {
return finalVariables;
}
public boolean isHasConstructorOverloadWithSuperClass() {
return hasConstructorOverloadWithSuperClass;
}
public List<VariableTree> getFieldsWithInitializers() {
return fieldsWithInitializers;
}
public List<String> getInlinedConstructorArgs() {
return inlinedConstructorArgs;
}
public List<ClassTree> getLocalClasses() {
return localClasses;
}
public List<String> getGeneratedMethodNames() {
return generatedMethodNames;
}
public boolean isAnonymousClass() {
return isAnonymousClass;
}
public boolean isInnerClass() {
return isInnerClass;
}
public boolean isLocalClass() {
return isLocalClass;
}
public boolean isConstructor() {
return constructor;
}
public boolean isDecoratorScope() {
return decoratorScope;
}
}
private static class ForeachLoopScope {
public EnhancedForLoopTree loop;
public String variableName;
public String arrayName;
public ForeachLoopScope(EnhancedForLoopTree loop) {
super();
this.loop = loop;
}
}
private Stack<ClassScope> scope = new Stack<>();
private boolean isAnnotationScope = false;
private boolean isDefinitionScope = false;
protected final boolean isTopLevelScope() {
return getIndent() == 0;
}
protected final ClassScope getScope() {
return scope.peek();
}
protected final ClassScope getScope(int i) {
return scope.get(scope.size() - 1 - i);
}
/**
* Enters a new class scope.
*
* @see #exitScope()
*/
public void enterScope() {
scope.push(new ClassScope(context, getCompilationUnit()));
}
/**
* Exits a class scope.
*
* @see #enterScope()
*/
public void exitScope() {
scope.pop();
}
/**
* Creates a new TypeScript translator.
*
* @param adapter an object that can tune various aspects of the
* TypeScript code generation
* @param logHandler the handler for logging and error reporting
* @param context the AST scanning context
* @param compilationUnit the compilation unit to be translated
* @param fillSourceMap if true, the printer generates the source maps, for
* debugging purpose
*/
public Java2TypeScriptTranslator(PrinterAdapter adapter, TranspilationHandler logHandler, JSweetContext context,
CompilationUnitTree compilationUnit, boolean fillSourceMap) {
super(logHandler, context, compilationUnit, adapter, fillSourceMap);
}
private static String mapConstructorType(String typeName) {
if (CONSTRUCTOR_TYPE_MAPPING.containsKey(typeName)) {
return CONSTRUCTOR_TYPE_MAPPING.get(typeName);
} else {
return typeName;
}
}
public static final Map<String, String> TYPE_MAPPING;
static {
Map<String, String> mapping = new HashMap<>();
mapping.put("java.lang.String", "String");
mapping.put("java.lang.Number", "Number");
mapping.put("java.lang.Integer", "Number");
mapping.put("java.lang.Float", "Number");
mapping.put("java.lang.Double", "Number");
mapping.put("java.lang.Short", "Number");
mapping.put("java.lang.Character", "String");
mapping.put("java.lang.Byte", "Number");
mapping.put("java.lang.Boolean", "Boolean");
mapping.put("java.lang.Long", "Number");
mapping.put("int", "Number");
mapping.put("float", "Number");
mapping.put("double", "Number");
mapping.put("short", "Number");
mapping.put("char", "String");
mapping.put("boolean", "Boolean");
mapping.put("byte", "Number");
mapping.put("long", "Number");
TYPE_MAPPING = Collections.unmodifiableMap(mapping);
}
private static final Map<String, String> CONSTRUCTOR_TYPE_MAPPING;
static {
Map<String, String> mapping = new HashMap<>();
mapping.put("string", "String");
mapping.put("number", "Number");
mapping.put("boolean", "Boolean");
mapping.put("any", "Object");
CONSTRUCTOR_TYPE_MAPPING = Collections.unmodifiableMap(mapping);
}
private PackageElement topLevelPackage;
public void useModule(ModuleImportDescriptor moduleImport) {
if (moduleImport != null) {
useModule(false, moduleImport.isDirect(), moduleImport.getTargetPackage(), null,
moduleImport.getImportedName(), moduleImport.getPathToImportedClass(), null);
}
}
private void useModule(boolean require, boolean direct, PackageElement targetPackage, Tree sourceTree,
String targetName, String moduleName, Element sourceElement) {
// avoid imports for names of types that are declared in this file
for (Tree t : getCompilationUnit().getTypeDecls()) {
if (t instanceof ClassTree) {
if (targetName.equals( Util.getElement(((ClassTree)t)).getSimpleName().toString())) {
return;
}
}
}
if (context.useModules && targetPackage != null) {
context.packageDependencies.add((PackageElement) targetPackage);
PackageElement packageElement = Util.getElement(compilationUnit.getPackage());
context.packageDependencies.add(packageElement);
context.packageDependencies.addEdge(packageElement, (PackageElement) targetPackage);
}
context.registerUsedModule(moduleName);
Set<String> importedNames = context.getImportedNames(compilationUnit.getSourceFile().getName());
if (!importedNames.contains(targetName)) {
if (context.useModules) {
// TODO: when using several qualified Globals classes, we need
// to disambiguate (Globals__1, Globals__2, ....)
// TODO: IDEA FOR MODULES AND FULLY QUALIFIED NAMES
// when using a fully qualified name in the code, we need an
// import, which can be named after something like
// qualName.replace(".", "_")... this would work in the general
// case...
if (context.isExcludedSourcePath(util().getSourceFilePath(sourceElement))) {
// ignore excluded source files
return;
}
if (sourceElement instanceof TypeElement
&& context.hasAnnotationType(sourceElement, JSweetConfig.ANNOTATION_DECORATOR)) {
context.forceTopImports();
}
if (!context.moduleBundleMode && sourceElement instanceof TypeElement
&& util().isSourceElement(sourceElement)
&& !(sourceElement instanceof TypeElement && context.referenceAnalyzer != null
&& context.referenceAnalyzer.isDependent(compilationUnit,
(TypeElement) sourceElement))) {
// import as footer statements to avoid cyclic dependencies
// as much as possible
// note that the better way to avoid cyclic dependency
// issues is to create bundles
context.addTopFooterStatement("import." + targetName,
"import { " + targetName + " } from '" + moduleName + "';\n");
} else {
if (direct) {
context.addHeader("import." + targetName, "import " + targetName + " = " + moduleName + ";\n");
} else {
boolean fullImport = require || GLOBALS_CLASS_NAME.equals(targetName);
if (fullImport) {
if (context.useRequireForModules) {
context.addHeader("import." + targetName, "import " + targetName + " = require("
+ getStringLiteralQuote() + moduleName + getStringLiteralQuote() + ");\n");
} else {
context.addHeader("import." + targetName,
"import * as " + targetName + " from '" + moduleName + "';\n");
}
} else {
context.addHeader("import." + targetName,
"import { " + targetName + " } from '" + moduleName + "';\n");
}
}
}
}
context.registerImportedName(compilationUnit.getSourceFile().getName(), sourceElement, targetName);
}
}
private boolean checkRootPackageParent(CompilationUnitTree topLevel, PackageElement rootPackage,
PackageElement parentPackage) {
if (parentPackage == null) {
return true;
}
if (!context.options.isNoRootDirectories() || context.options.isBundle()) {
return true;
}
if (context.isRootPackage(parentPackage)) {
report(topLevel.getPackageName(), JSweetProblem.ENCLOSED_ROOT_PACKAGES,
rootPackage.getQualifiedName().toString(), parentPackage.getQualifiedName().toString());
return false;
}
for (Element s : parentPackage.getEnclosedElements()) {
if (s instanceof TypeElement) {
if (util().isSourceElement(s)) {
report(topLevel.getPackageName(), JSweetProblem.CLASS_OUT_OF_ROOT_PACKAGE_SCOPE,
util().getQualifiedName(s), rootPackage.getQualifiedName().toString());
return false;
}
}
}
return checkRootPackageParent(topLevel, rootPackage, util().getParentPackage(parentPackage));
}
private ModuleImportDescriptor getModuleImportDescriptor(String importedName, TypeElement importedClass) {
return getAdapter().getModuleImportDescriptor(createExtendedElement(compilationUnit), importedName,
importedClass);
}
private boolean isMappedOrErasedType(Element typeElement) {
return context.isMappedType(util().getQualifiedName(typeElement))
|| context.hasAnnotationType(typeElement, JSweetConfig.ANNOTATION_ERASED);
}
/**
* Ensures that the module that corresponds to the given element is used
* (imported).
*/
public void ensureModuleIsUsed(Element element) {
if (context.useModules) {
if (element instanceof TypeElement) {
ModuleImportDescriptor moduleImport = getAdapter().getModuleImportDescriptor(
getCompilationUnitElement(), element.getSimpleName().toString(), (TypeElement) element);
if (moduleImport != null) {
useModule(moduleImport);
}
}
}
}
/**
* Prints a compilation unit tree.
*/
@Override
public Void visitCompilationUnit(final CompilationUnitTree compilationUnit, final Trees trees) {
PackageElement packageElement = Util.getElement(compilationUnit.getPackage());
if (context.isPackageErased(packageElement)) {
return returnNothing();
}
String packageFullName = util().getPackageFullNameForCompilationUnit(compilationUnit);
isDefinitionScope = packageFullName.startsWith(JSweetConfig.LIBS_PACKAGE + ".");
if (packageElement != null && context.hasAnnotationType(packageElement, JSweetConfig.ANNOTATION_MODULE)) {
context.addExportedElement(
context.getAnnotationValue(packageElement, JSweetConfig.ANNOTATION_MODULE, String.class, null),
packageElement, getCompilationUnit());
}
PackageElement rootPackage = context.getFirstEnclosingRootPackage(packageElement);
if (rootPackage != null) {
if (!checkRootPackageParent(compilationUnit, rootPackage,
util().getParentPackage((PackageElement) rootPackage))) {
return returnNothing();
}
}
context.importedTopPackages.clear();
context.rootPackages.add(rootPackage);
topLevelPackage = context.getTopLevelPackage(packageElement);
if (topLevelPackage != null) {
context.topLevelPackageNames.add(topLevelPackage.getQualifiedName().toString());
}
footer.delete(0, footer.length());
setCompilationUnit(compilationUnit);
getAdapter().beforeCompilationUnit();
boolean globalModule = JSweetConfig.GLOBALS_PACKAGE_NAME.equals(packageFullName)
|| packageFullName.endsWith("." + JSweetConfig.GLOBALS_PACKAGE_NAME);
String rootRelativePackageName = "";
if (!globalModule) {
rootRelativePackageName = getRootRelativeName(packageElement);
if (rootRelativePackageName.length() == 0) {
globalModule = true;
}
}
List<String> packageSegments = new ArrayList<String>(Arrays.asList(rootRelativePackageName.split("\\.")));
packageSegments.retainAll(JSweetConfig.TS_TOP_LEVEL_KEYWORDS);
if (!packageSegments.isEmpty()) {
report(compilationUnit.getPackageName(), JSweetProblem.PACKAGE_NAME_CONTAINS_KEYWORD, packageSegments);
}
detectAndUseImportedModules(compilationUnit);
detectAndUseModulesFromReferencedTypes(compilationUnit);
// require root modules when using fully qualified names or reserved
// keywords
new TreeScanner<Void, Trees>() {
Stack<Tree> stack = new Stack<>();
@Override
public Void scan(Tree tree, Trees trees) {
if (tree != null) {
stack.push(tree);
try {
super.scan(tree, trees);
} finally {
stack.pop();
}
}
return returnNothing();
}
@SuppressWarnings("unchecked")
public <T extends Tree> T getParent(Class<T> type) {
for (int i = this.stack.size() - 2; i >= 0; i--) {
if (type.isAssignableFrom(this.stack.get(i).getClass())) {
return (T) this.stack.get(i);
}
}
return null;
}
@Override
public Void visitIdentifier(final IdentifierTree identifier, final Trees trees) {
PackageElement compilationUnitPackageElement = Util.getElement(compilationUnit.getPackage());
Element identifierElement = Util.getElement(identifier);
if (identifierElement instanceof PackageElement) {
// ignore packages in imports
if (getParent(ImportTree.class) != null) {
return returnNothing();
}
boolean isSourceType = false;
for (int i = stack.size() - 2; i >= 0; i--) {
Tree tree = stack.get(i);
if (!(tree instanceof MemberSelectTree)) {
break;
} else {
MemberSelectTree selectTree = (MemberSelectTree) tree;
Element selectElement = Util.getElement(selectTree);
if ((selectElement instanceof TypeElement) && util().isSourceElement(selectElement)) {
isSourceType = true;
break;
}
}
}
if (!isSourceType) {
return returnNothing();
}
PackageElement identifierPackage = (PackageElement) identifierElement;
String pathToModulePackage = util().getRelativePath(compilationUnitPackageElement,
identifierPackage);
if (pathToModulePackage == null) {
return returnNothing();
}
File moduleFile = new File(new File(pathToModulePackage), JSweetConfig.MODULE_FILE_NAME);
if (!identifierPackage.getSimpleName().toString()
.equals(compilationUnitPackageElement.getSimpleName().toString())) {
useModule(false, false, identifierPackage, identifier,
identifierPackage.getSimpleName().toString(), moduleFile.getPath().replace('\\', '/'),
null);
}
} else if (identifierElement instanceof TypeElement) {
if (JSweetConfig.GLOBALS_PACKAGE_NAME
.equals(identifierElement.getEnclosingElement().getSimpleName().toString())) {
String pathToModulePackage = util().getRelativePath(compilationUnitPackageElement,
identifierElement.getEnclosingElement());
if (pathToModulePackage == null) {
return returnNothing();
}
File moduleFile = new File(new File(pathToModulePackage), JSweetConfig.MODULE_FILE_NAME);
if (!identifierElement.getEnclosingElement().getSimpleName().toString()
.equals(compilationUnitPackageElement.getSimpleName().toString())) {
useModule(false, false, (PackageElement) identifierElement.getEnclosingElement(),
identifier, JSweetConfig.GLOBALS_PACKAGE_NAME,
moduleFile.getPath().replace('\\', '/'), null);
}
}
}
return returnNothing();
}
@Override
public Void visitMethodInvocation(final MethodInvocationTree invocation, final Trees trees) {
PackageElement compilationUnitPackageElement = Util.getElement(compilationUnit.getPackage());
// TODO: same for static variables
if (invocation.getMethodSelect() instanceof IdentifierTree && JSweetConfig.TS_STRICT_MODE_KEYWORDS
.contains(invocation.getMethodSelect().toString().toLowerCase())) {
Element invokedMethodElement = Util.getElement((IdentifierTree) invocation.getMethodSelect());
PackageElement invocationPackage = util().getParentElement(invokedMethodElement,
PackageElement.class);
String rootRelativeInvocationPackageName = getRootRelativeName(invocationPackage);
if (rootRelativeInvocationPackageName.indexOf('.') == -1) {
return super.visitMethodInvocation(invocation, trees);
}
String targetRootPackageName = rootRelativeInvocationPackageName.substring(0,
rootRelativeInvocationPackageName.indexOf('.'));
String pathToReachRootPackage = util().getRelativePath(
"/" + compilationUnitPackageElement.getQualifiedName().toString().replace('.', '/'),
"/" + targetRootPackageName);
if (pathToReachRootPackage == null) {
return super.visitMethodInvocation(invocation, trees);
}
File moduleFile = new File(new File(pathToReachRootPackage), JSweetConfig.MODULE_FILE_NAME);
if (!invocationPackage.toString()
.equals(compilationUnitPackageElement.getSimpleName().toString())) {
useModule(false, false, invocationPackage, invocation, targetRootPackageName,
moduleFile.getPath().replace('\\', '/'), null);
}
}
return super.visitMethodInvocation(invocation, trees);
}
};
// TODO: change the way qualified names are handled (because of new
// module organization)
// inlinedModuleScanner.scan(compilationUnit);
if (!globalModule && !context.useModules) {
printIndent();
if (isDefinitionScope) {
print("declare ");
} else if (context.moduleBundleMode) {
print("export ");
}
print("namespace ").print(rootRelativePackageName).print(" {").startIndent().println();
}
for (ImportTree def : compilationUnit.getImports()) {
print(def);
}
for (ClassTree def : util().getSortedClassDeclarations(compilationUnit.getTypeDecls(), compilationUnit)) {
printIndent();
int pos = getCurrentPosition();
print(def);
if (getCurrentPosition() == pos) {
removeLastIndent();
continue;
}
println().println();
}
if (!globalModule && !context.useModules) {
removeLastChar().endIndent().printIndent().print("}").println();
}
if (footer.length() > 0) {
println().print(footer.toString());
}
globalModule = false;
return returnNothing();
}
private void detectAndUseModulesFromReferencedTypes(CompilationUnitTree compilationUnit) {
if (context.useModules) {
new UsedTypesScanner().scan(compilationUnit, context.trees);
}
}
private void detectAndUseImportedModules(CompilationUnitTree compilationUnit) {
// generate requires by looking up imported external modules
for (ImportTree importDecl : compilationUnit.getImports()) {
TreeScanner<Void, Trees> importedModulesScanner = new TreeScanner<>() {
@Override
public Void scan(Tree tree, Trees trees) {
if (tree instanceof MemberSelectTree) {
MemberSelectTree qualified = (MemberSelectTree) tree;
Element memberSelectElement = Util.getElement(tree);
if (memberSelectElement != null) {
// regular import case (qualified.sym is a package)
if (context.hasAnnotationType(memberSelectElement, JSweetConfig.ANNOTATION_MODULE)) {
String targetName = createImportAliasFromFieldAccess(qualified);
String actualName = context.getAnnotationValue(memberSelectElement,
JSweetConfig.ANNOTATION_MODULE, String.class, null);
useModule(true, false, null, importDecl, targetName, actualName, memberSelectElement);
}
} else {
// static import case (imported fields and methods)
if (qualified.getExpression() instanceof MemberSelectTree) {
MemberSelectTree qualifier = (MemberSelectTree) qualified.getExpression();
Element subMemberSelectElement = Util.getElement(qualifier);
if (subMemberSelectElement != null) {
try {
for (Element importedMember : subMemberSelectElement.getEnclosedElements()) {
if (qualified.getIdentifier().equals(importedMember.getSimpleName())) {