1 /* 2 * Copyright (c) 1999, 2021, 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.tree; 27 28 import java.util.Iterator; 29 30 import com.sun.source.tree.CaseTree; 31 import com.sun.source.tree.ModuleTree.ModuleKind; 32 import com.sun.tools.javac.code.*; 33 import com.sun.tools.javac.code.Attribute.UnresolvedClass; 34 import com.sun.tools.javac.code.Symbol.*; 35 import com.sun.tools.javac.code.Type.*; 36 import com.sun.tools.javac.util.*; 37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 38 39 import com.sun.tools.javac.tree.JCTree.*; 40 41 import static com.sun.tools.javac.code.Flags.*; 42 import static com.sun.tools.javac.code.Kinds.Kind.*; 43 import static com.sun.tools.javac.code.TypeTag.*; 44 45 /** Factory class for trees. 46 * 47 * <p><b>This is NOT part of any supported API. 48 * If you write code that depends on this, you do so at your own risk. 49 * This code and its internal interfaces are subject to change or 50 * deletion without notice.</b> 51 */ 52 public class TreeMaker implements JCTree.Factory { 53 54 /** The context key for the tree factory. */ 55 protected static final Context.Key<TreeMaker> treeMakerKey = new Context.Key<>(); 56 57 /** Get the TreeMaker instance. */ 58 public static TreeMaker instance(Context context) { 59 TreeMaker instance = context.get(treeMakerKey); 60 if (instance == null) 61 instance = new TreeMaker(context); 62 return instance; 63 } 64 65 /** The position at which subsequent trees will be created. 66 */ 67 public int pos = Position.NOPOS; 68 69 /** The toplevel tree to which created trees belong. 70 */ 71 public JCCompilationUnit toplevel; 72 73 /** The current name table. */ 74 Names names; 75 76 Types types; 77 78 /** The current symbol table. */ 79 Symtab syms; 80 81 /** Create a tree maker with null toplevel and NOPOS as initial position. 82 */ 83 protected TreeMaker(Context context) { 84 context.put(treeMakerKey, this); 85 this.pos = Position.NOPOS; 86 this.toplevel = null; 87 this.names = Names.instance(context); 88 this.syms = Symtab.instance(context); 89 this.types = Types.instance(context); 90 } 91 92 /** Create a tree maker with a given toplevel and FIRSTPOS as initial position. 93 */ 94 protected TreeMaker(JCCompilationUnit toplevel, Names names, Types types, Symtab syms) { 95 this.pos = Position.FIRSTPOS; 96 this.toplevel = toplevel; 97 this.names = names; 98 this.types = types; 99 this.syms = syms; 100 } 101 102 /** Create a new tree maker for a given toplevel. 103 */ 104 public TreeMaker forToplevel(JCCompilationUnit toplevel) { 105 return new TreeMaker(toplevel, names, types, syms); 106 } 107 108 /** Reassign current position. 109 */ 110 public TreeMaker at(int pos) { 111 this.pos = pos; 112 return this; 113 } 114 115 /** Reassign current position. 116 */ 117 public TreeMaker at(DiagnosticPosition pos) { 118 this.pos = (pos == null ? Position.NOPOS : pos.getStartPosition()); 119 return this; 120 } 121 122 /** 123 * Create given tree node at current position. 124 * @param defs a list of PackageDef, ClassDef, Import, and Skip 125 */ 126 public JCCompilationUnit TopLevel(List<JCTree> defs) { 127 for (JCTree node : defs) 128 Assert.check(node instanceof JCClassDecl 129 || node instanceof JCPackageDecl 130 || node instanceof JCImport 131 || node instanceof JCModuleDecl 132 || node instanceof JCSkip 133 || node instanceof JCErroneous 134 || (node instanceof JCExpressionStatement expressionStatement 135 && expressionStatement.expr instanceof JCErroneous), 136 () -> node.getClass().getSimpleName()); 137 JCCompilationUnit tree = new JCCompilationUnit(defs); 138 tree.pos = pos; 139 return tree; 140 } 141 142 public JCPackageDecl PackageDecl(List<JCAnnotation> annotations, 143 JCExpression pid) { 144 Assert.checkNonNull(annotations); 145 Assert.checkNonNull(pid); 146 JCPackageDecl tree = new JCPackageDecl(annotations, pid); 147 tree.pos = pos; 148 return tree; 149 } 150 151 public JCImport Import(JCTree qualid, boolean importStatic) { 152 JCImport tree = new JCImport(qualid, importStatic); 153 tree.pos = pos; 154 return tree; 155 } 156 157 public JCClassDecl ClassDef(JCModifiers mods, 158 Name name, 159 List<JCTypeParameter> typarams, 160 JCExpression extending, 161 List<JCExpression> implementing, 162 List<JCTree> defs) 163 { 164 return ClassDef(mods, name, typarams, extending, implementing, List.nil(), defs); 165 } 166 167 public JCClassDecl ClassDef(JCModifiers mods, 168 Name name, 169 List<JCTypeParameter> typarams, 170 JCExpression extending, 171 List<JCExpression> implementing, 172 List<JCExpression> permitting, 173 List<JCTree> defs) 174 { 175 JCClassDecl tree = new JCClassDecl(mods, 176 name, 177 typarams, 178 extending, 179 implementing, 180 permitting, 181 defs, 182 null); 183 tree.pos = pos; 184 return tree; 185 } 186 187 public JCMethodDecl MethodDef(JCModifiers mods, 188 Name name, 189 JCExpression restype, 190 List<JCTypeParameter> typarams, 191 List<JCVariableDecl> params, 192 List<JCExpression> thrown, 193 JCBlock body, 194 JCExpression defaultValue) { 195 return MethodDef( 196 mods, name, restype, typarams, null, params, 197 thrown, body, defaultValue); 198 } 199 200 public JCMethodDecl MethodDef(JCModifiers mods, 201 Name name, 202 JCExpression restype, 203 List<JCTypeParameter> typarams, 204 JCVariableDecl recvparam, 205 List<JCVariableDecl> params, 206 List<JCExpression> thrown, 207 JCBlock body, 208 JCExpression defaultValue) 209 { 210 JCMethodDecl tree = new JCMethodDecl(mods, 211 name, 212 restype, 213 typarams, 214 recvparam, 215 params, 216 thrown, 217 body, 218 defaultValue, 219 null); 220 tree.pos = pos; 221 return tree; 222 } 223 224 public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init) { 225 JCVariableDecl tree = new JCVariableDecl(mods, name, vartype, init, null); 226 tree.pos = pos; 227 return tree; 228 } 229 230 public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init, boolean declaredUsingVar) { 231 JCVariableDecl tree = new JCVariableDecl(mods, name, vartype, init, null, declaredUsingVar); 232 tree.pos = pos; 233 return tree; 234 } 235 236 public JCVariableDecl ReceiverVarDef(JCModifiers mods, JCExpression name, JCExpression vartype) { 237 JCVariableDecl tree = new JCVariableDecl(mods, name, vartype); 238 tree.pos = pos; 239 return tree; 240 } 241 242 public JCSkip Skip() { 243 JCSkip tree = new JCSkip(); 244 tree.pos = pos; 245 return tree; 246 } 247 248 public JCBlock Block(long flags, List<JCStatement> stats) { 249 JCBlock tree = new JCBlock(flags, stats); 250 tree.pos = pos; 251 return tree; 252 } 253 254 public JCDoWhileLoop DoLoop(JCStatement body, JCExpression cond) { 255 JCDoWhileLoop tree = new JCDoWhileLoop(body, cond); 256 tree.pos = pos; 257 return tree; 258 } 259 260 public JCWhileLoop WhileLoop(JCExpression cond, JCStatement body) { 261 JCWhileLoop tree = new JCWhileLoop(cond, body); 262 tree.pos = pos; 263 return tree; 264 } 265 266 public JCForLoop ForLoop(List<JCStatement> init, 267 JCExpression cond, 268 List<JCExpressionStatement> step, 269 JCStatement body) 270 { 271 JCForLoop tree = new JCForLoop(init, cond, step, body); 272 tree.pos = pos; 273 return tree; 274 } 275 276 public JCEnhancedForLoop ForeachLoop(JCVariableDecl var, JCExpression expr, JCStatement body) { 277 JCEnhancedForLoop tree = new JCEnhancedForLoop(var, expr, body); 278 tree.pos = pos; 279 return tree; 280 } 281 282 public JCLabeledStatement Labelled(Name label, JCStatement body) { 283 JCLabeledStatement tree = new JCLabeledStatement(label, body); 284 tree.pos = pos; 285 return tree; 286 } 287 288 public JCSwitch Switch(JCExpression selector, List<JCCase> cases) { 289 JCSwitch tree = new JCSwitch(selector, cases); 290 tree.pos = pos; 291 return tree; 292 } 293 294 public JCCase Case(CaseTree.CaseKind caseKind, List<JCCaseLabel> labels, 295 List<JCStatement> stats, JCTree body) { 296 JCCase tree = new JCCase(caseKind, labels, stats, body); 297 tree.pos = pos; 298 return tree; 299 } 300 301 public JCSwitchExpression SwitchExpression(JCExpression selector, List<JCCase> cases) { 302 JCSwitchExpression tree = new JCSwitchExpression(selector, cases); 303 tree.pos = pos; 304 return tree; 305 } 306 307 public JCSynchronized Synchronized(JCExpression lock, JCBlock body) { 308 JCSynchronized tree = new JCSynchronized(lock, body); 309 tree.pos = pos; 310 return tree; 311 } 312 313 public JCTry Try(JCBlock body, List<JCCatch> catchers, JCBlock finalizer) { 314 return Try(List.nil(), body, catchers, finalizer); 315 } 316 317 public JCTry Try(List<JCTree> resources, 318 JCBlock body, 319 List<JCCatch> catchers, 320 JCBlock finalizer) { 321 JCTry tree = new JCTry(resources, body, catchers, finalizer); 322 tree.pos = pos; 323 return tree; 324 } 325 326 public JCCatch Catch(JCVariableDecl param, JCBlock body) { 327 JCCatch tree = new JCCatch(param, body); 328 tree.pos = pos; 329 return tree; 330 } 331 332 public JCConditional Conditional(JCExpression cond, 333 JCExpression thenpart, 334 JCExpression elsepart) 335 { 336 JCConditional tree = new JCConditional(cond, thenpart, elsepart); 337 tree.pos = pos; 338 return tree; 339 } 340 341 public JCIf If(JCExpression cond, JCStatement thenpart, JCStatement elsepart) { 342 JCIf tree = new JCIf(cond, thenpart, elsepart); 343 tree.pos = pos; 344 return tree; 345 } 346 347 public JCExpressionStatement Exec(JCExpression expr) { 348 JCExpressionStatement tree = new JCExpressionStatement(expr); 349 tree.pos = pos; 350 return tree; 351 } 352 353 public JCBreak Break(Name label) { 354 JCBreak tree = new JCBreak(label, null); 355 tree.pos = pos; 356 return tree; 357 } 358 359 public JCYield Yield(JCExpression value) { 360 JCYield tree = new JCYield(value, null); 361 tree.pos = pos; 362 return tree; 363 } 364 365 public JCContinue Continue(Name label) { 366 JCContinue tree = new JCContinue(label, null); 367 tree.pos = pos; 368 return tree; 369 } 370 371 public JCReturn Return(JCExpression expr) { 372 JCReturn tree = new JCReturn(expr); 373 tree.pos = pos; 374 return tree; 375 } 376 377 public JCThrow Throw(JCExpression expr) { 378 JCThrow tree = new JCThrow(expr); 379 tree.pos = pos; 380 return tree; 381 } 382 383 public JCAssert Assert(JCExpression cond, JCExpression detail) { 384 JCAssert tree = new JCAssert(cond, detail); 385 tree.pos = pos; 386 return tree; 387 } 388 389 public JCMethodInvocation Apply(List<JCExpression> typeargs, 390 JCExpression fn, 391 List<JCExpression> args) 392 { 393 JCMethodInvocation tree = new JCMethodInvocation(typeargs, fn, args); 394 tree.pos = pos; 395 return tree; 396 } 397 398 public JCNewClass NewClass(JCExpression encl, 399 List<JCExpression> typeargs, 400 JCExpression clazz, 401 List<JCExpression> args, 402 JCClassDecl def) 403 { 404 return SpeculativeNewClass(encl, typeargs, clazz, args, def, false); 405 } 406 407 public JCNewClass SpeculativeNewClass(JCExpression encl, 408 List<JCExpression> typeargs, 409 JCExpression clazz, 410 List<JCExpression> args, 411 JCClassDecl def, 412 boolean classDefRemoved) 413 { 414 JCNewClass tree = classDefRemoved ? 415 new JCNewClass(encl, typeargs, clazz, args, def) { 416 @Override 417 public boolean classDeclRemoved() { 418 return true; 419 } 420 } : 421 new JCNewClass(encl, typeargs, clazz, args, def); 422 tree.pos = pos; 423 return tree; 424 } 425 426 public JCNewArray NewArray(JCExpression elemtype, 427 List<JCExpression> dims, 428 List<JCExpression> elems) 429 { 430 JCNewArray tree = new JCNewArray(elemtype, dims, elems); 431 tree.pos = pos; 432 return tree; 433 } 434 435 public JCLambda Lambda(List<JCVariableDecl> params, 436 JCTree body) 437 { 438 JCLambda tree = new JCLambda(params, body); 439 tree.pos = pos; 440 return tree; 441 } 442 443 public JCParens Parens(JCExpression expr) { 444 JCParens tree = new JCParens(expr); 445 tree.pos = pos; 446 return tree; 447 } 448 449 public JCAssign Assign(JCExpression lhs, JCExpression rhs) { 450 JCAssign tree = new JCAssign(lhs, rhs); 451 tree.pos = pos; 452 return tree; 453 } 454 455 public JCAssignOp Assignop(JCTree.Tag opcode, JCTree lhs, JCTree rhs) { 456 JCAssignOp tree = new JCAssignOp(opcode, lhs, rhs, null); 457 tree.pos = pos; 458 return tree; 459 } 460 461 public JCUnary Unary(JCTree.Tag opcode, JCExpression arg) { 462 JCUnary tree = new JCUnary(opcode, arg); 463 tree.pos = pos; 464 return tree; 465 } 466 467 public JCBinary Binary(JCTree.Tag opcode, JCExpression lhs, JCExpression rhs) { 468 JCBinary tree = new JCBinary(opcode, lhs, rhs, null); 469 tree.pos = pos; 470 return tree; 471 } 472 473 public JCTypeCast TypeCast(JCTree clazz, JCExpression expr) { 474 JCTypeCast tree = new JCTypeCast(clazz, expr); 475 tree.pos = pos; 476 return tree; 477 } 478 479 public JCInstanceOf TypeTest(JCExpression expr, JCTree clazz) { 480 JCInstanceOf tree = new JCInstanceOf(expr, clazz); 481 tree.pos = pos; 482 return tree; 483 } 484 485 public JCBindingPattern BindingPattern(JCVariableDecl var) { 486 JCBindingPattern tree = new JCBindingPattern(var); 487 tree.pos = pos; 488 return tree; 489 } 490 491 public JCDefaultCaseLabel DefaultCaseLabel() { 492 JCDefaultCaseLabel tree = new JCDefaultCaseLabel(); 493 tree.pos = pos; 494 return tree; 495 } 496 497 public JCParenthesizedPattern ParenthesizedPattern(JCPattern pattern) { 498 JCParenthesizedPattern tree = new JCParenthesizedPattern(pattern); 499 tree.pos = pos; 500 return tree; 501 } 502 503 public JCGuardPattern GuardPattern(JCPattern guardedPattern, JCExpression expr) { 504 JCGuardPattern tree = new JCGuardPattern(guardedPattern, expr); 505 tree.pos = pos; 506 return tree; 507 } 508 509 public JCArrayAccess Indexed(JCExpression indexed, JCExpression index) { 510 JCArrayAccess tree = new JCArrayAccess(indexed, index); 511 tree.pos = pos; 512 return tree; 513 } 514 515 public JCFieldAccess Select(JCExpression selected, Name selector) { 516 JCFieldAccess tree = new JCFieldAccess(selected, selector, null); 517 tree.pos = pos; 518 return tree; 519 } 520 521 public JCMemberReference Reference(JCMemberReference.ReferenceMode mode, Name name, 522 JCExpression expr, List<JCExpression> typeargs) { 523 JCMemberReference tree = new JCMemberReference(mode, name, expr, typeargs); 524 tree.pos = pos; 525 return tree; 526 } 527 528 public JCIdent Ident(Name name) { 529 JCIdent tree = new JCIdent(name, null); 530 tree.pos = pos; 531 return tree; 532 } 533 534 public JCLiteral Literal(TypeTag tag, Object value) { 535 JCLiteral tree = new JCLiteral(tag, value); 536 tree.pos = pos; 537 return tree; 538 } 539 540 public JCPrimitiveTypeTree TypeIdent(TypeTag typetag) { 541 JCPrimitiveTypeTree tree = new JCPrimitiveTypeTree(typetag); 542 tree.pos = pos; 543 return tree; 544 } 545 546 public JCArrayTypeTree TypeArray(JCExpression elemtype) { 547 JCArrayTypeTree tree = new JCArrayTypeTree(elemtype); 548 tree.pos = pos; 549 return tree; 550 } 551 552 public JCTypeApply TypeApply(JCExpression clazz, List<JCExpression> arguments) { 553 JCTypeApply tree = new JCTypeApply(clazz, arguments); 554 tree.pos = pos; 555 return tree; 556 } 557 558 public JCTypeUnion TypeUnion(List<JCExpression> components) { 559 JCTypeUnion tree = new JCTypeUnion(components); 560 tree.pos = pos; 561 return tree; 562 } 563 564 public JCTypeIntersection TypeIntersection(List<JCExpression> components) { 565 JCTypeIntersection tree = new JCTypeIntersection(components); 566 tree.pos = pos; 567 return tree; 568 } 569 570 public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds) { 571 return TypeParameter(name, bounds, List.nil()); 572 } 573 574 public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds, List<JCAnnotation> annos) { 575 JCTypeParameter tree = new JCTypeParameter(name, bounds, annos); 576 tree.pos = pos; 577 return tree; 578 } 579 580 public JCWildcard Wildcard(TypeBoundKind kind, JCTree type) { 581 JCWildcard tree = new JCWildcard(kind, type); 582 tree.pos = pos; 583 return tree; 584 } 585 586 public TypeBoundKind TypeBoundKind(BoundKind kind) { 587 TypeBoundKind tree = new TypeBoundKind(kind); 588 tree.pos = pos; 589 return tree; 590 } 591 592 public JCAnnotation Annotation(JCTree annotationType, List<JCExpression> args) { 593 JCAnnotation tree = new JCAnnotation(Tag.ANNOTATION, annotationType, args); 594 tree.pos = pos; 595 return tree; 596 } 597 598 public JCAnnotation TypeAnnotation(JCTree annotationType, List<JCExpression> args) { 599 JCAnnotation tree = new JCAnnotation(Tag.TYPE_ANNOTATION, annotationType, args); 600 tree.pos = pos; 601 return tree; 602 } 603 604 public JCModifiers Modifiers(long flags, List<JCAnnotation> annotations) { 605 JCModifiers tree = new JCModifiers(flags, annotations); 606 boolean noFlags = (flags & (Flags.ModifierFlags | Flags.ANNOTATION)) == 0; 607 tree.pos = (noFlags && annotations.isEmpty()) ? Position.NOPOS : pos; 608 return tree; 609 } 610 611 public JCModifiers Modifiers(long flags) { 612 return Modifiers(flags, List.nil()); 613 } 614 615 @Override 616 public JCModuleDecl ModuleDef(JCModifiers mods, ModuleKind kind, 617 JCExpression qualid, List<JCDirective> directives) { 618 JCModuleDecl tree = new JCModuleDecl(mods, kind, qualid, directives); 619 tree.pos = pos; 620 return tree; 621 } 622 623 @Override 624 public JCExports Exports(JCExpression qualId, List<JCExpression> moduleNames) { 625 JCExports tree = new JCExports(qualId, moduleNames); 626 tree.pos = pos; 627 return tree; 628 } 629 630 @Override 631 public JCOpens Opens(JCExpression qualId, List<JCExpression> moduleNames) { 632 JCOpens tree = new JCOpens(qualId, moduleNames); 633 tree.pos = pos; 634 return tree; 635 } 636 637 @Override 638 public JCProvides Provides(JCExpression serviceName, List<JCExpression> implNames) { 639 JCProvides tree = new JCProvides(serviceName, implNames); 640 tree.pos = pos; 641 return tree; 642 } 643 644 @Override 645 public JCRequires Requires(boolean isTransitive, boolean isStaticPhase, JCExpression qualId) { 646 JCRequires tree = new JCRequires(isTransitive, isStaticPhase, qualId); 647 tree.pos = pos; 648 return tree; 649 } 650 651 @Override 652 public JCUses Uses(JCExpression qualId) { 653 JCUses tree = new JCUses(qualId); 654 tree.pos = pos; 655 return tree; 656 } 657 658 public JCAnnotatedType AnnotatedType(List<JCAnnotation> annotations, JCExpression underlyingType) { 659 JCAnnotatedType tree = new JCAnnotatedType(annotations, underlyingType); 660 tree.pos = pos; 661 return tree; 662 } 663 664 public JCErroneous Erroneous() { 665 return Erroneous(List.nil()); 666 } 667 668 public JCErroneous Erroneous(List<? extends JCTree> errs) { 669 JCErroneous tree = new JCErroneous(errs); 670 tree.pos = pos; 671 return tree; 672 } 673 674 public LetExpr LetExpr(List<JCStatement> defs, JCExpression expr) { 675 LetExpr tree = new LetExpr(defs, expr); 676 tree.pos = pos; 677 return tree; 678 } 679 680 /* *************************************************************************** 681 * Derived building blocks. 682 ****************************************************************************/ 683 684 public JCClassDecl AnonymousClassDef(JCModifiers mods, 685 List<JCTree> defs) 686 { 687 return ClassDef(mods, 688 names.empty, 689 List.nil(), 690 null, 691 List.nil(), 692 defs); 693 } 694 695 public LetExpr LetExpr(JCVariableDecl def, JCExpression expr) { 696 LetExpr tree = new LetExpr(List.of(def), expr); 697 tree.pos = pos; 698 return tree; 699 } 700 701 /** Create an identifier from a symbol. 702 */ 703 public JCIdent Ident(Symbol sym) { 704 return (JCIdent)new JCIdent((sym.name != names.empty) 705 ? sym.name 706 : sym.flatName(), sym) 707 .setPos(pos) 708 .setType(sym.type); 709 } 710 711 /** Create a selection node from a qualifier tree and a symbol. 712 * @param base The qualifier tree. 713 */ 714 public JCExpression Select(JCExpression base, Symbol sym) { 715 return new JCFieldAccess(base, sym.name, sym).setPos(pos).setType(sym.type); 716 } 717 718 /** Create a qualified identifier from a symbol, adding enough qualifications 719 * to make the reference unique. 720 */ 721 public JCExpression QualIdent(Symbol sym) { 722 return isUnqualifiable(sym) 723 ? Ident(sym) 724 : Select(QualIdent(sym.owner), sym); 725 } 726 727 /** Create an identifier that refers to the variable declared in given variable 728 * declaration. 729 */ 730 public JCExpression Ident(JCVariableDecl param) { 731 return Ident(param.sym); 732 } 733 734 /** Create a list of identifiers referring to the variables declared 735 * in given list of variable declarations. 736 */ 737 public List<JCExpression> Idents(List<JCVariableDecl> params) { 738 ListBuffer<JCExpression> ids = new ListBuffer<>(); 739 for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) 740 ids.append(Ident(l.head)); 741 return ids.toList(); 742 } 743 744 /** Create a tree representing `this', given its type. 745 */ 746 public JCExpression This(Type t) { 747 return Ident(new VarSymbol(FINAL, names._this, t, t.tsym)); 748 } 749 750 /** Create a tree representing qualified `this' given its type 751 */ 752 public JCExpression QualThis(Type t) { 753 return Select(Type(t), new VarSymbol(FINAL, names._this, t, t.tsym)); 754 } 755 756 /** Create a tree representing a class literal. 757 */ 758 public JCExpression ClassLiteral(ClassSymbol clazz) { 759 return ClassLiteral(clazz.type); 760 } 761 762 /** Create a tree representing a class literal. 763 */ 764 public JCExpression ClassLiteral(Type t) { 765 VarSymbol lit = new VarSymbol(STATIC | PUBLIC | FINAL, 766 names._class, 767 t, 768 t.tsym); 769 return Select(Type(t), lit); 770 } 771 772 /** Create a tree representing `super', given its type and owner. 773 */ 774 public JCIdent Super(Type t, TypeSymbol owner) { 775 return Ident(new VarSymbol(FINAL, names._super, t, owner)); 776 } 777 778 /** 779 * Create a method invocation from a method tree and a list of 780 * argument trees. 781 */ 782 public JCMethodInvocation App(JCExpression meth, List<JCExpression> args) { 783 return Apply(null, meth, args).setType(meth.type.getReturnType()); 784 } 785 786 /** 787 * Create a no-arg method invocation from a method tree 788 */ 789 public JCMethodInvocation App(JCExpression meth) { 790 return Apply(null, meth, List.nil()).setType(meth.type.getReturnType()); 791 } 792 793 /** Create a method invocation from a method tree and a list of argument trees. 794 */ 795 public JCExpression Create(Symbol ctor, List<JCExpression> args) { 796 Type t = ctor.owner.erasure(types); 797 JCNewClass newclass = NewClass(null, null, Type(t), args, null); 798 newclass.constructor = ctor; 799 newclass.setType(t); 800 return newclass; 801 } 802 803 /** Create a tree representing given type. 804 */ 805 public JCExpression Type(Type t) { 806 if (t == null) return null; 807 JCExpression tp; 808 switch (t.getTag()) { 809 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: 810 case DOUBLE: case BOOLEAN: case VOID: 811 tp = TypeIdent(t.getTag()); 812 break; 813 case TYPEVAR: 814 tp = Ident(t.tsym); 815 break; 816 case WILDCARD: { 817 WildcardType a = ((WildcardType) t); 818 tp = Wildcard(TypeBoundKind(a.kind), a.kind == BoundKind.UNBOUND ? null : Type(a.type)); 819 break; 820 } 821 case CLASS: 822 switch (t.getKind()) { 823 case UNION: { 824 UnionClassType tu = (UnionClassType)t; 825 ListBuffer<JCExpression> la = new ListBuffer<>(); 826 for (Type ta : tu.getAlternativeTypes()) { 827 la.add(Type(ta)); 828 } 829 tp = TypeUnion(la.toList()); 830 break; 831 } 832 case INTERSECTION: { 833 IntersectionClassType it = (IntersectionClassType)t; 834 ListBuffer<JCExpression> la = new ListBuffer<>(); 835 for (Type ta : it.getExplicitComponents()) { 836 la.add(Type(ta)); 837 } 838 tp = TypeIntersection(la.toList()); 839 break; 840 } 841 default: { 842 Type outer = t.getEnclosingType(); 843 JCExpression clazz = outer.hasTag(CLASS) && t.tsym.owner.kind == TYP 844 ? Select(Type(outer), t.tsym) 845 : QualIdent(t.tsym); 846 tp = t.getTypeArguments().isEmpty() 847 ? clazz 848 : TypeApply(clazz, Types(t.getTypeArguments())); 849 break; 850 } 851 } 852 break; 853 case ARRAY: 854 tp = TypeArray(Type(types.elemtype(t))); 855 break; 856 case ERROR: 857 tp = TypeIdent(ERROR); 858 break; 859 default: 860 throw new AssertionError("unexpected type: " + t); 861 } 862 return tp.setType(t); 863 } 864 865 /** Create a list of trees representing given list of types. 866 */ 867 public List<JCExpression> Types(List<Type> ts) { 868 ListBuffer<JCExpression> lb = new ListBuffer<>(); 869 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 870 lb.append(Type(l.head)); 871 return lb.toList(); 872 } 873 874 /** Create a variable definition from a variable symbol and an initializer 875 * expression. 876 */ 877 public JCVariableDecl VarDef(VarSymbol v, JCExpression init) { 878 return (JCVariableDecl) 879 new JCVariableDecl( 880 Modifiers(v.flags(), Annotations(v.getRawAttributes())), 881 v.name, 882 Type(v.type), 883 init, 884 v).setPos(pos).setType(v.type); 885 } 886 887 /** Create annotation trees from annotations. 888 */ 889 public List<JCAnnotation> Annotations(List<Attribute.Compound> attributes) { 890 if (attributes == null) return List.nil(); 891 ListBuffer<JCAnnotation> result = new ListBuffer<>(); 892 for (List<Attribute.Compound> i = attributes; i.nonEmpty(); i=i.tail) { 893 Attribute a = i.head; 894 result.append(Annotation(a)); 895 } 896 return result.toList(); 897 } 898 899 public JCLiteral Literal(Object value) { 900 JCLiteral result = null; 901 if (value instanceof String) { 902 result = Literal(CLASS, value). 903 setType(syms.stringType.constType(value)); 904 } else if (value instanceof Integer) { 905 result = Literal(INT, value). 906 setType(syms.intType.constType(value)); 907 } else if (value instanceof Long) { 908 result = Literal(LONG, value). 909 setType(syms.longType.constType(value)); 910 } else if (value instanceof Byte) { 911 result = Literal(BYTE, value). 912 setType(syms.byteType.constType(value)); 913 } else if (value instanceof Character charVal) { 914 int v = charVal.toString().charAt(0); 915 result = Literal(CHAR, v). 916 setType(syms.charType.constType(v)); 917 } else if (value instanceof Double) { 918 result = Literal(DOUBLE, value). 919 setType(syms.doubleType.constType(value)); 920 } else if (value instanceof Float) { 921 result = Literal(FLOAT, value). 922 setType(syms.floatType.constType(value)); 923 } else if (value instanceof Short) { 924 result = Literal(SHORT, value). 925 setType(syms.shortType.constType(value)); 926 } else if (value instanceof Boolean boolVal) { 927 int v = boolVal ? 1 : 0; 928 result = Literal(BOOLEAN, v). 929 setType(syms.booleanType.constType(v)); 930 } else { 931 throw new AssertionError(value); 932 } 933 return result; 934 } 935 936 class AnnotationBuilder implements Attribute.Visitor { 937 JCExpression result = null; 938 public void visitConstant(Attribute.Constant v) { 939 result = Literal(v.type.getTag(), v.value); 940 } 941 public void visitClass(Attribute.Class clazz) { 942 result = ClassLiteral(clazz.classType).setType(syms.classType); 943 } 944 public void visitEnum(Attribute.Enum e) { 945 result = QualIdent(e.value); 946 } 947 public void visitError(Attribute.Error e) { 948 if (e instanceof UnresolvedClass unresolvedClass) { 949 result = ClassLiteral(unresolvedClass.classType).setType(syms.classType); 950 } else { 951 result = Erroneous(); 952 } 953 } 954 public void visitCompound(Attribute.Compound compound) { 955 if (compound instanceof Attribute.TypeCompound typeCompound) { 956 result = visitTypeCompoundInternal(typeCompound); 957 } else { 958 result = visitCompoundInternal(compound); 959 } 960 } 961 public JCAnnotation visitCompoundInternal(Attribute.Compound compound) { 962 ListBuffer<JCExpression> args = new ListBuffer<>(); 963 for (List<Pair<Symbol.MethodSymbol,Attribute>> values = compound.values; values.nonEmpty(); values=values.tail) { 964 Pair<MethodSymbol,Attribute> pair = values.head; 965 JCExpression valueTree = translate(pair.snd); 966 args.append(Assign(Ident(pair.fst), valueTree).setType(valueTree.type)); 967 } 968 return Annotation(Type(compound.type), args.toList()); 969 } 970 public JCAnnotation visitTypeCompoundInternal(Attribute.TypeCompound compound) { 971 ListBuffer<JCExpression> args = new ListBuffer<>(); 972 for (List<Pair<Symbol.MethodSymbol,Attribute>> values = compound.values; values.nonEmpty(); values=values.tail) { 973 Pair<MethodSymbol,Attribute> pair = values.head; 974 JCExpression valueTree = translate(pair.snd); 975 args.append(Assign(Ident(pair.fst), valueTree).setType(valueTree.type)); 976 } 977 return TypeAnnotation(Type(compound.type), args.toList()); 978 } 979 public void visitArray(Attribute.Array array) { 980 ListBuffer<JCExpression> elems = new ListBuffer<>(); 981 for (int i = 0; i < array.values.length; i++) 982 elems.append(translate(array.values[i])); 983 result = NewArray(null, List.nil(), elems.toList()).setType(array.type); 984 } 985 JCExpression translate(Attribute a) { 986 a.accept(this); 987 return result; 988 } 989 JCAnnotation translate(Attribute.Compound a) { 990 return visitCompoundInternal(a); 991 } 992 JCAnnotation translate(Attribute.TypeCompound a) { 993 return visitTypeCompoundInternal(a); 994 } 995 } 996 997 AnnotationBuilder annotationBuilder = new AnnotationBuilder(); 998 999 /** Create an annotation tree from an attribute. 1000 */ 1001 public JCAnnotation Annotation(Attribute a) { 1002 return annotationBuilder.translate((Attribute.Compound)a); 1003 } 1004 1005 public JCAnnotation TypeAnnotation(Attribute a) { 1006 return annotationBuilder.translate((Attribute.TypeCompound) a); 1007 } 1008 1009 /** Create a method definition from a method symbol and a method body. 1010 */ 1011 public JCMethodDecl MethodDef(MethodSymbol m, JCBlock body) { 1012 return MethodDef(m, m.type, body); 1013 } 1014 1015 /** Create a method definition from a method symbol, method type 1016 * and a method body. 1017 */ 1018 public JCMethodDecl MethodDef(MethodSymbol m, Type mtype, JCBlock body) { 1019 return (JCMethodDecl) 1020 new JCMethodDecl( 1021 Modifiers(m.flags(), Annotations(m.getRawAttributes())), 1022 m.name, 1023 m.name != names.init ? Type(mtype.getReturnType()) : null, 1024 TypeParams(mtype.getTypeArguments()), 1025 null, // receiver type 1026 Params(mtype.getParameterTypes(), m), 1027 Types(mtype.getThrownTypes()), 1028 body, 1029 null, 1030 m).setPos(pos).setType(mtype); 1031 } 1032 1033 /** Create a type parameter tree from its name and type. 1034 */ 1035 public JCTypeParameter TypeParam(Name name, TypeVar tvar) { 1036 return (JCTypeParameter) 1037 TypeParameter(name, Types(types.getBounds(tvar))).setPos(pos).setType(tvar); 1038 } 1039 1040 /** Create a list of type parameter trees from a list of type variables. 1041 */ 1042 public List<JCTypeParameter> TypeParams(List<Type> typarams) { 1043 ListBuffer<JCTypeParameter> tparams = new ListBuffer<>(); 1044 for (List<Type> l = typarams; l.nonEmpty(); l = l.tail) 1045 tparams.append(TypeParam(l.head.tsym.name, (TypeVar)l.head)); 1046 return tparams.toList(); 1047 } 1048 1049 /** Create a value parameter tree from its name, type, and owner. 1050 */ 1051 public JCVariableDecl Param(Name name, Type argtype, Symbol owner) { 1052 return VarDef(new VarSymbol(PARAMETER, name, argtype, owner), null); 1053 } 1054 1055 /** Create a a list of value parameter trees x0, ..., xn from a list of 1056 * their types and an their owner. 1057 */ 1058 public List<JCVariableDecl> Params(List<Type> argtypes, Symbol owner) { 1059 ListBuffer<JCVariableDecl> params = new ListBuffer<>(); 1060 MethodSymbol mth = (owner.kind == MTH) ? ((MethodSymbol)owner) : null; 1061 if (mth != null && mth.params != null && argtypes.length() == mth.params.length()) { 1062 for (VarSymbol param : ((MethodSymbol)owner).params) 1063 params.append(VarDef(param, null)); 1064 } else { 1065 int i = 0; 1066 for (List<Type> l = argtypes; l.nonEmpty(); l = l.tail) 1067 params.append(Param(paramName(i++), l.head, owner)); 1068 } 1069 return params.toList(); 1070 } 1071 1072 /** Wrap a method invocation in an expression statement or return statement, 1073 * depending on whether the method invocation expression's type is void. 1074 */ 1075 public JCStatement Call(JCExpression apply) { 1076 return apply.type.hasTag(VOID) ? Exec(apply) : Return(apply); 1077 } 1078 1079 /** Construct an assignment from a variable symbol and a right hand side. 1080 */ 1081 public JCStatement Assignment(Symbol v, JCExpression rhs) { 1082 return Exec(Assign(Ident(v), rhs).setType(v.type)); 1083 } 1084 1085 /** Construct an index expression from a variable and an expression. 1086 */ 1087 public JCArrayAccess Indexed(Symbol v, JCExpression index) { 1088 JCArrayAccess tree = new JCArrayAccess(QualIdent(v), index); 1089 tree.type = ((ArrayType)v.type).elemtype; 1090 return tree; 1091 } 1092 1093 /** Make an attributed type cast expression. 1094 */ 1095 public JCTypeCast TypeCast(Type type, JCExpression expr) { 1096 return (JCTypeCast)TypeCast(Type(type), expr).setType(type); 1097 } 1098 1099 /* *************************************************************************** 1100 * Helper methods. 1101 ****************************************************************************/ 1102 1103 /** Can given symbol be referred to in unqualified form? 1104 */ 1105 boolean isUnqualifiable(Symbol sym) { 1106 if (sym.name == names.empty || 1107 sym.owner == null || 1108 sym.owner == syms.rootPackage || 1109 sym.owner.kind == MTH || sym.owner.kind == VAR) { 1110 return true; 1111 } else if (sym.kind == TYP && toplevel != null) { 1112 Iterator<Symbol> it = toplevel.namedImportScope.getSymbolsByName(sym.name).iterator(); 1113 if (it.hasNext()) { 1114 Symbol s = it.next(); 1115 return 1116 s == sym && 1117 !it.hasNext(); 1118 } 1119 it = toplevel.packge.members().getSymbolsByName(sym.name).iterator(); 1120 if (it.hasNext()) { 1121 Symbol s = it.next(); 1122 return 1123 s == sym && 1124 !it.hasNext(); 1125 } 1126 it = toplevel.starImportScope.getSymbolsByName(sym.name).iterator(); 1127 if (it.hasNext()) { 1128 Symbol s = it.next(); 1129 return 1130 s == sym && 1131 !it.hasNext(); 1132 } 1133 } 1134 return false; 1135 } 1136 1137 /** The name of synthetic parameter number `i'. 1138 */ 1139 public Name paramName(int i) { return names.fromString("x" + i); } 1140 1141 /** The name of synthetic type parameter number `i'. 1142 */ 1143 public Name typaramName(int i) { return names.fromString("A" + i); } 1144 }