-
Notifications
You must be signed in to change notification settings - Fork 36
/
AbstractTransformer.java
executable file
·3045 lines (2741 loc) · 136 KB
/
AbstractTransformer.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 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.codegen;
import static com.sun.tools.javac.code.Flags.FINAL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.antlr.runtime.Token;
import com.redhat.ceylon.ceylondoc.Util;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.compiler.java.codegen.Naming.DeclNameFlag;
import com.redhat.ceylon.compiler.java.loader.CeylonModelLoader;
import com.redhat.ceylon.compiler.java.loader.TypeFactory;
import com.redhat.ceylon.compiler.java.tools.CeylonLog;
import com.redhat.ceylon.compiler.loader.AbstractModelLoader;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.ModuleImport;
import com.redhat.ceylon.compiler.typechecker.model.NothingType;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Comprehension;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositionalArgument;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.Factory;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.LetExpr;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.util.Position.LineMap;
/**
* Base class for all delegating transformers
*/
public abstract class AbstractTransformer implements Transformation {
private Context context;
private TreeMaker make;
private Names names;
private Symtab syms;
private AbstractModelLoader loader;
private TypeFactory typeFact;
protected Log log;
final Naming naming;
public AbstractTransformer(Context context) {
this.context = context;
make = TreeMaker.instance(context);
names = Names.instance(context);
syms = Symtab.instance(context);
loader = CeylonModelLoader.instance(context);
typeFact = TypeFactory.instance(context);
log = CeylonLog.instance(context);
naming = Naming.instance(context);
}
Context getContext() {
return context;
}
@Override
public TreeMaker make() {
return make;
}
private static JavaPositionsRetriever javaPositionsRetriever = null;
public static void trackNodePositions(JavaPositionsRetriever positionsRetriever) {
javaPositionsRetriever = positionsRetriever;
}
@Override
public Factory at(Node node) {
if (node == null) {
make.at(Position.NOPOS);
}
else {
Token token = node.getToken();
if (token != null) {
int tokenStartPosition = getMap().getStartPosition(token.getLine()) + token.getCharPositionInLine();
make().at(tokenStartPosition);
if (javaPositionsRetriever != null) {
javaPositionsRetriever.addCeylonNode(tokenStartPosition, node);
}
}
}
return make();
}
@Override
public Symtab syms() {
return syms;
}
@Override
public Names names() {
return names;
}
@Override
public AbstractModelLoader loader() {
return loader;
}
@Override
public TypeFactory typeFact() {
return typeFact;
}
void setMap(LineMap map) {
gen().setMap(map);
}
LineMap getMap() {
return gen().getMap();
}
@Override
public CeylonTransformer gen() {
return CeylonTransformer.getInstance(context);
}
@Override
public ExpressionTransformer expressionGen() {
return ExpressionTransformer.getInstance(context);
}
@Override
public StatementTransformer statementGen() {
return StatementTransformer.getInstance(context);
}
@Override
public ClassTransformer classGen() {
return ClassTransformer.getInstance(context);
}
/**
* Makes an <strong>unquoted</strong> simple identifier
* @param ident The identifier
* @return The ident
*/
JCExpression makeUnquotedIdent(String ident) {
return naming.makeUnquotedIdent(ident);
}
/**
* Makes an <strong>quoted</strong> simple identifier
* @param ident The identifier
* @return The ident
*/
JCIdent makeQuotedIdent(String ident) {
// TODO Only 3 callers
return naming.makeQuotedIdent(ident);
}
/**
* Makes a <strong>quoted</strong> qualified (compound) identifier from
* the given qualified name. Each part of the name will be
* quoted if it is a Java keyword.
* @param qualifiedName The qualified name
*/
JCExpression makeQuotedQualIdentFromString(String qualifiedName) {
return naming.makeQuotedQualIdentFromString(qualifiedName);
}
/**
* Makes an <strong>unquoted</strong> qualified (compound) identifier
* from the given qualified name components
* @param expr A starting expression (may be null)
* @param names The components of the name (may be null)
* @see #makeQuotedQualIdentFromString(String)
*/
JCExpression makeQualIdent(JCExpression expr, String name) {
return naming.makeQualIdent(expr, name);
}
JCExpression makeQuotedQualIdent(JCExpression expr, String... names) {
// TODO Remove this method: Only 1 caller
return naming.makeQuotedQualIdent(expr, names);
}
JCExpression makeQuotedFQIdent(String qualifiedName) {
// TODO Remove this method??: Only 2 callers
return naming.makeQuotedFQIdent(qualifiedName);
}
JCExpression makeIdent(Type type) {
return naming.makeIdent(type);
}
/**
* Makes a <strong>unquoted</strong> field access
* @param s1 The base expression
* @param s2 The field to access
* @return The field access
*/
JCFieldAccess makeSelect(JCExpression s1, String s2) {
return naming.makeSelect(s1, s2);
}
/**
* Makes a <strong>unquoted</strong> field access
* @param s1 The base expression
* @param s2 The field to access
* @return The field access
*/
JCFieldAccess makeSelect(String s1, String s2) {
return naming.makeSelect(s1, s2);
}
JCLiteral makeNull() {
return make().Literal(TypeTags.BOT, null);
}
JCExpression makeInteger(int i) {
return make().Literal(Integer.valueOf(i));
}
JCExpression makeLong(long i) {
return make().Literal(Long.valueOf(i));
}
/** Makes a boxed Ceylon String */
JCExpression makeCeylonString(String s) {
return boxString(make().Literal(s));
}
JCExpression makeBoolean(boolean b) {
JCExpression expr;
if (b) {
expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(1));
} else {
expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(0));
}
return expr;
}
// Creates a "foo foo = new foo();"
JCTree.JCVariableDecl makeLocalIdentityInstance(String varName, String className, boolean isShared) {
return makeLocalIdentityInstance(varName, className, isShared, null);
}
// Creates a "foo foo = new foo(parameter);"
JCTree.JCVariableDecl makeLocalIdentityInstance(String varName, String className, boolean isShared, JCTree.JCExpression parameter) {
JCExpression name = makeQuotedIdent(className);
JCExpression initValue = makeNewClass(className, false, parameter);
int modifiers = isShared ? 0 : FINAL;
JCTree.JCVariableDecl var = make().VarDef(
make().Modifiers(modifiers),
names().fromString(varName),
name,
initValue);
return var;
}
// Creates a "new foo();"
JCTree.JCNewClass makeNewClass(String className, boolean fullyQualified, JCTree.JCExpression parameter) {
JCExpression name = fullyQualified ? naming.makeQuotedFQIdent(className) : makeQuotedQualIdentFromString(className);
List<JCTree.JCExpression> params = parameter != null ? List.of(parameter) : List.<JCTree.JCExpression>nil();
return makeNewClass(name, params);
}
/** Creates a "new foo();" */
JCTree.JCNewClass makeSyntheticInstance(Declaration decl) {
JCExpression clazz = naming.makeSyntheticClassname(decl);
return makeNewClass(clazz, List.<JCTree.JCExpression>nil());
}
JCTree.JCNewClass makeNewClass(JCExpression clazz) {
return makeNewClass(clazz, null);
}
// Creates a "new foo(arg1, arg2, ...);"
JCTree.JCNewClass makeNewClass(JCExpression clazz, List<JCTree.JCExpression> args) {
if (args == null) {
args = List.<JCTree.JCExpression>nil();
}
return make().NewClass(null, null, clazz, args, null);
}
JCBlock makeGetterBlock(TypedDeclaration declarationModel,
final Tree.Block block,
final Tree.SpecifierOrInitializerExpression expression) {
List<JCStatement> stats;
if (block != null) {
stats = statementGen().transformStmts(block.getStatements());
} else {
BoxingStrategy boxing = CodegenUtil.getBoxingStrategy(declarationModel);
ProducedType type = declarationModel.getType();
JCExpression transExpr = expressionGen().transformExpression(expression.getExpression(), boxing, type);
stats = List.<JCStatement>of(make().Return(transExpr));
}
JCBlock getterBlock = make().Block(0, stats);
return getterBlock;
}
JCBlock makeSetterBlock(TypedDeclaration declarationModel,
final Tree.Block block,
final Tree.SpecifierOrInitializerExpression expression) {
List<JCStatement> stats;
if (block != null) {
stats = statementGen().transformStmts(block.getStatements());
} else {
ProducedType type = declarationModel.getType();
JCExpression transExpr = expressionGen().transformExpression(expression.getExpression(), BoxingStrategy.INDIFFERENT, type);
stats = List.<JCStatement>of(make().Exec(transExpr));
}
JCBlock setterBlock = make().Block(0, stats);
return setterBlock;
}
JCVariableDecl makeVar(long mods, String varName, JCExpression typeExpr, JCExpression valueExpr) {
return make().VarDef(make().Modifiers(mods), names().fromString(varName), typeExpr, valueExpr);
}
JCVariableDecl makeVar(String varName, JCExpression typeExpr, JCExpression valueExpr) {
return makeVar(0, varName, typeExpr, valueExpr);
}
JCVariableDecl makeVar(Naming.SyntheticName varName, JCExpression typeExpr, JCExpression valueExpr) {
return makeVar(0L, varName, typeExpr, valueExpr);
}
JCVariableDecl makeVar(long mods, Naming.SyntheticName varName, JCExpression typeExpr, JCExpression valueExpr) {
return make().VarDef(make().Modifiers(mods), varName.asName(), typeExpr, valueExpr);
}
/**
* Creates a {@code ( let var1=expr1,var2=expr2,...,varN=exprN in varN; )}
* or a {@code ( let var1=expr1,var2=expr2,...,varN=exprN,exprO in exprO; )}
* @param args
* @return
*/
JCExpression makeLetExpr(JCExpression... args) {
return makeLetExpr(naming.temp(), null, args);
}
/** Creates a
* {@code ( let var1=expr1,var2=expr2,...,varN=exprN in statements; varN; )}
* or a {@code ( let var1=expr1,var2=expr2,...,varN=exprN in statements; exprO; )}
*
*/
JCExpression makeLetExpr(Naming.SyntheticName varBaseName, List<JCStatement> statements, JCExpression... args) {
return makeLetExpr(varBaseName.getName(), statements, args);
}
private JCExpression makeLetExpr(String varBaseName, List<JCStatement> statements, JCExpression... args) {
String varName = null;
ListBuffer<JCStatement> decls = ListBuffer.lb();
int i;
for (i = 0; (i + 1) < args.length; i += 2) {
JCExpression typeExpr = args[i];
JCExpression valueExpr = args[i+1];
varName = varBaseName + ((args.length > 3) ? "$" + i : "");
JCVariableDecl varDecl = makeVar(varName, typeExpr, valueExpr);
decls.append(varDecl);
}
JCExpression result;
if (i == args.length) {
result = makeUnquotedIdent(varName);
} else {
result = args[i];
}
if (statements != null) {
decls.appendList(statements);
}
return make().LetExpr(decls.toList(), result);
}
/*
* Type handling
*/
boolean isBooleanTrue(Declaration decl) {
return decl == typeFact.getBooleanTrueDeclaration();
}
boolean isBooleanFalse(Declaration decl) {
return decl == typeFact.getBooleanFalseDeclaration();
}
/**
* Determines whether the given type is optional.
*/
boolean isOptional(ProducedType type) {
// Note we don't use typeFact().isOptionalType(type) because
// that implements a stricter test used in the type checker.
return typeFact().getNullValueDeclaration().getType().isSubtypeOf(type);
}
boolean isNull(ProducedType type) {
return type.getSupertype(typeFact.getNullDeclaration()) != null;
}
boolean isNullValue(ProducedType type) {
return type.getSupertype(typeFact.getNullValueDeclaration().getTypeDeclaration()) != null;
}
public static boolean isAnything(ProducedType type) {
return CodegenUtil.isVoid(type);
}
private boolean isObject(ProducedType type) {
return typeFact.getObjectDeclaration().getType().isExactly(type);
}
public boolean isAlias(ProducedType type) {
return type.getDeclaration().isAlias() || typeFact.getDefiniteType(type).getDeclaration().isAlias();
}
ProducedType simplifyType(ProducedType orgType) {
if(orgType == null)
return null;
ProducedType type = orgType.resolveAliases();
if (isOptional(type)) {
// For an optional type T?:
// - The Ceylon type T? results in the Java type T
type = typeFact().getDefiniteType(type);
if (type.getUnderlyingType() != null) {
// A definite type should not have its underlyingType set so we make a copy
type = type.withoutUnderlyingType();
}
}
TypeDeclaration tdecl = type.getDeclaration();
if (tdecl instanceof UnionType && tdecl.getCaseTypes().size() == 1) {
// Special case when the Union contains only a single CaseType
// FIXME This is not correct! We might lose information about type arguments!
type = tdecl.getCaseTypes().get(0);
} else if (tdecl instanceof IntersectionType) {
java.util.List<ProducedType> satisfiedTypes = tdecl.getSatisfiedTypes();
if (satisfiedTypes.size() == 1) {
// Special case when the Intersection contains only a single SatisfiedType
// FIXME This is not correct! We might lose information about type arguments!
type = satisfiedTypes.get(0);
} else if (satisfiedTypes.size() == 2) {
// special case for T? simplified as T&Object
if (isTypeParameter(satisfiedTypes.get(0)) && isObject(satisfiedTypes.get(1))) {
type = satisfiedTypes.get(0);
}
}
}
return type;
}
ProducedTypedReference getTypedReference(TypedDeclaration decl){
if(decl.getContainer() instanceof TypeDeclaration){
TypeDeclaration containerDecl = (TypeDeclaration) decl.getContainer();
return containerDecl.getType().getTypedMember(decl, Collections.<ProducedType>emptyList());
}
return decl.getProducedTypedReference(null, Collections.<ProducedType>emptyList());
}
ProducedTypedReference nonWideningTypeDecl(ProducedTypedReference typedReference) {
ProducedTypedReference refinedTypedReference = getRefinedDeclaration(typedReference);
if(refinedTypedReference != null){
/*
* We are widening if the type:
* - is not object
* - is erased to object
* - refines a declaration that is not erased to object
*/
ProducedType declType = typedReference.getType();
ProducedType refinedDeclType = refinedTypedReference.getType();
if(declType == null || refinedDeclType == null)
return typedReference;
boolean isWidening = isWidening(declType, refinedDeclType);
if(!isWidening){
// make sure we get the instantiated refined decl
if(refinedDeclType.getDeclaration() instanceof TypeParameter
&& !(declType.getDeclaration() instanceof TypeParameter))
refinedDeclType = nonWideningType(typedReference, refinedTypedReference);
isWidening = isWideningTypeArguments(declType, refinedDeclType, true);
}
if(isWidening)
return refinedTypedReference;
}
return typedReference;
}
/*
* We have several special cases here to find the best non-widening refinement in case of multiple inheritace:
*
* - The first special case is for some decls like None.first, which inherits from ContainerWithFirstElement
* twice: once with Nothing (erased to j.l.Object) and once with Element (a type param). Now, in order to not widen the
* return type it can't be Nothing (j.l.Object), it must be Element (a type param that is not instantiated), because in Java
* a type param refines j.l.Object but not the other way around.
* - The second special case is when implementing an interface first with a non-erased type, then with an erased type. In this
* case we want the refined decl to be the one with the non-erased type.
* - The third special case is when we implement a declaration via multiple super types, without having any refining
* declarations in those supertypes, simply by instantiating a common super type with different type parameters
*/
private ProducedTypedReference getRefinedDeclaration(ProducedTypedReference typedReference) {
TypedDeclaration decl = typedReference.getDeclaration();
TypedDeclaration modelRefinedDecl = (TypedDeclaration)decl.getRefinedDeclaration();
// quick exit
if(decl == modelRefinedDecl)
return null;
if(decl.getContainer() instanceof ClassOrInterface){
// only try to find better if we're erasing to Object and we're not returning a type param
if(willEraseToObject(typedReference.getType())
|| isWideningTypeArguments(decl.getType(), modelRefinedDecl.getType(), true)
&& !isTypeParameter(typedReference.getType())){
ClassOrInterface declaringType = (ClassOrInterface) decl.getContainer();
Set<TypedDeclaration> refinedMembers = getRefinedMembers(declaringType, decl.getName(),
com.redhat.ceylon.compiler.typechecker.model.Util.getSignature(decl), false);
// now we must select a different refined declaration if we refine it more than once
if(refinedMembers.size() > 1){
// first case
for(TypedDeclaration refinedDecl : refinedMembers){
// get the type reference to see if any eventual type param is instantiated in our inheritance of this type/method
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(typedReference, refinedDecl);
// if it is not instantiated, that's the one we're looking for
if(isTypeParameter(refinedTypedReference.getType()))
return refinedTypedReference;
}
// second case
for(TypedDeclaration refinedDecl : refinedMembers){
// get the type reference to see if any eventual type param is instantiated in our inheritance of this type/method
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(typedReference, refinedDecl);
// if we're not erasing this one to Object let's select it
if(!willEraseToObject(refinedTypedReference.getType()) && !isWideningTypeArguments(refinedDecl.getType(), modelRefinedDecl.getType(), true))
return refinedTypedReference;
}
// third case
if(isTypeParameter(modelRefinedDecl.getType())){
// it can happen that we have inherited a method twice from a single refined declaration
// via different supertype instantiations, without having ever refined them in supertypes
// so we try each super type to see if we already have a matching typed reference
// first super type
ProducedType extendedType = declaringType.getExtendedType();
if(extendedType != null){
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(extendedType, modelRefinedDecl);
ProducedType refinedType = refinedTypedReference.getType();
if(!isTypeParameter(refinedType)
&& !willEraseToObject(refinedType))
return refinedTypedReference;
}
// then satisfied interfaces
for(ProducedType satisfiedType : declaringType.getSatisfiedTypes()){
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(satisfiedType, modelRefinedDecl);
ProducedType refinedType = refinedTypedReference.getType();
if(!isTypeParameter(refinedType)
&& !willEraseToObject(refinedType))
return refinedTypedReference;
}
}
}
}
}
return getRefinedTypedReference(typedReference, modelRefinedDecl);
}
// Finds all member declarations (original and refinements) with the
// given name and signature within the given type and it's super
// classes and interfaces
public Set<TypedDeclaration> getRefinedMembers(TypeDeclaration decl,
String name,
java.util.List<ProducedType> signature, boolean ellipsis) {
Set<TypedDeclaration> ret = new HashSet<TypedDeclaration>();
collectRefinedMembers(decl, name, signature, ellipsis,
new HashSet<TypeDeclaration>(), ret);
return ret;
}
private void collectRefinedMembers(TypeDeclaration decl, String name,
java.util.List<ProducedType> signature, boolean ellipsis,
java.util.Set<TypeDeclaration> visited, Set<TypedDeclaration> ret) {
if (visited.contains(decl)) {
return;
}
else {
visited.add(decl);
TypeDeclaration et = decl.getExtendedTypeDeclaration();
if (et!=null) {
collectRefinedMembers(et, name, signature, ellipsis, visited, ret);
}
for (TypeDeclaration st: decl.getSatisfiedTypeDeclarations()) {
collectRefinedMembers(st, name, signature, ellipsis, visited, ret);
}
Declaration found = decl.getDirectMember(name, signature, ellipsis);
if(found != null)
ret.add((TypedDeclaration) found);
}
}
private ProducedTypedReference getRefinedTypedReference(ProducedTypedReference typedReference,
TypedDeclaration refinedDeclaration) {
return getRefinedTypedReference(typedReference.getQualifyingType(), refinedDeclaration);
}
private ProducedTypedReference getRefinedTypedReference(ProducedType qualifyingType,
TypedDeclaration refinedDeclaration) {
TypeDeclaration refinedContainer = (TypeDeclaration)refinedDeclaration.getContainer();
ProducedType refinedContainerType = qualifyingType.getSupertype(refinedContainer);
return refinedDeclaration.getProducedTypedReference(refinedContainerType, Collections.<ProducedType>emptyList());
}
public boolean isWidening(ProducedType declType, ProducedType refinedDeclType) {
return !sameTypeForCeylonTypes(syms().ceylonObjectType, declType)
&& willEraseToObject(declType)
&& !willEraseToObject(refinedDeclType);
}
private boolean isWideningTypeArguments(ProducedType declType, ProducedType refinedDeclType, boolean allowSubtypes) {
if(declType == null || refinedDeclType == null)
return false;
// make sure we work on simplified types, to avoid stuff like optional or size-1 unions
declType = simplifyType(declType);
refinedDeclType = simplifyType(refinedDeclType);
// special case for type parameters
if(declType.getDeclaration() instanceof TypeParameter
&& refinedDeclType.getDeclaration() instanceof TypeParameter){
// consider them equivalent if they have the same bounds
TypeParameter tp = (TypeParameter) declType.getDeclaration();
TypeParameter refinedTP = (TypeParameter) refinedDeclType.getDeclaration();
if(haveSameBounds(tp, refinedTP))
return false;
// if they don't have the same bounds and we don't allow subtypes then we're widening
if(!allowSubtypes)
return false;
// if we allow subtypes, we're widening if tp is not a subtype of refinedTP
return !tp.getType().isSubtypeOf(refinedTP.getType());
}
if(allowSubtypes){
// if we don't erase to object and we refine something that does, we can't possibly be widening
if((willEraseToObject(refinedDeclType) || willEraseToSequential(refinedDeclType))
&& !willEraseToObject(declType) && !willEraseToSequential(declType))
return false;
// if we have exactly the same type don't bother finding a common ancestor
if(!declType.isExactly(refinedDeclType)){
// check if we can form an informed decision
if(refinedDeclType.getDeclaration() == null)
return true;
// find the instantiation of the refined decl type in the decl type
// special case for optional types: let's find the definite type since
// in java they are equivalent
ProducedType definiteType = typeFact().getDefiniteType(refinedDeclType);
if(definiteType != null)
refinedDeclType = definiteType;
declType = declType.getSupertype(refinedDeclType.getDeclaration());
// could not find common type, we must be widening somehow
if(declType == null)
return true;
}
}
Map<TypeParameter, ProducedType> typeArguments = declType.getTypeArguments();
Map<TypeParameter, ProducedType> refinedTypeArguments = refinedDeclType.getTypeArguments();
for(Entry<TypeParameter, ProducedType> typeArgument : typeArguments.entrySet()){
ProducedType refinedTypeArgument = refinedTypeArguments.get(typeArgument.getKey());
if(refinedTypeArgument == null)
return true; // something fishy here
// check if the type arg is widening due to erasure
if(isWidening(typeArgument.getValue(), refinedTypeArgument))
return true;
// check if the type arg is a subtype, or if its type args are widening
if(isWideningTypeArguments(typeArgument.getValue(), refinedTypeArgument, false))
return true;
}
// so far so good
return false;
}
public boolean haveSameBounds(TypeParameter tp, TypeParameter refinedTP) {
java.util.List<ProducedType> satTP = tp.getSatisfiedTypes();
java.util.List<ProducedType> satRefinedTP = new LinkedList<ProducedType>();
satRefinedTP.addAll(refinedTP.getSatisfiedTypes());
// same number of bounds
if(satTP.size() != satRefinedTP.size())
return false;
// make sure all the bounds are the same
OUT:
for(ProducedType satisfiedType : satTP){
for(ProducedType refinedSatisfiedType : satRefinedTP){
// if we found it, remove it from the second list to not match it again
if(satisfiedType.isExactly(refinedSatisfiedType)){
satRefinedTP.remove(satRefinedTP);
continue OUT;
}
}
// not found
return false;
}
// all bounds are equal
return true;
}
ProducedType nonWideningType(ProducedTypedReference declaration, ProducedTypedReference refinedDeclaration){
final ProducedReference pr;
if (declaration == refinedDeclaration) {
pr = declaration;
} else {
ProducedType refinedType = refinedDeclaration.getType();
// if the refined type is a method TypeParam, use the original decl that will be more correct
if(refinedType.getDeclaration() instanceof TypeParameter
&& refinedType.getDeclaration().getContainer() instanceof Method){
pr = declaration;
} else {
pr = refinedType;
}
}
if (pr.getDeclaration() instanceof Functional
&& Decl.isMpl((Functional)pr.getDeclaration())) {
// Methods with MPL have a Callable return type, not the type of
// the innermost Callable.
return getReturnTypeOfCallable(pr.getFullType());
}
return pr.getType();
}
private ProducedType javacCeylonTypeToProducedType(com.sun.tools.javac.code.Type t) {
return loader().getType(getLanguageModule(), t.tsym.packge().getQualifiedName().toString(), t.tsym.getQualifiedName().toString(), null);
}
private boolean sameTypeForCeylonTypes(Type ceylonType, ProducedType otherType) {
return otherType != null && javacCeylonTypeToProducedType(ceylonType).isExactly(otherType);
}
/**
* Determines if a type will be erased to java.lang.Object once converted to Java
* @param type
* @return
*/
boolean willEraseToObject(ProducedType type) {
if(type == null)
return false;
type = simplifyType(type);
TypeDeclaration decl = type.getDeclaration();
// All the following types either are Object or erase to Object
if (decl == typeFact.getObjectDeclaration()
|| decl == typeFact.getIdentifiableDeclaration()
|| decl == typeFact.getBasicDeclaration()
|| decl == typeFact.getNullDeclaration()
|| decl == typeFact.getNullValueDeclaration().getTypeDeclaration()
|| decl == typeFact.getAnythingDeclaration()
|| decl instanceof NothingType) {
return true;
}
// Any Unions and Intersections erase to Object as well
// except for the ones that erase to Sequential
return ((decl instanceof UnionType || decl instanceof IntersectionType)
&& !typeFact().isSequentialType(type));
}
boolean willEraseToPrimitive(ProducedType type) {
return (isCeylonBoolean(type) || isCeylonInteger(type) || isCeylonFloat(type) || isCeylonCharacter(type));
}
boolean willEraseToException(ProducedType type) {
type = simplifyType(type);
return (sameTypeForCeylonTypes(syms().ceylonExceptionType, type));
}
boolean willEraseToSequential(ProducedType type) {
type = simplifyType(type);
TypeDeclaration decl = type.getDeclaration();
return (decl instanceof UnionType || decl instanceof IntersectionType)
&& typeFact().isSequentialType(type);
}
// keep in sync with MethodDefinitionBuilder.paramType()
public boolean willEraseToBestBounds(Parameter param) {
ProducedType type = param.getType();
if (typeFact().isUnion(type)
|| typeFact().isIntersection(type)) {
final TypeDeclaration refinedTypeDecl = ((TypedDeclaration)CodegenUtil.getTopmostRefinedDeclaration(param)).getType().getDeclaration();
if (refinedTypeDecl instanceof TypeParameter
&& !refinedTypeDecl.getSatisfiedTypes().isEmpty()) {
return true;
}
}
return false;
}
boolean hasErasure(ProducedType type) {
return hasErasureResolved(type.resolveAliases());
}
private boolean hasErasureResolved(ProducedType type) {
if(type == null)
return false;
TypeDeclaration declaration = type.getDeclaration();
if(declaration == null)
return false;
if(declaration instanceof UnionType){
UnionType ut = (UnionType) declaration;
java.util.List<ProducedType> caseTypes = ut.getCaseTypes();
// special case for optional types
if(caseTypes.size() == 2){
if(isOptional(caseTypes.get(0)))
return hasErasureResolved(caseTypes.get(1));
if(isOptional(caseTypes.get(1)))
return hasErasureResolved(caseTypes.get(0));
}
// must be erased
return true;
}
if(declaration instanceof IntersectionType){
IntersectionType ut = (IntersectionType) declaration;
java.util.List<ProducedType> satisfiedTypes = ut.getSatisfiedTypes();
// special case for non-optional types
if(satisfiedTypes.size() == 2){
if(isObject(satisfiedTypes.get(0)))
return hasErasureResolved(satisfiedTypes.get(1));
if(isObject(satisfiedTypes.get(1)))
return hasErasureResolved(satisfiedTypes.get(0));
}
// must be erased
return true;
}
// Note: we don't consider types like Anything, Null, Basic, Identifiable as erased because
// they can never be better than Object as far as Java is concerned
// FIXME: what about Nothing then?
// special case for Callable where we stop after the first type param
boolean isCallable = isCeylonCallable(type);
// now check its type parameters
for(ProducedType pt : type.getTypeArgumentList()){
if(hasErasureResolved(pt))
return true;
if(isCallable)
break;
}
// no erasure here
return false;
}
/**
* This method should do the same sort of logic as AbstractTransformer.makeTypeArgs to determine
* that the given type will be turned raw as a return type
*/
boolean isTurnedToRaw(ProducedType type){
return isTurnedToRawResolved(type.resolveAliases());
}
private boolean isTurnedToRawResolved(ProducedType type) {
// if we don't have type arguments we can't be raw
if(type.getTypeArguments().isEmpty())
return false;
// we only go raw if every type param is an erased union/intersection
// special case for Callable where we stop after the first type param
boolean isCallable = isCeylonCallable(type);
boolean everyTypeArgumentIsErasedUnionIntersection = true;
for(ProducedType typeArg : type.getTypeArgumentList()){
// skip invalid input
if(typeArg == null)
return false;
everyTypeArgumentIsErasedUnionIntersection &= isErasedUnionOrIntersection(typeArg);
// Callable really has a single type arg in Java
if(isCallable)
break;
// don't recurse
}
// we're only raw if every type param is an erased union/intersection
return everyTypeArgumentIsErasedUnionIntersection;
}
private boolean isErasedUnionOrIntersection(ProducedType producedType) {
TypeDeclaration typeDeclaration = producedType.getDeclaration();
if(typeDeclaration instanceof UnionType){
UnionType ut = (UnionType) typeDeclaration;
java.util.List<ProducedType> caseTypes = ut.getCaseTypes();
// special case for optional types
if(caseTypes.size() == 2){
if(isNull(caseTypes.get(0))){
return isErasedUnionOrIntersection(caseTypes.get(1));
}else if(isNull(caseTypes.get(1))){
return isErasedUnionOrIntersection(caseTypes.get(0));
}
}
// it is erased unless we turn it into Sequential something
return !willEraseToSequential(producedType);
}
if(typeDeclaration instanceof IntersectionType){
IntersectionType ut = (IntersectionType) typeDeclaration;
java.util.List<ProducedType> satisfiedTypes = ut.getSatisfiedTypes();
// special case for non-optional types
if(satisfiedTypes.size() == 2){
if(isObject(satisfiedTypes.get(0))){
return isErasedUnionOrIntersection(satisfiedTypes.get(1));
}else if(isObject(satisfiedTypes.get(1))){
return isErasedUnionOrIntersection(satisfiedTypes.get(0));
}
}
// it is erased unless we turn it into Sequential something
return !willEraseToSequential(producedType);
}
// we found something which is not erased entirely
return false;
}
boolean isCeylonString(ProducedType type) {
return (sameTypeForCeylonTypes(syms().ceylonStringType, type));
}
boolean isCeylonBoolean(ProducedType type) {
TypeDeclaration declaration = type.getDeclaration();
return declaration != null
&& (sameTypeForCeylonTypes(syms().ceylonBooleanType, type)
|| isBooleanTrue(declaration)
|| declaration == typeFact.getBooleanTrueClassDeclaration()
|| isBooleanFalse(declaration)
|| declaration == typeFact.getBooleanFalseClassDeclaration());
}
boolean isCeylonInteger(ProducedType type) {
return (sameTypeForCeylonTypes(syms().ceylonIntegerType, type));
}
boolean isCeylonFloat(ProducedType type) {
return (sameTypeForCeylonTypes(syms().ceylonFloatType, type));
}
boolean isCeylonCharacter(ProducedType type) {
return (sameTypeForCeylonTypes(syms().ceylonCharacterType, type));
}
boolean isCeylonArray(ProducedType type) {
return type.getSupertype(typeFact.getArrayDeclaration()) != null;
}