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