/
LambdaToMethod.java
2456 lines (2213 loc) · 103 KB
/
LambdaToMethod.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 (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import com.sun.tools.javac.code.Symbol.MethodHandleSymbol;
import com.sun.tools.javac.code.Types.SignatureGenerator.InvalidSignatureException;
import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeTranslator;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.DynamicMethodSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.MethodType;
import com.sun.tools.javac.code.Type.TypeVar;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.LambdaToMethod.LambdaAnalyzerPreprocessor.*;
import com.sun.tools.javac.comp.Lower.BasicFreeVarCollector;
import com.sun.tools.javac.resources.CompilerProperties.Notes;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static com.sun.tools.javac.comp.LambdaToMethod.LambdaSymbolKind.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.Kind.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
import javax.lang.model.element.ElementKind;
import javax.lang.model.type.TypeKind;
import com.sun.tools.javac.main.Option;
/**
* This pass desugars lambda expressions into static methods
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class LambdaToMethod extends TreeTranslator {
private Attr attr;
private JCDiagnostic.Factory diags;
private Log log;
private Lower lower;
private Names names;
private Symtab syms;
private Resolve rs;
private Operators operators;
private TreeMaker make;
private Types types;
private TransTypes transTypes;
private Env<AttrContext> attrEnv;
/** the analyzer scanner */
private LambdaAnalyzerPreprocessor analyzer;
/** map from lambda trees to translation contexts */
private Map<JCTree, TranslationContext<?>> contextMap;
/** current translation context (visitor argument) */
private TranslationContext<?> context;
/** info about the current class being processed */
private KlassInfo kInfo;
/** dump statistics about lambda code generation */
private final boolean dumpLambdaToMethodStats;
/** force serializable representation, for stress testing **/
private final boolean forceSerializable;
/** true if line or local variable debug info has been requested */
private final boolean debugLinesOrVars;
/** dump statistics about lambda method deduplication */
private final boolean verboseDeduplication;
/** deduplicate lambda implementation methods */
private final boolean deduplicateLambdas;
/** lambda proxy is a dynamic nestmate */
private final boolean nestmateLambdas;
/** Flag for alternate metafactories indicating the lambda object is intended to be serializable */
public static final int FLAG_SERIALIZABLE = 1 << 0;
/** Flag for alternate metafactories indicating the lambda object has multiple targets */
public static final int FLAG_MARKERS = 1 << 1;
/** Flag for alternate metafactories indicating the lambda object requires multiple bridges */
public static final int FLAG_BRIDGES = 1 << 2;
// <editor-fold defaultstate="collapsed" desc="Instantiating">
protected static final Context.Key<LambdaToMethod> unlambdaKey = new Context.Key<>();
public static LambdaToMethod instance(Context context) {
LambdaToMethod instance = context.get(unlambdaKey);
if (instance == null) {
instance = new LambdaToMethod(context);
}
return instance;
}
private LambdaToMethod(Context context) {
context.put(unlambdaKey, this);
diags = JCDiagnostic.Factory.instance(context);
log = Log.instance(context);
lower = Lower.instance(context);
names = Names.instance(context);
syms = Symtab.instance(context);
rs = Resolve.instance(context);
operators = Operators.instance(context);
make = TreeMaker.instance(context);
types = Types.instance(context);
transTypes = TransTypes.instance(context);
analyzer = new LambdaAnalyzerPreprocessor();
Options options = Options.instance(context);
dumpLambdaToMethodStats = options.isSet("debug.dumpLambdaToMethodStats");
attr = Attr.instance(context);
forceSerializable = options.isSet("forceSerializable");
debugLinesOrVars = options.isSet(Option.G)
|| options.isSet(Option.G_CUSTOM, "lines")
|| options.isSet(Option.G_CUSTOM, "vars");
verboseDeduplication = options.isSet("debug.dumpLambdaToMethodDeduplication");
deduplicateLambdas = options.getBoolean("deduplicateLambdas", true);
nestmateLambdas = Target.instance(context).runtimeUseNestAccess();
}
// </editor-fold>
class DedupedLambda {
private final MethodSymbol symbol;
private final JCTree tree;
private int hashCode;
DedupedLambda(MethodSymbol symbol, JCTree tree) {
this.symbol = symbol;
this.tree = tree;
}
@Override
public int hashCode() {
int hashCode = this.hashCode;
if (hashCode == 0) {
this.hashCode = hashCode = TreeHasher.hash(tree, symbol.params());
}
return hashCode;
}
@Override
public boolean equals(Object o) {
return (o instanceof DedupedLambda dedupedLambda)
&& types.isSameType(symbol.asType(), dedupedLambda.symbol.asType())
&& new TreeDiffer(symbol.params(), dedupedLambda.symbol.params()).scan(tree, dedupedLambda.tree);
}
}
private class KlassInfo {
/**
* list of methods to append
*/
private ListBuffer<JCTree> appendedMethodList;
private Map<DedupedLambda, DedupedLambda> dedupedLambdas;
private Map<Object, DynamicMethodSymbol> dynMethSyms = new HashMap<>();
/**
* list of deserialization cases
*/
private final Map<String, ListBuffer<JCStatement>> deserializeCases;
/**
* deserialize method symbol
*/
private final MethodSymbol deserMethodSym;
/**
* deserialize method parameter symbol
*/
private final VarSymbol deserParamSym;
private final JCClassDecl clazz;
private KlassInfo(JCClassDecl clazz) {
this.clazz = clazz;
appendedMethodList = new ListBuffer<>();
dedupedLambdas = new HashMap<>();
deserializeCases = new HashMap<>();
MethodType type = new MethodType(List.of(syms.serializedLambdaType), syms.objectType,
List.nil(), syms.methodClass);
deserMethodSym = makePrivateSyntheticMethod(STATIC, names.deserializeLambda, type, clazz.sym);
deserParamSym = new VarSymbol(FINAL, names.fromString("lambda"),
syms.serializedLambdaType, deserMethodSym);
}
private void addMethod(JCTree decl) {
appendedMethodList = appendedMethodList.prepend(decl);
}
}
// <editor-fold defaultstate="collapsed" desc="translate methods">
@Override
public <T extends JCTree> T translate(T tree) {
TranslationContext<?> newContext = contextMap.get(tree);
return translate(tree, newContext != null ? newContext : context);
}
<T extends JCTree> T translate(T tree, TranslationContext<?> newContext) {
TranslationContext<?> prevContext = context;
try {
context = newContext;
return super.translate(tree);
}
finally {
context = prevContext;
}
}
<T extends JCTree> List<T> translate(List<T> trees, TranslationContext<?> newContext) {
ListBuffer<T> buf = new ListBuffer<>();
for (T tree : trees) {
buf.append(translate(tree, newContext));
}
return buf.toList();
}
public JCTree translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
this.make = make;
this.attrEnv = env;
this.context = null;
this.contextMap = new HashMap<>();
return translate(cdef);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="visitor methods">
/**
* Visit a class.
* Maintain the translatedMethodList across nested classes.
* Append the translatedMethodList to the class after it is translated.
* @param tree
*/
@Override
public void visitClassDef(JCClassDecl tree) {
if (tree.sym.owner.kind == PCK) {
//analyze class
tree = analyzer.analyzeAndPreprocessClass(tree);
}
KlassInfo prevKlassInfo = kInfo;
try {
kInfo = new KlassInfo(tree);
super.visitClassDef(tree);
if (!kInfo.deserializeCases.isEmpty()) {
int prevPos = make.pos;
try {
make.at(tree);
kInfo.addMethod(makeDeserializeMethod(tree.sym));
} finally {
make.at(prevPos);
}
}
//add all translated instance methods here
List<JCTree> newMethods = kInfo.appendedMethodList.toList();
tree.defs = tree.defs.appendList(newMethods);
for (JCTree lambda : newMethods) {
tree.sym.members().enter(((JCMethodDecl)lambda).sym);
}
result = tree;
} finally {
kInfo = prevKlassInfo;
}
}
/**
* Translate a lambda into a method to be inserted into the class.
* Then replace the lambda site with an invokedynamic call of to lambda
* meta-factory, which will use the lambda method.
* @param tree
*/
@Override
public void visitLambda(JCLambda tree) {
LambdaTranslationContext localContext = (LambdaTranslationContext)context;
MethodSymbol sym = localContext.translatedSym;
MethodType lambdaType = (MethodType) sym.type;
{ /* Type annotation management: Based on where the lambda features, type annotations that
are interior to it, may at this point be attached to the enclosing method, or the first
constructor in the class, or in the enclosing class symbol or in the field whose
initializer is the lambda. In any event, gather up the annotations that belong to the
lambda and attach it to the implementation method.
*/
Symbol owner = localContext.owner;
apportionTypeAnnotations(tree,
owner::getRawTypeAttributes,
owner::setTypeAttributes,
sym::setTypeAttributes);
boolean init;
if ((init = (owner.name == names.init)) || owner.name == names.clinit) {
owner = owner.owner;
apportionTypeAnnotations(tree,
init ? owner::getInitTypeAttributes : owner::getClassInitTypeAttributes,
init ? owner::setInitTypeAttributes : owner::setClassInitTypeAttributes,
sym::appendUniqueTypeAttributes);
}
if (localContext.self != null && localContext.self.getKind() == ElementKind.FIELD) {
owner = localContext.self;
apportionTypeAnnotations(tree,
owner::getRawTypeAttributes,
owner::setTypeAttributes,
sym::appendUniqueTypeAttributes);
}
}
//create the method declaration hoisting the lambda body
JCMethodDecl lambdaDecl = make.MethodDef(make.Modifiers(sym.flags_field),
sym.name,
make.QualIdent(lambdaType.getReturnType().tsym),
List.nil(),
localContext.syntheticParams,
lambdaType.getThrownTypes() == null ?
List.nil() :
make.Types(lambdaType.getThrownTypes()),
null,
null);
lambdaDecl.sym = sym;
lambdaDecl.type = lambdaType;
//translate lambda body
//As the lambda body is translated, all references to lambda locals,
//captured variables, enclosing members are adjusted accordingly
//to refer to the static method parameters (rather than i.e. accessing
//captured members directly).
lambdaDecl.body = translate(makeLambdaBody(tree, lambdaDecl));
boolean dedupe = false;
if (deduplicateLambdas && !debugLinesOrVars && !localContext.isSerializable()) {
DedupedLambda dedupedLambda = new DedupedLambda(lambdaDecl.sym, lambdaDecl.body);
DedupedLambda existing = kInfo.dedupedLambdas.putIfAbsent(dedupedLambda, dedupedLambda);
if (existing != null) {
sym = existing.symbol;
dedupe = true;
if (verboseDeduplication) log.note(tree, Notes.VerboseL2mDeduplicate(sym));
}
}
if (!dedupe) {
//Add the method to the list of methods to be added to this class.
kInfo.addMethod(lambdaDecl);
}
//now that we have generated a method for the lambda expression,
//we can translate the lambda into a method reference pointing to the newly
//created method.
//
//Note that we need to adjust the method handle so that it will match the
//signature of the SAM descriptor - this means that the method reference
//should be added the following synthetic arguments:
//
// * the "this" argument if it is an instance method
// * enclosing locals captured by the lambda expression
ListBuffer<JCExpression> syntheticInits = new ListBuffer<>();
if (localContext.methodReferenceReceiver != null) {
syntheticInits.append(localContext.methodReferenceReceiver);
} else if (!sym.isStatic()) {
syntheticInits.append(makeThis(
sym.owner.enclClass().asType(),
localContext.owner.enclClass()));
}
//add captured locals
for (Symbol fv : localContext.getSymbolMap(CAPTURED_VAR).keySet()) {
if (fv != localContext.self) {
JCExpression captured_local = make.Ident(fv).setType(fv.type);
syntheticInits.append(captured_local);
}
}
// add captured outer this instances (used only when `this' capture itself is illegal)
for (Symbol fv : localContext.getSymbolMap(CAPTURED_OUTER_THIS).keySet()) {
JCExpression captured_local = make.QualThis(fv.type);
syntheticInits.append(captured_local);
}
//then, determine the arguments to the indy call
List<JCExpression> indy_args = translate(syntheticInits.toList(), localContext.prev);
//convert to an invokedynamic call
result = makeMetafactoryIndyCall(context, sym.asHandle(), indy_args);
}
// where
// Reassign type annotations from the source that should really belong to the lambda
private void apportionTypeAnnotations(JCLambda tree,
Supplier<List<Attribute.TypeCompound>> source,
Consumer<List<Attribute.TypeCompound>> owner,
Consumer<List<Attribute.TypeCompound>> lambda) {
ListBuffer<Attribute.TypeCompound> ownerTypeAnnos = new ListBuffer<>();
ListBuffer<Attribute.TypeCompound> lambdaTypeAnnos = new ListBuffer<>();
for (Attribute.TypeCompound tc : source.get()) {
if (tc.position.onLambda == tree) {
lambdaTypeAnnos.append(tc);
} else {
ownerTypeAnnos.append(tc);
}
}
if (lambdaTypeAnnos.nonEmpty()) {
owner.accept(ownerTypeAnnos.toList());
lambda.accept(lambdaTypeAnnos.toList());
}
}
private JCIdent makeThis(Type type, Symbol owner) {
VarSymbol _this = new VarSymbol(PARAMETER | FINAL | SYNTHETIC,
names._this,
type,
owner);
return make.Ident(_this);
}
/**
* Translate a method reference into an invokedynamic call to the
* meta-factory.
* @param tree
*/
@Override
public void visitReference(JCMemberReference tree) {
ReferenceTranslationContext localContext = (ReferenceTranslationContext)context;
//first determine the method symbol to be used to generate the sam instance
//this is either the method reference symbol, or the bridged reference symbol
MethodSymbol refSym = (MethodSymbol)tree.sym;
//the qualifying expression is treated as a special captured arg
JCExpression init;
switch(tree.kind) {
case IMPLICIT_INNER: /** Inner :: new */
case SUPER: /** super :: instMethod */
init = makeThis(
localContext.owner.enclClass().asType(),
localContext.owner.enclClass());
break;
case BOUND: /** Expr :: instMethod */
init = transTypes.coerce(attrEnv, tree.getQualifierExpression(),
types.erasure(tree.sym.owner.type));
init = attr.makeNullCheck(init);
break;
case UNBOUND: /** Type :: instMethod */
case STATIC: /** Type :: staticMethod */
case TOPLEVEL: /** Top level :: new */
case ARRAY_CTOR: /** ArrayType :: new */
init = null;
break;
default:
throw new InternalError("Should not have an invalid kind");
}
List<JCExpression> indy_args = init==null? List.nil() : translate(List.of(init), localContext.prev);
//build a sam instance using an indy call to the meta-factory
result = makeMetafactoryIndyCall(localContext, refSym.asHandle(), indy_args);
}
/**
* Translate identifiers within a lambda to the mapped identifier
* @param tree
*/
@Override
public void visitIdent(JCIdent tree) {
if (context == null || !analyzer.lambdaIdentSymbolFilter(tree.sym)) {
super.visitIdent(tree);
} else {
int prevPos = make.pos;
try {
make.at(tree);
LambdaTranslationContext lambdaContext = (LambdaTranslationContext) context;
JCTree ltree = lambdaContext.translate(tree);
if (ltree != null) {
result = ltree;
} else {
//access to untranslated symbols (i.e. compile-time constants,
//members defined inside the lambda body, etc.) )
super.visitIdent(tree);
}
} finally {
make.at(prevPos);
}
}
}
/**
* Translate qualified `this' references within a lambda to the mapped identifier
* @param tree
*/
@Override
public void visitSelect(JCFieldAccess tree) {
if (context == null || !analyzer.lambdaFieldAccessFilter(tree)) {
super.visitSelect(tree);
} else {
int prevPos = make.pos;
try {
make.at(tree);
LambdaTranslationContext lambdaContext = (LambdaTranslationContext) context;
JCTree ltree = lambdaContext.translate(tree);
if (ltree != null) {
result = ltree;
} else {
super.visitSelect(tree);
}
} finally {
make.at(prevPos);
}
}
}
/**
* Translate instance creation expressions with implicit enclosing instances
* @param tree
*/
@Override
public void visitNewClass(JCNewClass tree) {
if (context == null || !analyzer.lambdaNewClassFilter(context, tree)) {
super.visitNewClass(tree);
} else {
int prevPos = make.pos;
try {
make.at(tree);
LambdaTranslationContext lambdaContext = (LambdaTranslationContext) context;
tree = lambdaContext.translate(tree);
super.visitNewClass(tree);
} finally {
make.at(prevPos);
}
}
}
@Override
public void visitVarDef(JCVariableDecl tree) {
LambdaTranslationContext lambdaContext = (LambdaTranslationContext)context;
if (context != null && lambdaContext.getSymbolMap(LOCAL_VAR).containsKey(tree.sym)) {
tree.init = translate(tree.init);
tree.sym = (VarSymbol) lambdaContext.getSymbolMap(LOCAL_VAR).get(tree.sym);
result = tree;
} else {
super.visitVarDef(tree);
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Translation helper methods">
private JCBlock makeLambdaBody(JCLambda tree, JCMethodDecl lambdaMethodDecl) {
return tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
makeLambdaExpressionBody((JCExpression)tree.body, lambdaMethodDecl) :
makeLambdaStatementBody((JCBlock)tree.body, lambdaMethodDecl, tree.canCompleteNormally);
}
private JCBlock makeLambdaExpressionBody(JCExpression expr, JCMethodDecl lambdaMethodDecl) {
Type restype = lambdaMethodDecl.type.getReturnType();
boolean isLambda_void = expr.type.hasTag(VOID);
boolean isTarget_void = restype.hasTag(VOID);
boolean isTarget_Void = types.isSameType(restype, types.boxedClass(syms.voidType).type);
int prevPos = make.pos;
try {
if (isTarget_void) {
//target is void:
// BODY;
JCStatement stat = make.at(expr).Exec(expr);
return make.Block(0, List.of(stat));
} else if (isLambda_void && isTarget_Void) {
//void to Void conversion:
// BODY; return null;
ListBuffer<JCStatement> stats = new ListBuffer<>();
stats.append(make.at(expr).Exec(expr));
stats.append(make.Return(make.Literal(BOT, null).setType(syms.botType)));
return make.Block(0, stats.toList());
} else {
//non-void to non-void conversion:
// return BODY;
return make.at(expr).Block(0, List.of(make.Return(expr)));
}
} finally {
make.at(prevPos);
}
}
private JCBlock makeLambdaStatementBody(JCBlock block, final JCMethodDecl lambdaMethodDecl, boolean completeNormally) {
final Type restype = lambdaMethodDecl.type.getReturnType();
final boolean isTarget_void = restype.hasTag(VOID);
boolean isTarget_Void = types.isSameType(restype, types.boxedClass(syms.voidType).type);
class LambdaBodyTranslator extends TreeTranslator {
@Override
public void visitClassDef(JCClassDecl tree) {
//do NOT recurse on any inner classes
result = tree;
}
@Override
public void visitLambda(JCLambda tree) {
//do NOT recurse on any nested lambdas
result = tree;
}
@Override
public void visitReturn(JCReturn tree) {
boolean isLambda_void = tree.expr == null;
if (isTarget_void && !isLambda_void) {
//Void to void conversion:
// { TYPE $loc = RET-EXPR; return; }
VarSymbol loc = makeSyntheticVar(0, names.fromString("$loc"), tree.expr.type, lambdaMethodDecl.sym);
JCVariableDecl varDef = make.VarDef(loc, tree.expr);
result = make.Block(0, List.of(varDef, make.Return(null)));
} else {
result = tree;
}
}
}
JCBlock trans_block = new LambdaBodyTranslator().translate(block);
if (completeNormally && isTarget_Void) {
//there's no return statement and the lambda (possibly inferred)
//return type is java.lang.Void; emit a synthetic return statement
trans_block.stats = trans_block.stats.append(make.Return(make.Literal(BOT, null).setType(syms.botType)));
}
return trans_block;
}
private JCMethodDecl makeDeserializeMethod(Symbol kSym) {
ListBuffer<JCCase> cases = new ListBuffer<>();
ListBuffer<JCBreak> breaks = new ListBuffer<>();
for (Map.Entry<String, ListBuffer<JCStatement>> entry : kInfo.deserializeCases.entrySet()) {
JCBreak br = make.Break(null);
breaks.add(br);
List<JCStatement> stmts = entry.getValue().append(br).toList();
cases.add(make.Case(JCCase.STATEMENT, List.of(make.Literal(entry.getKey())), stmts, null));
}
JCSwitch sw = make.Switch(deserGetter("getImplMethodName", syms.stringType), cases.toList());
for (JCBreak br : breaks) {
br.target = sw;
}
JCBlock body = make.Block(0L, List.of(
sw,
make.Throw(makeNewClass(
syms.illegalArgumentExceptionType,
List.of(make.Literal("Invalid lambda deserialization"))))));
JCMethodDecl deser = make.MethodDef(make.Modifiers(kInfo.deserMethodSym.flags()),
names.deserializeLambda,
make.QualIdent(kInfo.deserMethodSym.getReturnType().tsym),
List.nil(),
List.of(make.VarDef(kInfo.deserParamSym, null)),
List.nil(),
body,
null);
deser.sym = kInfo.deserMethodSym;
deser.type = kInfo.deserMethodSym.type;
//System.err.printf("DESER: '%s'\n", deser);
return deser;
}
/** Make an attributed class instance creation expression.
* @param ctype The class type.
* @param args The constructor arguments.
* @param cons The constructor symbol
*/
JCNewClass makeNewClass(Type ctype, List<JCExpression> args, Symbol cons) {
JCNewClass tree = make.NewClass(null,
null, make.QualIdent(ctype.tsym), args, null);
tree.constructor = cons;
tree.type = ctype;
return tree;
}
/** Make an attributed class instance creation expression.
* @param ctype The class type.
* @param args The constructor arguments.
*/
JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
return makeNewClass(ctype, args,
rs.resolveConstructor(null, attrEnv, ctype, TreeInfo.types(args), List.nil()));
}
private void addDeserializationCase(MethodHandleSymbol refSym, Type targetType, MethodSymbol samSym,
DiagnosticPosition pos, List<LoadableConstant> staticArgs, MethodType indyType) {
String functionalInterfaceClass = classSig(targetType);
String functionalInterfaceMethodName = samSym.getSimpleName().toString();
String functionalInterfaceMethodSignature = typeSig(types.erasure(samSym.type));
String implClass = classSig(types.erasure(refSym.owner.type));
String implMethodName = refSym.getQualifiedName().toString();
String implMethodSignature = typeSig(types.erasure(refSym.type));
JCExpression kindTest = eqTest(syms.intType, deserGetter("getImplMethodKind", syms.intType),
make.Literal(refSym.referenceKind()));
ListBuffer<JCExpression> serArgs = new ListBuffer<>();
int i = 0;
for (Type t : indyType.getParameterTypes()) {
List<JCExpression> indexAsArg = new ListBuffer<JCExpression>().append(make.Literal(i)).toList();
List<Type> argTypes = new ListBuffer<Type>().append(syms.intType).toList();
serArgs.add(make.TypeCast(types.erasure(t), deserGetter("getCapturedArg", syms.objectType, argTypes, indexAsArg)));
++i;
}
JCStatement stmt = make.If(
deserTest(deserTest(deserTest(deserTest(deserTest(
kindTest,
"getFunctionalInterfaceClass", functionalInterfaceClass),
"getFunctionalInterfaceMethodName", functionalInterfaceMethodName),
"getFunctionalInterfaceMethodSignature", functionalInterfaceMethodSignature),
"getImplClass", implClass),
"getImplMethodSignature", implMethodSignature),
make.Return(makeIndyCall(
pos,
syms.lambdaMetafactory,
names.altMetafactory,
staticArgs, indyType, serArgs.toList(), samSym.name)),
null);
ListBuffer<JCStatement> stmts = kInfo.deserializeCases.get(implMethodName);
if (stmts == null) {
stmts = new ListBuffer<>();
kInfo.deserializeCases.put(implMethodName, stmts);
}
/****
System.err.printf("+++++++++++++++++\n");
System.err.printf("*functionalInterfaceClass: '%s'\n", functionalInterfaceClass);
System.err.printf("*functionalInterfaceMethodName: '%s'\n", functionalInterfaceMethodName);
System.err.printf("*functionalInterfaceMethodSignature: '%s'\n", functionalInterfaceMethodSignature);
System.err.printf("*implMethodKind: %d\n", implMethodKind);
System.err.printf("*implClass: '%s'\n", implClass);
System.err.printf("*implMethodName: '%s'\n", implMethodName);
System.err.printf("*implMethodSignature: '%s'\n", implMethodSignature);
****/
stmts.append(stmt);
}
private JCExpression eqTest(Type argType, JCExpression arg1, JCExpression arg2) {
JCBinary testExpr = make.Binary(JCTree.Tag.EQ, arg1, arg2);
testExpr.operator = operators.resolveBinary(testExpr, JCTree.Tag.EQ, argType, argType);
testExpr.setType(syms.booleanType);
return testExpr;
}
private JCExpression deserTest(JCExpression prev, String func, String lit) {
MethodType eqmt = new MethodType(List.of(syms.objectType), syms.booleanType, List.nil(), syms.methodClass);
Symbol eqsym = rs.resolveQualifiedMethod(null, attrEnv, syms.objectType, names.equals, List.of(syms.objectType), List.nil());
JCMethodInvocation eqtest = make.Apply(
List.nil(),
make.Select(deserGetter(func, syms.stringType), eqsym).setType(eqmt),
List.of(make.Literal(lit)));
eqtest.setType(syms.booleanType);
JCBinary compound = make.Binary(JCTree.Tag.AND, prev, eqtest);
compound.operator = operators.resolveBinary(compound, JCTree.Tag.AND, syms.booleanType, syms.booleanType);
compound.setType(syms.booleanType);
return compound;
}
private JCExpression deserGetter(String func, Type type) {
return deserGetter(func, type, List.nil(), List.nil());
}
private JCExpression deserGetter(String func, Type type, List<Type> argTypes, List<JCExpression> args) {
MethodType getmt = new MethodType(argTypes, type, List.nil(), syms.methodClass);
Symbol getsym = rs.resolveQualifiedMethod(null, attrEnv, syms.serializedLambdaType, names.fromString(func), argTypes, List.nil());
return make.Apply(
List.nil(),
make.Select(make.Ident(kInfo.deserParamSym).setType(syms.serializedLambdaType), getsym).setType(getmt),
args).setType(type);
}
/**
* Create new synthetic method with given flags, name, type, owner
*/
private MethodSymbol makePrivateSyntheticMethod(long flags, Name name, Type type, Symbol owner) {
return new MethodSymbol(flags | SYNTHETIC | PRIVATE, name, type, owner);
}
/**
* Create new synthetic variable with given flags, name, type, owner
*/
private VarSymbol makeSyntheticVar(long flags, Name name, Type type, Symbol owner) {
return new VarSymbol(flags | SYNTHETIC, name, type, owner);
}
/**
* Set varargsElement field on a given tree (must be either a new class tree
* or a method call tree)
*/
private void setVarargsIfNeeded(JCTree tree, Type varargsElement) {
if (varargsElement != null) {
switch (tree.getTag()) {
case APPLY: ((JCMethodInvocation)tree).varargsElement = varargsElement; break;
case NEWCLASS: ((JCNewClass)tree).varargsElement = varargsElement; break;
case TYPECAST: setVarargsIfNeeded(((JCTypeCast) tree).expr, varargsElement); break;
default: throw new AssertionError();
}
}
}
/**
* Convert method/constructor arguments by inserting appropriate cast
* as required by type-erasure - this is needed when bridging a lambda/method
* reference, as the bridged signature might require downcast to be compatible
* with the generated signature.
*/
private List<JCExpression> convertArgs(Symbol meth, List<JCExpression> args, Type varargsElement) {
Assert.check(meth.kind == MTH);
List<Type> formals = types.erasure(meth.type).getParameterTypes();
if (varargsElement != null) {
Assert.check((meth.flags() & VARARGS) != 0);
}
return transTypes.translateArgs(args, formals, varargsElement, attrEnv);
}
// </editor-fold>
/**
* Converts a method reference which cannot be used directly into a lambda
*/
private class MemberReferenceToLambda {
private final JCMemberReference tree;
private final ReferenceTranslationContext localContext;
private final Symbol owner;
private final ListBuffer<JCExpression> args = new ListBuffer<>();
private final ListBuffer<JCVariableDecl> params = new ListBuffer<>();
private JCExpression receiverExpression = null;
MemberReferenceToLambda(JCMemberReference tree, ReferenceTranslationContext localContext, Symbol owner) {
this.tree = tree;
this.localContext = localContext;
this.owner = owner;
}
JCLambda lambda() {
int prevPos = make.pos;
try {
make.at(tree);
//body generation - this can be either a method call or a
//new instance creation expression, depending on the member reference kind
VarSymbol rcvr = addParametersReturnReceiver();
JCExpression expr = (tree.getMode() == ReferenceMode.INVOKE)
? expressionInvoke(rcvr)
: expressionNew();
JCLambda slam = make.Lambda(params.toList(), expr);
slam.target = tree.target;
slam.type = tree.type;
slam.pos = tree.pos;
return slam;
} finally {
make.at(prevPos);
}
}
/**
* Generate the parameter list for the converted member reference.
*
* @return The receiver variable symbol, if any
*/
VarSymbol addParametersReturnReceiver() {
Type samDesc = localContext.bridgedRefSig();
List<Type> samPTypes = samDesc.getParameterTypes();
List<Type> descPTypes = tree.getDescriptorType(types).getParameterTypes();
// Determine the receiver, if any
VarSymbol rcvr;
switch (tree.kind) {
case BOUND:
// The receiver is explicit in the method reference
rcvr = addParameter("rec$", tree.getQualifierExpression().type, false);
receiverExpression = attr.makeNullCheck(tree.getQualifierExpression());
break;
case UNBOUND:
// The receiver is the first parameter, extract it and
// adjust the SAM and unerased type lists accordingly
rcvr = addParameter("rec$", samDesc.getParameterTypes().head, false);
samPTypes = samPTypes.tail;
descPTypes = descPTypes.tail;
break;
default:
rcvr = null;
break;
}
List<Type> implPTypes = tree.sym.type.getParameterTypes();
int implSize = implPTypes.size();
int samSize = samPTypes.size();
// Last parameter to copy from referenced method, exclude final var args
int last = localContext.needsVarArgsConversion() ? implSize - 1 : implSize;
// Failsafe -- assure match-up
boolean checkForIntersection = tree.varargsElement != null || implSize == descPTypes.size();
// Use parameter types of the implementation method unless the unerased
// SAM parameter type is an intersection type, in that case use the
// erased SAM parameter type so that the supertype relationship
// the implementation method parameters is not obscured.
// Note: in this loop, the lists implPTypes, samPTypes, and descPTypes
// are used as pointers to the current parameter type information
// and are thus not usable afterwards.
for (int i = 0; implPTypes.nonEmpty() && i < last; ++i) {
// By default use the implementation method parameter type
Type parmType = implPTypes.head;
if (checkForIntersection) {
if (descPTypes.head.getKind() == TypeKind.INTERSECTION) {
parmType = samPTypes.head;
}
// If the unerased parameter type is a type variable whose
// bound is an intersection (eg. <T extends A & B>) then
// use the SAM parameter type
if (descPTypes.head.getKind() == TypeKind.TYPEVAR) {
TypeVar tv = (TypeVar) descPTypes.head;
if (tv.getUpperBound().getKind() == TypeKind.INTERSECTION) {
parmType = samPTypes.head;
}
}
}
addParameter("x$" + i, parmType, true);
// Advance to the next parameter
implPTypes = implPTypes.tail;
samPTypes = samPTypes.tail;
descPTypes = descPTypes.tail;
}
// Flatten out the var args
for (int i = last; i < samSize; ++i) {
addParameter("xva$" + i, tree.varargsElement, true);
}
return rcvr;
}
JCExpression getReceiverExpression() {
return receiverExpression;
}