1 /*
2 * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package com.sun.tools.javac.comp;
27
28
29 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
30 import com.sun.tools.javac.code.*;
31 import com.sun.tools.javac.code.Attribute.TypeCompound;
32 import com.sun.tools.javac.code.Symbol.*;
33 import com.sun.tools.javac.code.Type.TypeVar;
34 import com.sun.tools.javac.jvm.Target;
35 import com.sun.tools.javac.tree.*;
36 import com.sun.tools.javac.tree.JCTree.*;
37 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
38 import com.sun.tools.javac.util.*;
39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
40 import com.sun.tools.javac.util.List;
41
42 import static com.sun.tools.javac.code.Flags.*;
43 import static com.sun.tools.javac.code.Kinds.Kind.*;
44 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
45 import static com.sun.tools.javac.code.TypeTag.CLASS;
46 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
47 import static com.sun.tools.javac.code.TypeTag.VOID;
48 import static com.sun.tools.javac.comp.CompileStates.CompileState;
49 import com.sun.tools.javac.tree.JCTree.JCBreak;
50
51 /** This pass translates Generic Java to conventional Java.
52 *
53 * <p><b>This is NOT part of any supported API.
54 * If you write code that depends on this, you do so at your own risk.
55 * This code and its internal interfaces are subject to change or
56 * deletion without notice.</b>
57 */
58 public class TransTypes extends TreeTranslator {
59 /** The context key for the TransTypes phase. */
60 protected static final Context.Key<TransTypes> transTypesKey = new Context.Key<>();
61
62 /** Get the instance for this context. */
63 public static TransTypes instance(Context context) {
64 TransTypes instance = context.get(transTypesKey);
65 if (instance == null)
66 instance = new TransTypes(context);
67 return instance;
68 }
69
70 private Names names;
71 private Log log;
72 private Symtab syms;
73 private TreeMaker make;
74 private Enter enter;
75 private Types types;
76 private Annotate annotate;
77 private Attr attr;
78 private final Resolve resolve;
79 private final CompileStates compileStates;
80 private final Target target;
81
82 @SuppressWarnings("this-escape")
83 protected TransTypes(Context context) {
84 context.put(transTypesKey, this);
85 compileStates = CompileStates.instance(context);
86 names = Names.instance(context);
87 log = Log.instance(context);
88 syms = Symtab.instance(context);
89 enter = Enter.instance(context);
90 types = Types.instance(context);
91 make = TreeMaker.instance(context);
92 resolve = Resolve.instance(context);
93 annotate = Annotate.instance(context);
94 attr = Attr.instance(context);
95 target = Target.instance(context);
96 }
97
98 /** Construct an attributed tree for a cast of expression to target type,
99 * unless it already has precisely that type.
100 * @param tree The expression tree.
101 * @param target The target type.
102 */
103 JCExpression cast(JCExpression tree, Type target) {
104 int oldpos = make.pos;
105 make.at(tree.pos);
106 if (!types.isSameType(tree.type, target)) {
107 if (!resolve.isAccessible(env, target.tsym))
108 resolve.logAccessErrorInternal(env, tree, target);
109 tree = explicitCastTP != null && types.isSameType(target, explicitCastTP) ?
110 tree :
111 make.TypeCast(make.Type(target), tree).setType(target);
112 }
113 make.pos = oldpos;
114 return tree;
115 }
116
117 /** Construct an attributed tree to coerce an expression to some erased
118 * target type, unless the expression is already assignable to that type.
119 * If target type is a constant type, use its base type instead.
120 * @param tree The expression tree.
121 * @param target The target type.
122 */
123 public JCExpression coerce(Env<AttrContext> env, JCExpression tree, Type target) {
124 Env<AttrContext> prevEnv = this.env;
125 try {
126 this.env = env;
127 return coerce(tree, target);
128 }
129 finally {
130 this.env = prevEnv;
131 }
132 }
133 JCExpression coerce(JCExpression tree, Type target) {
134 Type btarget = target.baseType();
135 if (tree.type.isPrimitive() == target.isPrimitive()) {
136 return types.isAssignable(tree.type, btarget, types.noWarnings)
137 ? tree
138 : cast(tree, btarget);
139 }
140 return tree;
141 }
142
143 /** Given an erased reference type, assume this type as the tree's type.
144 * Then, coerce to some given target type unless target type is null.
145 * This operation is used in situations like the following:
146 *
147 * <pre>{@code
148 * class Cell<A> { A value; }
149 * ...
150 * Cell<Integer> cell;
151 * Integer x = cell.value;
152 * }</pre>
153 *
154 * Since the erasure of Cell.value is Object, but the type
155 * of cell.value in the assignment is Integer, we need to
156 * adjust the original type of cell.value to Object, and insert
157 * a cast to Integer. That is, the last assignment becomes:
158 *
159 * <pre>{@code
160 * Integer x = (Integer)cell.value;
161 * }</pre>
162 *
163 * @param tree The expression tree whose type might need adjustment.
164 * @param erasedType The expression's type after erasure.
165 * @param target The target type, which is usually the erasure of the
166 * expression's original type.
167 */
168 JCExpression retype(JCExpression tree, Type erasedType, Type target) {
169 // System.err.println("retype " + tree + " to " + erasedType);//DEBUG
170 if (!erasedType.isPrimitive()) {
171 if (target != null && target.isPrimitive()) {
172 target = erasure(tree.type);
173 }
174 tree.type = erasedType;
175 if (target != null) {
176 return coerce(tree, target);
177 }
178 }
179 return tree;
180 }
181
182 /** Translate method argument list, casting each argument
183 * to its corresponding type in a list of target types.
184 * @param _args The method argument list.
185 * @param parameters The list of target types.
186 * @param varargsElement The erasure of the varargs element type,
187 * or null if translating a non-varargs invocation
188 */
189 <T extends JCTree> List<T> translateArgs(List<T> _args,
190 List<Type> parameters,
191 Type varargsElement) {
192 if (parameters.isEmpty()) return _args;
193 List<T> args = _args;
194 while (parameters.tail.nonEmpty()) {
195 args.head = translate(args.head, parameters.head);
196 args = args.tail;
197 parameters = parameters.tail;
198 }
199 Type parameter = parameters.head;
200 Assert.check(varargsElement != null || args.length() == 1);
201 if (varargsElement != null) {
202 while (args.nonEmpty()) {
203 args.head = translate(args.head, varargsElement);
204 args = args.tail;
205 }
206 } else {
207 args.head = translate(args.head, parameter);
208 }
209 return _args;
210 }
211
212 public <T extends JCTree> List<T> translateArgs(List<T> _args,
213 List<Type> parameters,
214 Type varargsElement,
215 Env<AttrContext> localEnv) {
216 Env<AttrContext> prevEnv = env;
217 try {
218 env = localEnv;
219 return translateArgs(_args, parameters, varargsElement);
220 }
221 finally {
222 env = prevEnv;
223 }
224 }
225
226 /** Add a bridge definition and enter corresponding method symbol in
227 * local scope of origin.
228 *
229 * @param pos The source code position to be used for the definition.
230 * @param meth The method for which a bridge needs to be added
231 * @param impl That method's implementation (possibly the method itself)
232 * @param origin The class to which the bridge will be added
233 * @param bridges The list buffer to which the bridge will be added
234 */
235 void addBridge(DiagnosticPosition pos,
236 MethodSymbol meth,
237 MethodSymbol impl,
238 ClassSymbol origin,
239 ListBuffer<JCTree> bridges) {
240 make.at(pos);
241 Type implTypeErasure = erasure(impl.type);
242
243 // Create a bridge method symbol and a bridge definition without a body.
244 Type bridgeType = meth.erasure(types);
245 long flags = impl.flags() & AccessFlags | SYNTHETIC | BRIDGE |
246 (origin.isInterface() ? DEFAULT : 0);
247 MethodSymbol bridge = new MethodSymbol(flags,
248 meth.name,
249 bridgeType,
250 origin);
251 bridge.params = createBridgeParams(impl, bridge, bridgeType);
252 bridge.setAttributes(impl);
253
254 JCMethodDecl md = make.MethodDef(bridge, null);
255
256 // The bridge calls this.impl(..), if we have an implementation
257 // in the current class, super.impl(...) otherwise.
258 JCExpression receiver = (impl.owner == origin)
259 ? make.This(origin.erasure(types))
260 : make.Super(types.supertype(origin.type).tsym.erasure(types), origin);
261
262 // The type returned from the original method.
263 Type calltype = implTypeErasure.getReturnType();
264
265 // Construct a call of this.impl(params), or super.impl(params),
266 // casting params and possibly results as needed.
267 JCExpression call =
268 make.Apply(
269 null,
270 make.Select(receiver, impl).setType(calltype),
271 translateArgs(make.Idents(md.params), implTypeErasure.getParameterTypes(), null))
272 .setType(calltype);
273 JCStatement stat = (implTypeErasure.getReturnType().hasTag(VOID))
274 ? make.Exec(call)
275 : make.Return(coerce(call, bridgeType.getReturnType()));
276 md.body = make.Block(0, List.of(stat));
277
278 // Add bridge to `bridges' buffer
279 bridges.append(md);
280
281 // Add bridge to scope of enclosing class and keep track of the bridge span.
282 origin.members().enter(bridge);
283 }
284
285 private List<VarSymbol> createBridgeParams(MethodSymbol impl, MethodSymbol bridge,
286 Type bridgeType) {
287 List<VarSymbol> bridgeParams = null;
288 if (impl.params != null) {
289 bridgeParams = List.nil();
290 List<VarSymbol> implParams = impl.params;
291 Type.MethodType mType = (Type.MethodType)bridgeType;
292 List<Type> argTypes = mType.argtypes;
293 while (implParams.nonEmpty() && argTypes.nonEmpty()) {
294 VarSymbol param = new VarSymbol(implParams.head.flags() | SYNTHETIC | PARAMETER,
295 implParams.head.name, argTypes.head, bridge);
296 param.setAttributes(implParams.head);
297 bridgeParams = bridgeParams.append(param);
298 implParams = implParams.tail;
299 argTypes = argTypes.tail;
300 }
301 }
302 return bridgeParams;
303 }
304
305 /** Add bridge if given symbol is a non-private, non-static member
306 * of the given class, which is either defined in the class or non-final
307 * inherited, and one of the two following conditions holds:
308 * 1. The method's type changes in the given class, as compared to the
309 * class where the symbol was defined, (in this case
310 * we have extended a parameterized class with non-trivial parameters).
311 * 2. The method has an implementation with a different erased return type.
312 * (in this case we have used co-variant returns).
313 * If a bridge already exists in some other class, no new bridge is added.
314 * Instead, it is checked that the bridge symbol overrides the method symbol.
315 * (Spec ???).
316 * todo: what about bridges for privates???
317 *
318 * @param pos The source code position to be used for the definition.
319 * @param sym The symbol for which a bridge might have to be added.
320 * @param origin The class in which the bridge would go.
321 * @param bridges The list buffer to which the bridge would be added.
322 */
323 void addBridgeIfNeeded(DiagnosticPosition pos,
324 Symbol sym,
325 ClassSymbol origin,
326 ListBuffer<JCTree> bridges) {
327 if (sym.kind == MTH &&
328 sym.name != names.init &&
329 (sym.flags() & (PRIVATE | STATIC)) == 0 &&
330 (sym.flags() & SYNTHETIC) != SYNTHETIC &&
331 sym.isMemberOf(origin, types)) {
332 MethodSymbol meth = (MethodSymbol)sym;
333 MethodSymbol bridge = meth.binaryImplementation(origin, types);
334 MethodSymbol impl = meth.implementation(origin, types, true);
335 if (bridge == null ||
336 bridge == meth ||
337 (impl != null && !bridge.owner.isSubClass(impl.owner, types))) {
338 // No bridge was added yet.
339 if (impl != null && bridge != impl && isBridgeNeeded(meth, impl, origin.type)) {
340 addBridge(pos, meth, impl, origin, bridges);
341 } else if (impl == meth
342 && impl.owner != origin
343 && (impl.flags() & FINAL) == 0
344 && (meth.flags() & (ABSTRACT|PUBLIC)) == PUBLIC
345 && (origin.flags() & PUBLIC) > (impl.owner.flags() & PUBLIC)) {
346 // this is to work around a horrible but permanent
347 // reflection design error.
348 addBridge(pos, meth, impl, origin, bridges);
349 }
350 }
351 }
352 }
353 // where
354
355 /**
356 * @param method The symbol for which a bridge might have to be added
357 * @param impl The implementation of method
358 * @param dest The type in which the bridge would go
359 */
360 private boolean isBridgeNeeded(MethodSymbol method,
361 MethodSymbol impl,
362 Type dest) {
363 if (impl != method) {
364 // If either method or impl have different erasures as
365 // members of dest, a bridge is needed.
366 Type method_erasure = method.erasure(types);
367 if (!isSameMemberWhenErased(dest, method, method_erasure))
368 return true;
369 Type impl_erasure = impl.erasure(types);
370 if (!isSameMemberWhenErased(dest, impl, impl_erasure))
371 return true;
372
373 /* Bottom line: A bridge is needed if the erasure of the implementation
374 is different from that of the method that it overrides.
375 */
376 return !types.isSameType(impl_erasure, method_erasure);
377 } else {
378 // method and impl are the same...
379 if ((method.flags() & ABSTRACT) != 0) {
380 // ...and abstract so a bridge is not needed.
381 // Concrete subclasses will bridge as needed.
382 return false;
383 }
384
385 // The erasure of the return type is always the same
386 // for the same symbol. Reducing the three tests in
387 // the other branch to just one:
388 return !isSameMemberWhenErased(dest, method, method.erasure(types));
389 }
390 }
391 /**
392 * Lookup the method as a member of the type. Compare the
393 * erasures.
394 * @param type the class where to look for the method
395 * @param method the method to look for in class
396 * @param erasure the erasure of method
397 */
398 private boolean isSameMemberWhenErased(Type type,
399 MethodSymbol method,
400 Type erasure) {
401 return types.isSameType(erasure(types.memberType(type, method)),
402 erasure);
403 }
404
405 void addBridges(DiagnosticPosition pos,
406 TypeSymbol i,
407 ClassSymbol origin,
408 ListBuffer<JCTree> bridges) {
409 for (Symbol sym : i.members().getSymbols(NON_RECURSIVE))
410 addBridgeIfNeeded(pos, sym, origin, bridges);
411 for (List<Type> l = types.interfaces(i.type); l.nonEmpty(); l = l.tail)
412 addBridges(pos, l.head.tsym, origin, bridges);
413 }
414
415 /** Add all necessary bridges to some class appending them to list buffer.
416 * @param pos The source code position to be used for the bridges.
417 * @param origin The class in which the bridges go.
418 * @param bridges The list buffer to which the bridges are added.
419 */
420 void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
421 Type st = types.supertype(origin.type);
422 while (st.hasTag(CLASS)) {
423 // if (isSpecialization(st))
424 addBridges(pos, st.tsym, origin, bridges);
425 st = types.supertype(st);
426 }
427 for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
428 // if (isSpecialization(l.head))
429 addBridges(pos, l.head.tsym, origin, bridges);
430 }
431
432 /* ************************************************************************
433 * Visitor methods
434 *************************************************************************/
435
436 /** Visitor argument: proto-type.
437 */
438 private Type pt;
439 /** we use this type to indicate that "upstream" there is an explicit cast to this type,
440 * this way we can avoid generating redundant type casts. Redundant casts are not
441 * innocuous as they can trump user provided ones and affect the offset
442 * calculation of type annotations applied to the user provided type cast.
443 */
444 private Type explicitCastTP;
445
446 /** Visitor method: perform a type translation on tree.
447 */
448 public <T extends JCTree> T translate(T tree, Type pt) {
449 return translate(tree, pt, pt == explicitCastTP ? explicitCastTP : null);
450 }
451
452 public <T extends JCTree> T translate(T tree, Type pt, Type castTP) {
453 Type prevPt = this.pt;
454 Type prevCastPT = this.explicitCastTP;
455 try {
456 this.pt = pt;
457 this.explicitCastTP = castTP;
458 return translate(tree);
459 } finally {
460 this.pt = prevPt;
461 this.explicitCastTP = prevCastPT;
462 }
463 }
464
465 /** Visitor method: perform a type translation on list of trees.
466 */
467 public <T extends JCTree> List<T> translate(List<T> trees, Type pt) {
468 Type prevPt = this.pt;
469 List<T> res;
470 try {
471 this.pt = pt;
472 res = translate(trees);
473 } finally {
474 this.pt = prevPt;
475 }
476 return res;
477 }
478
479 public void visitClassDef(JCClassDecl tree) {
480 translateClass(tree.sym);
481 result = tree;
482 }
483
484 Type returnType = null;
485 public void visitMethodDef(JCMethodDecl tree) {
486 Type prevRetType = returnType;
487 try {
488 returnType = erasure(tree.type).getReturnType();
489 tree.restype = translate(tree.restype, null);
490 tree.typarams = List.nil();
491 tree.params = translateVarDefs(tree.params);
492 tree.recvparam = translate(tree.recvparam, null);
493 tree.thrown = translate(tree.thrown, null);
494 tree.body = translate(tree.body, tree.sym.erasure(types).getReturnType());
495 tree.type = erasure(tree.type);
496 result = tree;
497 } finally {
498 returnType = prevRetType;
499 }
500 }
501
502 public void visitVarDef(JCVariableDecl tree) {
503 tree.vartype = translate(tree.vartype, null);
504 tree.init = translate(tree.init, tree.sym.erasure(types));
505 tree.type = erasure(tree.type);
506 result = tree;
507 }
508
509 public void visitDoLoop(JCDoWhileLoop tree) {
510 tree.body = translate(tree.body);
511 tree.cond = translate(tree.cond, syms.booleanType);
512 result = tree;
513 }
514
515 public void visitWhileLoop(JCWhileLoop tree) {
516 tree.cond = translate(tree.cond, syms.booleanType);
517 tree.body = translate(tree.body);
518 result = tree;
519 }
520
521 public void visitForLoop(JCForLoop tree) {
522 tree.init = translate(tree.init, null);
523 if (tree.cond != null)
524 tree.cond = translate(tree.cond, syms.booleanType);
525 tree.step = translate(tree.step, null);
526 tree.body = translate(tree.body);
527 result = tree;
528 }
529
530 public void visitForeachLoop(JCEnhancedForLoop tree) {
531 tree.var = translate(tree.var, null);
532 Type iterableType = tree.expr.type;
533 tree.expr = translate(tree.expr, erasure(tree.expr.type));
534 if (types.elemtype(tree.expr.type) == null)
535 tree.expr.type = iterableType; // preserve type for Lower
536 tree.body = translate(tree.body);
537 result = tree;
538 }
539
540 public void visitLambda(JCLambda tree) {
541 Type prevRetType = returnType;
542 try {
543 returnType = erasure(tree.getDescriptorType(types)).getReturnType();
544 tree.params = translate(tree.params);
545 tree.body = translate(tree.body, tree.body.type == null || returnType.hasTag(VOID) ? null : returnType);
546 if (!tree.type.isIntersection()) {
547 tree.type = erasure(tree.type);
548 } else {
549 tree.type = types.erasure(types.findDescriptorSymbol(tree.type.tsym).owner.type);
550 }
551 result = tree;
552 }
553 finally {
554 returnType = prevRetType;
555 }
556 }
557
558 @Override
559 public void visitReference(JCMemberReference tree) {
560 if (needsConversionToLambda(tree)) {
561 // Convert to a lambda, and process as such
562 MemberReferenceToLambda conv = new MemberReferenceToLambda(tree);
563 result = translate(conv.lambda());
564 } else {
565 Type t = types.skipTypeVars(tree.expr.type, false);
566 Type receiverTarget = t.isCompound() ? erasure(tree.sym.owner.type) : erasure(t);
567 if (tree.kind == ReferenceKind.UNBOUND) {
568 tree.expr = make.Type(receiverTarget);
569 } else {
570 tree.expr = translate(tree.expr, receiverTarget);
571 }
572 if (!tree.type.isIntersection()) {
573 tree.type = erasure(tree.type);
574 } else {
575 tree.type = types.erasure(types.findDescriptorSymbol(tree.type.tsym).owner.type);
576 }
577 result = tree;
578 }
579 }
580 // where
581 boolean needsVarArgsConversion(JCMemberReference tree) {
582 return tree.varargsElement != null;
583 }
584
585 /**
586 * @return Is this an array operation like clone()
587 */
588 boolean isArrayOp(JCMemberReference tree) {
589 return tree.sym.owner == syms.arrayClass;
590 }
591
592 boolean receiverAccessible(JCMemberReference tree) {
593 //hack needed to workaround 292 bug (7087658)
594 //when 292 issue is fixed we should remove this and change the backend
595 //code to always generate a method handle to an accessible method
596 return tree.ownerAccessible;
597 }
598
599 /**
600 * Erasure destroys the implementation parameter subtype
601 * relationship for intersection types.
602 * Have similar problems for union types too.
603 */
604 boolean interfaceParameterIsIntersectionOrUnionType(JCMemberReference tree) {
605 List<Type> tl = tree.getDescriptorType(types).getParameterTypes();
606 for (; tl.nonEmpty(); tl = tl.tail) {
607 Type pt = tl.head;
608 if (isIntersectionOrUnionType(pt))
609 return true;
610 }
611 return false;
612 }
613
614 boolean isIntersectionOrUnionType(Type t) {
615 return switch (t.getKind()) {
616 case INTERSECTION, UNION -> true;
617 case TYPEVAR -> {
618 TypeVar tv = (TypeVar) t;
619 yield isIntersectionOrUnionType(tv.getUpperBound());
620 }
621 default -> false;
622 };
623 }
624
625 private boolean isProtectedInSuperClassOfEnclosingClassInOtherPackage(Symbol targetReference,
626 Symbol currentClass) {
627 return ((targetReference.flags() & PROTECTED) != 0 &&
628 targetReference.packge() != currentClass.packge());
629 }
630
631 /**
632 * This method should be called only when target release <= 14
633 * where LambdaMetaFactory does not spin nestmate classes.
634 *
635 * This method should be removed when --release 14 is not supported.
636 */
637 boolean isPrivateInOtherClass(JCMemberReference tree) {
638 return (tree.sym.flags() & PRIVATE) != 0 &&
639 !types.isSameType(
640 types.erasure(tree.sym.enclClass().asType()),
641 types.erasure(env.enclClass.sym.asType()));
642 }
643
644 /**
645 * Does this reference need to be converted to a lambda
646 * (i.e. var args need to be expanded or "super" is used)
647 */
648 boolean needsConversionToLambda(JCMemberReference tree) {
649 return interfaceParameterIsIntersectionOrUnionType(tree) ||
650 tree.hasKind(ReferenceKind.SUPER) ||
651 needsVarArgsConversion(tree) ||
652 tree.codeReflectionInfo != null ||
653 isArrayOp(tree) ||
654 (!target.runtimeUseNestAccess() && isPrivateInOtherClass(tree)) ||
655 isProtectedInSuperClassOfEnclosingClassInOtherPackage(tree.sym, env.enclClass.sym) ||
656 !receiverAccessible(tree) ||
657 (tree.getMode() == ReferenceMode.NEW &&
658 tree.kind != ReferenceKind.ARRAY_CTOR &&
659 (tree.sym.owner.isDirectlyOrIndirectlyLocal() || tree.sym.owner.isInner()));
660 }
661
662 /**
663 * Converts a method reference which cannot be used directly into a lambda
664 */
665 private class MemberReferenceToLambda {
666
667 private final JCMemberReference tree;
668 private final ListBuffer<JCExpression> args = new ListBuffer<>();
669 private final ListBuffer<JCVariableDecl> params = new ListBuffer<>();
670 private final MethodSymbol owner = new MethodSymbol(0, names.empty, Type.noType, env.enclClass.sym);
671
672 private JCExpression receiverExpression = null;
673
674 MemberReferenceToLambda(JCMemberReference tree) {
675 this.tree = tree;
676 }
677
678 JCExpression lambda() {
679 int prevPos = make.pos;
680 try {
681 make.at(tree);
682
683 //body generation - this can be either a method call or a
684 //new instance creation expression, depending on the member reference kind
685 VarSymbol rcvr = addParametersReturnReceiver();
686 JCExpression expr = (tree.getMode() == ReferenceMode.INVOKE)
687 ? expressionInvoke(rcvr)
688 : expressionNew();
689
690 JCLambda slam = make.Lambda(params.toList(), expr);
691 slam.target = tree.target;
692 slam.owner = tree.owner;
693 slam.type = tree.type;
694 slam.pos = tree.pos;
695 slam.codeReflectionInfo = tree.codeReflectionInfo;
696 slam.wasMethodReference = true;
697 if (receiverExpression != null) {
698 // use a let expression so that the receiver expression is evaluated eagerly
699 return make.at(tree.pos).LetExpr(
700 make.VarDef(rcvr, receiverExpression), slam).setType(tree.type);
701 } else {
702 return slam;
703 }
704 } finally {
705 make.at(prevPos);
706 }
707 }
708
709 /**
710 * Generate the parameter list for the converted member reference.
711 *
712 * @return The receiver variable symbol, if any
713 */
714 VarSymbol addParametersReturnReceiver() {
715 List<Type> descPTypes = tree.getDescriptorType(types).getParameterTypes();
716
717 // Determine the receiver, if any
718 VarSymbol rcvr;
719 switch (tree.kind) {
720 case BOUND:
721 // The receiver is explicit in the method reference
722 rcvr = new VarSymbol(SYNTHETIC, names.fromString("rec$"), tree.getQualifierExpression().type, owner);
723 rcvr.pos = tree.pos;
724 receiverExpression = attr.makeNullCheck(tree.getQualifierExpression());
725 break;
726 case UNBOUND:
727 // The receiver is the first parameter, extract it and
728 // adjust the SAM and unerased type lists accordingly
729 rcvr = addParameter("rec$", descPTypes.head, false);
730 descPTypes = descPTypes.tail;
731 break;
732 default:
733 rcvr = null;
734 break;
735 }
736 List<Type> implPTypes = tree.sym.type.getParameterTypes();
737 int implSize = implPTypes.size();
738 int samSize = descPTypes.size();
739 // Last parameter to copy from referenced method, exclude final var args
740 int last = needsVarArgsConversion(tree) ? implSize - 1 : implSize;
741
742 for (int i = 0; implPTypes.nonEmpty() && i < last; ++i) {
743 // Use the descriptor parameter type
744 Type parmType = descPTypes.head;
745 addParameter("x$" + i, parmType, true);
746
747 // Advance to the next parameter
748 implPTypes = implPTypes.tail;
749 descPTypes = descPTypes.tail;
750 }
751 // Flatten out the var args
752 for (int i = last; i < samSize; ++i) {
753 addParameter("xva$" + i, tree.varargsElement, true);
754 }
755
756 return rcvr;
757 }
758
759 /**
760 * determine the receiver of the method call - the receiver can
761 * be a type qualifier, the synthetic receiver parameter or 'super'.
762 */
763 private JCExpression expressionInvoke(VarSymbol rcvr) {
764 JCExpression qualifier =
765 (rcvr != null) ?
766 make.Ident(rcvr) :
767 tree.getQualifierExpression();
768
769 //create the qualifier expression
770 JCFieldAccess select = make.Select(qualifier, tree.sym.name);
771 select.sym = tree.sym;
772 select.type = tree.referentType;
773
774 //create the method call expression
775 JCExpression apply = make.Apply(List.nil(), select,
776 args.toList()).setType(tree.referentType.getReturnType());
777
778 TreeInfo.setVarargsElement(apply, tree.varargsElement);
779 return apply;
780 }
781
782 /**
783 * Lambda body to use for a 'new'.
784 */
785 private JCExpression expressionNew() {
786 if (tree.kind == ReferenceKind.ARRAY_CTOR) {
787 //create the array creation expression
788 JCNewArray newArr = make.NewArray(
789 make.Type(types.elemtype(tree.getQualifierExpression().type)),
790 List.of(make.Ident(params.first())),
791 null);
792 newArr.type = tree.getQualifierExpression().type;
793 return newArr;
794 } else {
795 //create the instance creation expression
796 //note that method reference syntax does not allow an explicit
797 //enclosing class (so the enclosing class is null)
798 // but this may need to be patched up later with the proxy for the outer this
799 JCNewClass newClass = make.NewClass(null,
800 List.nil(),
801 make.Type(tree.getQualifierExpression().type),
802 args.toList(),
803 null);
804 newClass.constructor = tree.sym;
805 newClass.constructorType = tree.sym.erasure(types);
806 newClass.type = tree.getQualifierExpression().type;
807 TreeInfo.setVarargsElement(newClass, tree.varargsElement);
808 return newClass;
809 }
810 }
811
812 private VarSymbol addParameter(String name, Type p, boolean genArg) {
813 VarSymbol vsym = new VarSymbol(PARAMETER | SYNTHETIC, names.fromString(name), p, owner);
814 vsym.pos = tree.pos;
815 params.append(make.VarDef(vsym, null));
816 if (genArg) {
817 args.append(make.Ident(vsym));
818 }
819 return vsym;
820 }
821 }
822
823 public void visitSwitch(JCSwitch tree) {
824 tree.selector = translate(tree.selector, erasure(tree.selector.type));
825 tree.cases = translateCases(tree.cases);
826 result = tree;
827 }
828
829 public void visitCase(JCCase tree) {
830 tree.labels = translate(tree.labels, null);
831 tree.guard = translate(tree.guard, syms.booleanType);
832 tree.stats = translate(tree.stats);
833 result = tree;
834 }
835
836 @Override
837 public void visitAnyPattern(JCAnyPattern tree) {
838 result = tree;
839 }
840
841 public void visitBindingPattern(JCBindingPattern tree) {
842 tree.var = translate(tree.var, null);
843 result = tree;
844 }
845
846 @Override
847 public void visitConstantCaseLabel(JCConstantCaseLabel tree) {
848 tree.expr = translate(tree.expr, null);
849 result = tree;
850 }
851
852 @Override
853 public void visitPatternCaseLabel(JCPatternCaseLabel tree) {
854 tree.pat = translate(tree.pat, null);
855 result = tree;
856 }
857
858 public void visitSwitchExpression(JCSwitchExpression tree) {
859 tree.selector = translate(tree.selector, erasure(tree.selector.type));
860 tree.cases = translate(tree.cases, erasure(tree.type));
861 tree.type = erasure(tree.type);
862 result = retype(tree, tree.type, pt);
863 }
864
865 public void visitRecordPattern(JCRecordPattern tree) {
866 tree.fullComponentTypes = tree.record.getRecordComponents()
867 .map(rc -> types.memberType(tree.type, rc));
868 tree.deconstructor = translate(tree.deconstructor, null);
869 tree.nested = translate(tree.nested, null);
870 result = tree;
871 }
872
873 public void visitSynchronized(JCSynchronized tree) {
874 tree.lock = translate(tree.lock, erasure(tree.lock.type));
875 tree.body = translate(tree.body);
876 result = tree;
877 }
878
879 public void visitTry(JCTry tree) {
880 tree.resources = translate(tree.resources, syms.autoCloseableType);
881 tree.body = translate(tree.body);
882 tree.catchers = translateCatchers(tree.catchers);
883 tree.finalizer = translate(tree.finalizer);
884 result = tree;
885 }
886
887 public void visitConditional(JCConditional tree) {
888 tree.cond = translate(tree.cond, syms.booleanType);
889 tree.truepart = translate(tree.truepart, erasure(tree.type));
890 tree.falsepart = translate(tree.falsepart, erasure(tree.type));
891 tree.type = erasure(tree.type);
892 result = retype(tree, tree.type, pt);
893 }
894
895 public void visitIf(JCIf tree) {
896 tree.cond = translate(tree.cond, syms.booleanType);
897 tree.thenpart = translate(tree.thenpart);
898 tree.elsepart = translate(tree.elsepart);
899 result = tree;
900 }
901
902 public void visitExec(JCExpressionStatement tree) {
903 tree.expr = translate(tree.expr, null);
904 result = tree;
905 }
906
907 public void visitReturn(JCReturn tree) {
908 if (!returnType.hasTag(VOID))
909 tree.expr = translate(tree.expr, returnType);
910 result = tree;
911 }
912
913 @Override
914 public void visitBreak(JCBreak tree) {
915 result = tree;
916 }
917
918 @Override
919 public void visitYield(JCYield tree) {
920 tree.value = translate(tree.value, erasure(tree.value.type));
921 tree.value.type = erasure(tree.value.type);
922 tree.value = retype(tree.value, tree.value.type, pt);
923 result = tree;
924 }
925
926 public void visitThrow(JCThrow tree) {
927 tree.expr = translate(tree.expr, erasure(tree.expr.type));
928 result = tree;
929 }
930
931 public void visitAssert(JCAssert tree) {
932 tree.cond = translate(tree.cond, syms.booleanType);
933 if (tree.detail != null)
934 tree.detail = translate(tree.detail, erasure(tree.detail.type));
935 result = tree;
936 }
937
938 public void visitApply(JCMethodInvocation tree) {
939 tree.meth = translate(tree.meth, null);
940 Symbol meth = TreeInfo.symbol(tree.meth);
941 Type mt = meth.erasure(types);
942 boolean useInstantiatedPtArgs = !types.isSignaturePolymorphic((MethodSymbol)meth.baseSymbol());
943 List<Type> argtypes = useInstantiatedPtArgs ?
944 tree.meth.type.getParameterTypes() :
945 mt.getParameterTypes();
946 if (meth.name == names.init && meth.owner == syms.enumSym)
947 argtypes = argtypes.tail.tail;
948 if (tree.varargsElement != null)
949 tree.varargsElement = types.erasure(tree.varargsElement);
950 else
951 if (tree.args.length() != argtypes.length()) {
952 Assert.error(String.format("Incorrect number of arguments; expected %d, found %d",
953 tree.args.length(), argtypes.length()));
954 }
955 tree.args = translateArgs(tree.args, argtypes, tree.varargsElement);
956
957 tree.type = types.erasure(tree.type);
958 // Insert casts of method invocation results as needed.
959 result = retype(tree, mt.getReturnType(), pt);
960 }
961
962 public void visitNewClass(JCNewClass tree) {
963 if (tree.encl != null) {
964 if (tree.def == null) {
965 tree.encl = translate(tree.encl, erasure(tree.encl.type));
966 } else {
967 tree.args = tree.args.prepend(attr.makeNullCheck(tree.encl));
968 tree.encl = null;
969 }
970 }
971
972 Type erasedConstructorType = tree.constructorType != null ?
973 erasure(tree.constructorType) :
974 null;
975
976 List<Type> argtypes = erasedConstructorType != null ?
977 erasedConstructorType.getParameterTypes() :
978 tree.constructor.erasure(types).getParameterTypes();
979
980 tree.clazz = translate(tree.clazz, null);
981 if (tree.varargsElement != null)
982 tree.varargsElement = types.erasure(tree.varargsElement);
983 tree.args = translateArgs(
984 tree.args, argtypes, tree.varargsElement);
985 tree.def = translate(tree.def, null);
986 if (erasedConstructorType != null)
987 tree.constructorType = erasedConstructorType;
988 tree.type = erasure(tree.type);
989 result = tree;
990 }
991
992 public void visitNewArray(JCNewArray tree) {
993 tree.elemtype = translate(tree.elemtype, null);
994 translate(tree.dims, syms.intType);
995 if (tree.type != null) {
996 tree.elems = translate(tree.elems, erasure(types.elemtype(tree.type)));
997 tree.type = erasure(tree.type);
998 } else {
999 tree.elems = translate(tree.elems, null);
1000 }
1001
1002 result = tree;
1003 }
1004
1005 public void visitParens(JCParens tree) {
1006 tree.expr = translate(tree.expr, pt);
1007 tree.type = erasure(tree.expr.type);
1008 result = tree;
1009 }
1010
1011 public void visitAssign(JCAssign tree) {
1012 tree.lhs = translate(tree.lhs, null);
1013 tree.rhs = translate(tree.rhs, erasure(tree.lhs.type));
1014 tree.type = erasure(tree.lhs.type);
1015 result = retype(tree, tree.type, pt);
1016 }
1017
1018 public void visitAssignop(JCAssignOp tree) {
1019 tree.lhs = translate(tree.lhs, null);
1020 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
1021 tree.type = erasure(tree.type);
1022 result = tree;
1023 }
1024
1025 public void visitUnary(JCUnary tree) {
1026 tree.arg = translate(tree.arg, (tree.getTag() == Tag.NULLCHK)
1027 ? tree.type
1028 : tree.operator.type.getParameterTypes().head);
1029 result = tree;
1030 }
1031
1032 public void visitBinary(JCBinary tree) {
1033 tree.lhs = translate(tree.lhs, tree.operator.type.getParameterTypes().head);
1034 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
1035 result = tree;
1036 }
1037
1038 public void visitAnnotatedType(JCAnnotatedType tree) {
1039 // For now, we need to keep the annotations in the tree because of the current
1040 // MultiCatch implementation wrt type annotations
1041 List<TypeCompound> mirrors = annotate.fromAnnotations(tree.annotations);
1042 tree.underlyingType = translate(tree.underlyingType);
1043 tree.type = tree.underlyingType.type.annotatedType(mirrors);
1044 result = tree;
1045 }
1046
1047 public void visitTypeCast(JCTypeCast tree) {
1048 tree.clazz = translate(tree.clazz, null);
1049 Type originalTarget = tree.type;
1050 tree.type = erasure(tree.type);
1051 JCExpression newExpression = tree.clazz.hasTag(Tag.ANNOTATED_TYPE) ?
1052 translate(tree.expr, tree.type, tree.type) :
1053 translate(tree.expr, tree.type);
1054 if (newExpression != tree.expr) {
1055 JCTypeCast typeCast = newExpression.hasTag(Tag.TYPECAST)
1056 ? (JCTypeCast) newExpression
1057 : null;
1058 tree.expr = typeCast != null && types.isSameType(typeCast.type, tree.type)
1059 ? typeCast.expr
1060 : newExpression;
1061 }
1062 if (originalTarget.isIntersection()) {
1063 Type.IntersectionClassType ict = (Type.IntersectionClassType)originalTarget;
1064 for (Type c : ict.getExplicitComponents()) {
1065 Type ec = erasure(c);
1066 if (!types.isSameType(ec, tree.type) && (!types.isSameType(ec, pt))) {
1067 tree.expr = coerce(tree.expr, ec);
1068 }
1069 }
1070 }
1071 result = retype(tree, tree.type, pt);
1072 }
1073
1074 public void visitTypeTest(JCInstanceOf tree) {
1075 tree.pattern = translate(tree.pattern, null);
1076 if (tree.pattern.type.isPrimitive()) {
1077 tree.erasedExprOriginalType = erasure(tree.expr.type);
1078 tree.expr = translate(tree.expr, null);
1079 }
1080 else {
1081 tree.expr = translate(tree.expr, null);
1082 }
1083 result = tree;
1084 }
1085
1086 public void visitIndexed(JCArrayAccess tree) {
1087 tree.indexed = translate(tree.indexed, erasure(tree.indexed.type));
1088 tree.index = translate(tree.index, syms.intType);
1089
1090 // Insert casts of indexed expressions as needed.
1091 result = retype(tree, types.elemtype(tree.indexed.type), pt);
1092 }
1093
1094 // There ought to be nothing to rewrite here;
1095 // we don't generate code.
1096 public void visitAnnotation(JCAnnotation tree) {
1097 result = tree;
1098 }
1099
1100 public void visitIdent(JCIdent tree) {
1101 Type et = tree.sym.erasure(types);
1102
1103 // Map type variables to their bounds.
1104 if (tree.sym.kind == TYP && tree.sym.type.hasTag(TYPEVAR)) {
1105 result = make.at(tree.pos).Type(et);
1106 } else
1107 // Map constants expressions to themselves.
1108 if (tree.type.constValue() != null) {
1109 result = tree;
1110 }
1111 // Insert casts of variable uses as needed.
1112 else if (tree.sym.kind == VAR) {
1113 result = retype(tree, et, pt);
1114 }
1115 else {
1116 tree.type = erasure(tree.type);
1117 result = tree;
1118 }
1119 }
1120
1121 public void visitSelect(JCFieldAccess tree) {
1122 Type t = types.skipTypeVars(tree.selected.type, false);
1123 if (t.isCompound()) {
1124 tree.selected = coerce(
1125 translate(tree.selected, erasure(tree.selected.type)),
1126 erasure(tree.sym.owner.type));
1127 } else
1128 tree.selected = translate(tree.selected, erasure(t));
1129
1130 // Map constants expressions to themselves.
1131 if (tree.type.constValue() != null) {
1132 result = tree;
1133 }
1134 // Insert casts of variable uses as needed.
1135 else if (tree.sym.kind == VAR) {
1136 result = retype(tree, tree.sym.erasure(types), pt);
1137 }
1138 else {
1139 tree.type = erasure(tree.type);
1140 result = tree;
1141 }
1142 }
1143
1144 public void visitTypeArray(JCArrayTypeTree tree) {
1145 tree.elemtype = translate(tree.elemtype, null);
1146 tree.type = erasure(tree.type);
1147 result = tree;
1148 }
1149
1150 /** Visitor method for parameterized types.
1151 */
1152 public void visitTypeApply(JCTypeApply tree) {
1153 JCTree clazz = translate(tree.clazz, null);
1154 result = clazz;
1155 }
1156
1157 public void visitTypeIntersection(JCTypeIntersection tree) {
1158 result = translate(tree.bounds.head, null);
1159 }
1160
1161 /* ************************************************************************
1162 * utility methods
1163 *************************************************************************/
1164
1165 private Type erasure(Type t) {
1166 return types.erasure(t);
1167 }
1168
1169 /* ************************************************************************
1170 * main method
1171 *************************************************************************/
1172
1173 private Env<AttrContext> env;
1174
1175 private static final String statePreviousToFlowAssertMsg =
1176 "The current compile state [%s] of class %s is previous to WARN";
1177
1178 void translateClass(ClassSymbol c) {
1179 Type st = types.supertype(c.type);
1180 // process superclass before derived
1181 if (st.hasTag(CLASS)) {
1182 translateClass((ClassSymbol)st.tsym);
1183 }
1184
1185 Env<AttrContext> myEnv = enter.getEnv(c);
1186 if (myEnv == null || (c.flags_field & TYPE_TRANSLATED) != 0) {
1187 return;
1188 }
1189 c.flags_field |= TYPE_TRANSLATED;
1190
1191 /* The two assertions below are set for early detection of any attempt
1192 * to translate a class that:
1193 *
1194 * 1) has no compile state being it the most outer class.
1195 * We accept this condition for inner classes.
1196 *
1197 * 2) has a compile state which is previous to WARN state.
1198 */
1199 boolean envHasCompState = compileStates.get(myEnv) != null;
1200 if (!envHasCompState && c.outermostClass() == c) {
1201 Assert.error("No info for outermost class: " + myEnv.enclClass.sym);
1202 }
1203
1204 if (envHasCompState &&
1205 CompileState.WARN.isAfter(compileStates.get(myEnv))) {
1206 Assert.error(String.format(statePreviousToFlowAssertMsg,
1207 compileStates.get(myEnv), myEnv.enclClass.sym));
1208 }
1209
1210 Env<AttrContext> oldEnv = env;
1211 try {
1212 env = myEnv;
1213 // class has not been translated yet
1214
1215 TreeMaker savedMake = make;
1216 Type savedPt = pt;
1217 make = make.forToplevel(env.toplevel);
1218 pt = null;
1219 try {
1220 JCClassDecl tree = (JCClassDecl) env.tree;
1221 tree.typarams = List.nil();
1222 super.visitClassDef(tree);
1223 make.at(tree.pos);
1224 ListBuffer<JCTree> bridges = new ListBuffer<>();
1225 addBridges(tree.pos(), c, bridges);
1226 tree.defs = bridges.toList().prependList(tree.defs);
1227 tree.type = erasure(tree.type);
1228 } finally {
1229 make = savedMake;
1230 pt = savedPt;
1231 }
1232 } finally {
1233 env = oldEnv;
1234 }
1235 }
1236
1237 /** Translate a toplevel class definition.
1238 * @param cdef The definition to be translated.
1239 */
1240 public JCTree translateTopLevelClass(JCTree cdef, TreeMaker make) {
1241 // note that this method does NOT support recursion.
1242 this.make = make;
1243 pt = null;
1244 return translate(cdef, null);
1245 }
1246 }
--- EOF ---