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         return SpeculativeNewClass(encl, typeargs, clazz, args, def, false);
 382     }
 383 
 384     public JCNewClass SpeculativeNewClass(JCExpression encl,
 385                              List<JCExpression> typeargs,
 386                              JCExpression clazz,
 387                              List<JCExpression> args,
 388                              JCClassDecl def,
 389                              boolean classDefRemoved)
 390     {
 391         JCNewClass tree = classDefRemoved ?
 392                 new JCNewClass(encl, typeargs, clazz, args, def) {
 393                     @Override
 394                     public boolean classDeclRemoved() {
 395                         return true;
 396                     }
 397                 } :
 398                 new JCNewClass(encl, typeargs, clazz, args, def);
 399         tree.pos = pos;
 400         return tree;
 401     }
 402 
 403     public JCNewArray NewArray(JCExpression elemtype,
 404                              List<JCExpression> dims,
 405                              List<JCExpression> elems)
 406     {
 407         JCNewArray tree = new JCNewArray(elemtype, dims, elems);
 408         tree.pos = pos;
 409         return tree;
 410     }
 411 
 412     public JCLambda Lambda(List<JCVariableDecl> params,
 413                            JCTree body)
 414     {
 415         JCLambda tree = new JCLambda(params, body);
 416         tree.pos = pos;
 417         return tree;
 418     }
 419 
 420     public JCParens Parens(JCExpression expr) {
 421         JCParens tree = new JCParens(expr);
 422         tree.pos = pos;
 423         return tree;
 424     }
 425 
 426     public JCAssign Assign(JCExpression lhs, JCExpression rhs) {
 427         JCAssign tree = new JCAssign(lhs, rhs);
 428         tree.pos = pos;
 429         return tree;
 430     }
 431 
 432     public JCAssignOp Assignop(JCTree.Tag opcode, JCTree lhs, JCTree rhs) {
 433         JCAssignOp tree = new JCAssignOp(opcode, lhs, rhs, null);
 434         tree.pos = pos;
 435         return tree;
 436     }
 437 
 438     public JCUnary Unary(JCTree.Tag opcode, JCExpression arg) {
 439         JCUnary tree = new JCUnary(opcode, arg);
 440         tree.pos = pos;
 441         return tree;
 442     }
 443 
 444     public JCBinary Binary(JCTree.Tag opcode, JCExpression lhs, JCExpression rhs) {
 445         JCBinary tree = new JCBinary(opcode, lhs, rhs, null);
 446         tree.pos = pos;
 447         return tree;
 448     }
 449 
 450     public JCTypeCast TypeCast(JCTree clazz, JCExpression expr) {
 451         JCTypeCast tree = new JCTypeCast(clazz, expr);
 452         tree.pos = pos;
 453         return tree;
 454     }
 455 
 456     public JCInstanceOf TypeTest(JCExpression expr, JCTree clazz) {
 457         JCInstanceOf tree = new JCInstanceOf(expr, clazz);
 458         tree.pos = pos;
 459         return tree;
 460     }
 461 
 462     public JCArrayAccess Indexed(JCExpression indexed, JCExpression index) {
 463         JCArrayAccess tree = new JCArrayAccess(indexed, index);
 464         tree.pos = pos;
 465         return tree;
 466     }
 467 
 468     public JCFieldAccess Select(JCExpression selected, Name selector) {
 469         JCFieldAccess tree = new JCFieldAccess(selected, selector, null);
 470         tree.pos = pos;
 471         return tree;
 472     }
 473 
 474     public JCMemberReference Reference(JCMemberReference.ReferenceMode mode, Name name,
 475             JCExpression expr, List<JCExpression> typeargs) {
 476         JCMemberReference tree = new JCMemberReference(mode, name, expr, typeargs);
 477         tree.pos = pos;
 478         return tree;
 479     }
 480 
 481     public JCIdent Ident(Name name) {
 482         JCIdent tree = new JCIdent(name, null);
 483         tree.pos = pos;
 484         return tree;
 485     }
 486 
 487     public JCLiteral Literal(TypeTag tag, Object value) {
 488         JCLiteral tree = new JCLiteral(tag, value);
 489         tree.pos = pos;
 490         return tree;
 491     }
 492 
 493     public JCPrimitiveTypeTree TypeIdent(TypeTag typetag) {
 494         JCPrimitiveTypeTree tree = new JCPrimitiveTypeTree(typetag);
 495         tree.pos = pos;
 496         return tree;
 497     }
 498 
 499     public JCArrayTypeTree TypeArray(JCExpression elemtype) {
 500         JCArrayTypeTree tree = new JCArrayTypeTree(elemtype);
 501         tree.pos = pos;
 502         return tree;
 503     }
 504 
 505     public JCTypeApply TypeApply(JCExpression clazz, List<JCExpression> arguments) {
 506         JCTypeApply tree = new JCTypeApply(clazz, arguments);
 507         tree.pos = pos;
 508         return tree;
 509     }
 510 
 511     public JCTypeUnion TypeUnion(List<JCExpression> components) {
 512         JCTypeUnion tree = new JCTypeUnion(components);
 513         tree.pos = pos;
 514         return tree;
 515     }
 516 
 517     public JCTypeIntersection TypeIntersection(List<JCExpression> components) {
 518         JCTypeIntersection tree = new JCTypeIntersection(components);
 519         tree.pos = pos;
 520         return tree;
 521     }
 522 
 523     public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds) {
 524         return TypeParameter(name, bounds, List.nil());
 525     }
 526 
 527     public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds, List<JCAnnotation> annos) {
 528         JCTypeParameter tree = new JCTypeParameter(name, bounds, annos);
 529         tree.pos = pos;
 530         return tree;
 531     }
 532 
 533     public JCWildcard Wildcard(TypeBoundKind kind, JCTree type) {
 534         JCWildcard tree = new JCWildcard(kind, type);
 535         tree.pos = pos;
 536         return tree;
 537     }
 538 
 539     public TypeBoundKind TypeBoundKind(BoundKind kind) {
 540         TypeBoundKind tree = new TypeBoundKind(kind);
 541         tree.pos = pos;
 542         return tree;
 543     }
 544 
 545     public JCAnnotation Annotation(JCTree annotationType, List<JCExpression> args) {
 546         JCAnnotation tree = new JCAnnotation(Tag.ANNOTATION, annotationType, args);
 547         tree.pos = pos;
 548         return tree;
 549     }
 550 
 551     public JCAnnotation TypeAnnotation(JCTree annotationType, List<JCExpression> args) {
 552         JCAnnotation tree = new JCAnnotation(Tag.TYPE_ANNOTATION, annotationType, args);
 553         tree.pos = pos;
 554         return tree;
 555     }
 556 
 557     public JCModifiers Modifiers(long flags, List<JCAnnotation> annotations) {
 558         JCModifiers tree = new JCModifiers(flags, annotations);
 559         boolean noFlags = (flags & (Flags.ModifierFlags | Flags.ANNOTATION)) == 0;
 560         tree.pos = (noFlags && annotations.isEmpty()) ? Position.NOPOS : pos;
 561         return tree;
 562     }
 563 
 564     public JCModifiers Modifiers(long flags) {
 565         return Modifiers(flags, List.nil());
 566     }
 567 
 568     @Override
 569     public JCModuleDecl ModuleDef(JCModifiers mods, ModuleKind kind,
 570             JCExpression qualid, List<JCDirective> directives) {
 571         JCModuleDecl tree = new JCModuleDecl(mods, kind, qualid, directives);
 572         tree.pos = pos;
 573         return tree;
 574     }
 575 
 576     @Override
 577     public JCExports Exports(JCExpression qualId, List<JCExpression> moduleNames) {
 578         JCExports tree = new JCExports(qualId, moduleNames);
 579         tree.pos = pos;
 580         return tree;
 581     }
 582 
 583     @Override
 584     public JCOpens Opens(JCExpression qualId, List<JCExpression> moduleNames) {
 585         JCOpens tree = new JCOpens(qualId, moduleNames);
 586         tree.pos = pos;
 587         return tree;
 588     }
 589 
 590     @Override
 591     public JCProvides Provides(JCExpression serviceName, List<JCExpression> implNames) {
 592         JCProvides tree = new JCProvides(serviceName, implNames);
 593         tree.pos = pos;
 594         return tree;
 595     }
 596 
 597     @Override
 598     public JCRequires Requires(boolean isTransitive, boolean isStaticPhase, JCExpression qualId) {
 599         JCRequires tree = new JCRequires(isTransitive, isStaticPhase, qualId);
 600         tree.pos = pos;
 601         return tree;
 602     }
 603 
 604     @Override
 605     public JCUses Uses(JCExpression qualId) {
 606         JCUses tree = new JCUses(qualId);
 607         tree.pos = pos;
 608         return tree;
 609     }
 610 
 611     public JCAnnotatedType AnnotatedType(List<JCAnnotation> annotations, JCExpression underlyingType) {
 612         JCAnnotatedType tree = new JCAnnotatedType(annotations, underlyingType);
 613         tree.pos = pos;
 614         return tree;
 615     }
 616 
 617     public JCErroneous Erroneous() {
 618         return Erroneous(List.nil());
 619     }
 620 
 621     public JCErroneous Erroneous(List<? extends JCTree> errs) {
 622         JCErroneous tree = new JCErroneous(errs);
 623         tree.pos = pos;
 624         return tree;
 625     }
 626 
 627     public LetExpr LetExpr(List<JCStatement> defs, JCExpression expr) {
 628         LetExpr tree = new LetExpr(defs, expr);
 629         tree.pos = pos;
 630         return tree;
 631     }
 632 
 633 /* ***************************************************************************
 634  * Derived building blocks.
 635  ****************************************************************************/
 636 
 637     public JCClassDecl AnonymousClassDef(JCModifiers mods,
 638                                          List<JCTree> defs)
 639     {
 640         return ClassDef(mods,
 641                         names.empty,
 642                         List.nil(),
 643                         null,
 644                         List.nil(),
 645                         defs);
 646     }
 647 
 648     public LetExpr LetExpr(JCVariableDecl def, JCExpression expr) {
 649         LetExpr tree = new LetExpr(List.of(def), expr);
 650         tree.pos = pos;
 651         return tree;
 652     }
 653 
 654     /** Create an identifier from a symbol.
 655      */
 656     public JCIdent Ident(Symbol sym) {
 657         return (JCIdent)new JCIdent((sym.name != names.empty)
 658                                 ? sym.name
 659                                 : sym.flatName(), sym)
 660             .setPos(pos)
 661             .setType(sym.type);
 662     }
 663 
 664     /** Create a selection node from a qualifier tree and a symbol.
 665      *  @param base   The qualifier tree.
 666      */
 667     public JCExpression Select(JCExpression base, Symbol sym) {
 668         return new JCFieldAccess(base, sym.name, sym).setPos(pos).setType(sym.type);
 669     }
 670 
 671     /** Create a qualified identifier from a symbol, adding enough qualifications
 672      *  to make the reference unique.
 673      */
 674     public JCExpression QualIdent(Symbol sym) {
 675         return isUnqualifiable(sym)
 676             ? Ident(sym)
 677             : Select(QualIdent(sym.owner), sym);
 678     }
 679 
 680     /** Create an identifier that refers to the variable declared in given variable
 681      *  declaration.
 682      */
 683     public JCExpression Ident(JCVariableDecl param) {
 684         return Ident(param.sym);
 685     }
 686 
 687     /** Create a list of identifiers referring to the variables declared
 688      *  in given list of variable declarations.
 689      */
 690     public List<JCExpression> Idents(List<JCVariableDecl> params) {
 691         ListBuffer<JCExpression> ids = new ListBuffer<>();
 692         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail)
 693             ids.append(Ident(l.head));
 694         return ids.toList();
 695     }
 696 
 697     /** Create a tree representing `this', given its type.
 698      */
 699     public JCExpression This(Type t) {
 700         return Ident(new VarSymbol(FINAL, names._this, t, t.tsym));
 701     }
 702 
 703     /** Create a tree representing qualified `this' given its type
 704      */
 705     public JCExpression QualThis(Type t) {
 706         return Select(Type(t), new VarSymbol(FINAL, names._this, t, t.tsym));
 707     }
 708 
 709     /** Create a tree representing a class literal.
 710      */
 711     public JCExpression ClassLiteral(ClassSymbol clazz) {
 712         return ClassLiteral(clazz.type);
 713     }
 714 
 715     /** Create a tree representing a class literal.
 716      */
 717     public JCExpression ClassLiteral(Type t) {
 718         VarSymbol lit = new VarSymbol(STATIC | PUBLIC | FINAL,
 719                                       names._class,
 720                                       t,
 721                                       t.tsym);
 722         return Select(Type(t), lit);
 723     }
 724 
 725     /** Create a tree representing `super', given its type and owner.
 726      */
 727     public JCIdent Super(Type t, TypeSymbol owner) {
 728         return Ident(new VarSymbol(FINAL, names._super, t, owner));
 729     }
 730 
 731     /**
 732      * Create a method invocation from a method tree and a list of
 733      * argument trees.
 734      */
 735     public JCMethodInvocation App(JCExpression meth, List<JCExpression> args) {
 736         return Apply(null, meth, args).setType(meth.type.getReturnType());
 737     }
 738 
 739     /**
 740      * Create a no-arg method invocation from a method tree
 741      */
 742     public JCMethodInvocation App(JCExpression meth) {
 743         return Apply(null, meth, List.nil()).setType(meth.type.getReturnType());
 744     }
 745 
 746     /** Create a method invocation from a method tree and a list of argument trees.
 747      */
 748     public JCExpression Create(Symbol ctor, List<JCExpression> args) {
 749         Type t = ctor.owner.erasure(types);
 750         JCNewClass newclass = NewClass(null, null, Type(t), args, null);
 751         newclass.constructor = ctor;
 752         newclass.setType(t);
 753         return newclass;
 754     }
 755 
 756     /** Create a tree representing given type.
 757      */
 758     public JCExpression Type(Type t) {
 759         if (t == null) return null;
 760         JCExpression tp;
 761         switch (t.getTag()) {
 762         case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
 763         case DOUBLE: case BOOLEAN: case VOID:
 764             tp = TypeIdent(t.getTag());
 765             break;
 766         case TYPEVAR:
 767             tp = Ident(t.tsym);
 768             break;
 769         case WILDCARD: {
 770             WildcardType a = ((WildcardType) t);
 771             tp = Wildcard(TypeBoundKind(a.kind), a.kind == BoundKind.UNBOUND ? null : Type(a.type));
 772             break;
 773         }
 774         case CLASS:
 775             switch (t.getKind()) {
 776             case UNION: {
 777                 UnionClassType tu = (UnionClassType)t;
 778                 ListBuffer<JCExpression> la = new ListBuffer<>();
 779                 for (Type ta : tu.getAlternativeTypes()) {
 780                     la.add(Type(ta));
 781                 }
 782                 tp = TypeUnion(la.toList());
 783                 break;
 784             }
 785             case INTERSECTION: {
 786                 IntersectionClassType it = (IntersectionClassType)t;
 787                 ListBuffer<JCExpression> la = new ListBuffer<>();
 788                 for (Type ta : it.getExplicitComponents()) {
 789                     la.add(Type(ta));
 790                 }
 791                 tp = TypeIntersection(la.toList());
 792                 break;
 793             }
 794             default: {
 795                 Type outer = t.getEnclosingType();
 796                 JCExpression clazz = outer.hasTag(CLASS) && t.tsym.owner.kind == TYP
 797                         ? Select(Type(outer), t.tsym)
 798                         : QualIdent(t.tsym);
 799                 tp = t.getTypeArguments().isEmpty()
 800                         ? clazz
 801                         : TypeApply(clazz, Types(t.getTypeArguments()));
 802                 break;
 803             }
 804             }
 805             break;
 806         case ARRAY:
 807             tp = TypeArray(Type(types.elemtype(t)));
 808             break;
 809         case ERROR:
 810             tp = TypeIdent(ERROR);
 811             break;
 812         default:
 813             throw new AssertionError("unexpected type: " + t);
 814         }
 815         return tp.setType(t);
 816     }
 817 
 818     /** Create a list of trees representing given list of types.
 819      */
 820     public List<JCExpression> Types(List<Type> ts) {
 821         ListBuffer<JCExpression> lb = new ListBuffer<>();
 822         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
 823             lb.append(Type(l.head));
 824         return lb.toList();
 825     }
 826 
 827     /** Create a variable definition from a variable symbol and an initializer
 828      *  expression.
 829      */
 830     public JCVariableDecl VarDef(VarSymbol v, JCExpression init) {
 831         return (JCVariableDecl)
 832             new JCVariableDecl(
 833                 Modifiers(v.flags(), Annotations(v.getRawAttributes())),
 834                 v.name,
 835                 Type(v.type),
 836                 init,
 837                 v).setPos(pos).setType(v.type);
 838     }
 839 
 840     /** Create annotation trees from annotations.
 841      */
 842     public List<JCAnnotation> Annotations(List<Attribute.Compound> attributes) {
 843         if (attributes == null) return List.nil();
 844         ListBuffer<JCAnnotation> result = new ListBuffer<>();
 845         for (List<Attribute.Compound> i = attributes; i.nonEmpty(); i=i.tail) {
 846             Attribute a = i.head;
 847             result.append(Annotation(a));
 848         }
 849         return result.toList();
 850     }
 851 
 852     public JCLiteral Literal(Object value) {
 853         JCLiteral result = null;
 854         if (value instanceof String) {
 855             result = Literal(CLASS, value).
 856                 setType(syms.stringType.constType(value));
 857         } else if (value instanceof Integer) {
 858             result = Literal(INT, value).
 859                 setType(syms.intType.constType(value));
 860         } else if (value instanceof Long) {
 861             result = Literal(LONG, value).
 862                 setType(syms.longType.constType(value));
 863         } else if (value instanceof Byte) {
 864             result = Literal(BYTE, value).
 865                 setType(syms.byteType.constType(value));
 866         } else if (value instanceof Character) {
 867             int v = (int) (((Character) value).toString().charAt(0));
 868             result = Literal(CHAR, v).
 869                 setType(syms.charType.constType(v));
 870         } else if (value instanceof Double) {
 871             result = Literal(DOUBLE, value).
 872                 setType(syms.doubleType.constType(value));
 873         } else if (value instanceof Float) {
 874             result = Literal(FLOAT, value).
 875                 setType(syms.floatType.constType(value));
 876         } else if (value instanceof Short) {
 877             result = Literal(SHORT, value).
 878                 setType(syms.shortType.constType(value));
 879         } else if (value instanceof Boolean) {
 880             int v = ((Boolean) value) ? 1 : 0;
 881             result = Literal(BOOLEAN, v).
 882                 setType(syms.booleanType.constType(v));
 883         } else {
 884             throw new AssertionError(value);
 885         }
 886         return result;
 887     }
 888 
 889     class AnnotationBuilder implements Attribute.Visitor {
 890         JCExpression result = null;
 891         public void visitConstant(Attribute.Constant v) {
 892             result = Literal(v.type.getTag(), v.value);
 893         }
 894         public void visitClass(Attribute.Class clazz) {
 895             result = ClassLiteral(clazz.classType).setType(syms.classType);
 896         }
 897         public void visitEnum(Attribute.Enum e) {
 898             result = QualIdent(e.value);
 899         }
 900         public void visitError(Attribute.Error e) {
 901             if (e instanceof UnresolvedClass) {
 902                 result = ClassLiteral(((UnresolvedClass) e).classType).setType(syms.classType);
 903             } else {
 904                 result = Erroneous();
 905             }
 906         }
 907         public void visitCompound(Attribute.Compound compound) {
 908             if (compound instanceof Attribute.TypeCompound) {
 909                 result = visitTypeCompoundInternal((Attribute.TypeCompound) compound);
 910             } else {
 911                 result = visitCompoundInternal(compound);
 912             }
 913         }
 914         public JCAnnotation visitCompoundInternal(Attribute.Compound compound) {
 915             ListBuffer<JCExpression> args = new ListBuffer<>();
 916             for (List<Pair<Symbol.MethodSymbol,Attribute>> values = compound.values; values.nonEmpty(); values=values.tail) {
 917                 Pair<MethodSymbol,Attribute> pair = values.head;
 918                 JCExpression valueTree = translate(pair.snd);
 919                 args.append(Assign(Ident(pair.fst), valueTree).setType(valueTree.type));
 920             }
 921             return Annotation(Type(compound.type), args.toList());
 922         }
 923         public JCAnnotation visitTypeCompoundInternal(Attribute.TypeCompound compound) {
 924             ListBuffer<JCExpression> args = new ListBuffer<>();
 925             for (List<Pair<Symbol.MethodSymbol,Attribute>> values = compound.values; values.nonEmpty(); values=values.tail) {
 926                 Pair<MethodSymbol,Attribute> pair = values.head;
 927                 JCExpression valueTree = translate(pair.snd);
 928                 args.append(Assign(Ident(pair.fst), valueTree).setType(valueTree.type));
 929             }
 930             return TypeAnnotation(Type(compound.type), args.toList());
 931         }
 932         public void visitArray(Attribute.Array array) {
 933             ListBuffer<JCExpression> elems = new ListBuffer<>();
 934             for (int i = 0; i < array.values.length; i++)
 935                 elems.append(translate(array.values[i]));
 936             result = NewArray(null, List.nil(), elems.toList()).setType(array.type);
 937         }
 938         JCExpression translate(Attribute a) {
 939             a.accept(this);
 940             return result;
 941         }
 942         JCAnnotation translate(Attribute.Compound a) {
 943             return visitCompoundInternal(a);
 944         }
 945         JCAnnotation translate(Attribute.TypeCompound a) {
 946             return visitTypeCompoundInternal(a);
 947         }
 948     }
 949 
 950     AnnotationBuilder annotationBuilder = new AnnotationBuilder();
 951 
 952     /** Create an annotation tree from an attribute.
 953      */
 954     public JCAnnotation Annotation(Attribute a) {
 955         return annotationBuilder.translate((Attribute.Compound)a);
 956     }
 957 
 958     public JCAnnotation TypeAnnotation(Attribute a) {
 959         return annotationBuilder.translate((Attribute.TypeCompound) a);
 960     }
 961 
 962     /** Create a method definition from a method symbol and a method body.
 963      */
 964     public JCMethodDecl MethodDef(MethodSymbol m, JCBlock body) {
 965         return MethodDef(m, m.type, body);
 966     }
 967 
 968     /** Create a method definition from a method symbol, method type
 969      *  and a method body.
 970      */
 971     public JCMethodDecl MethodDef(MethodSymbol m, Type mtype, JCBlock body) {
 972         return (JCMethodDecl)
 973             new JCMethodDecl(
 974                 Modifiers(m.flags(), Annotations(m.getRawAttributes())),
 975                 m.name,
 976                 Type(mtype.getReturnType()),
 977                 TypeParams(mtype.getTypeArguments()),
 978                 null, // receiver type
 979                 Params(mtype.getParameterTypes(), m),
 980                 Types(mtype.getThrownTypes()),
 981                 body,
 982                 null,
 983                 m).setPos(pos).setType(mtype);
 984     }
 985 
 986     /** Create a type parameter tree from its name and type.
 987      */
 988     public JCTypeParameter TypeParam(Name name, TypeVar tvar) {
 989         return (JCTypeParameter)
 990             TypeParameter(name, Types(types.getBounds(tvar))).setPos(pos).setType(tvar);
 991     }
 992 
 993     /** Create a list of type parameter trees from a list of type variables.
 994      */
 995     public List<JCTypeParameter> TypeParams(List<Type> typarams) {
 996         ListBuffer<JCTypeParameter> tparams = new ListBuffer<>();
 997         for (List<Type> l = typarams; l.nonEmpty(); l = l.tail)
 998             tparams.append(TypeParam(l.head.tsym.name, (TypeVar)l.head));
 999         return tparams.toList();
1000     }
1001 
1002     /** Create a value parameter tree from its name, type, and owner.
1003      */
1004     public JCVariableDecl Param(Name name, Type argtype, Symbol owner) {
1005         return VarDef(new VarSymbol(PARAMETER, name, argtype, owner), null);
1006     }
1007 
1008     /** Create a a list of value parameter trees x0, ..., xn from a list of
1009      *  their types and an their owner.
1010      */
1011     public List<JCVariableDecl> Params(List<Type> argtypes, Symbol owner) {
1012         ListBuffer<JCVariableDecl> params = new ListBuffer<>();
1013         MethodSymbol mth = (owner.kind == MTH) ? ((MethodSymbol)owner) : null;
1014         if (mth != null && mth.params != null && argtypes.length() == mth.params.length()) {
1015             for (VarSymbol param : ((MethodSymbol)owner).params)
1016                 params.append(VarDef(param, null));
1017         } else {
1018             int i = 0;
1019             for (List<Type> l = argtypes; l.nonEmpty(); l = l.tail)
1020                 params.append(Param(paramName(i++), l.head, owner));
1021         }
1022         return params.toList();
1023     }
1024 
1025     /** Wrap a method invocation in an expression statement or return statement,
1026      *  depending on whether the method invocation expression's type is void.
1027      */
1028     public JCStatement Call(JCExpression apply) {
1029         return apply.type.hasTag(VOID) ? Exec(apply) : Return(apply);
1030     }
1031 
1032     /** Construct an assignment from a variable symbol and a right hand side.
1033      */
1034     public JCStatement Assignment(Symbol v, JCExpression rhs) {
1035         return Exec(Assign(Ident(v), rhs).setType(v.type));
1036     }
1037 
1038     /** Construct an index expression from a variable and an expression.
1039      */
1040     public JCArrayAccess Indexed(Symbol v, JCExpression index) {
1041         JCArrayAccess tree = new JCArrayAccess(QualIdent(v), index);
1042         tree.type = ((ArrayType)v.type).elemtype;
1043         return tree;
1044     }
1045 
1046     /** Make an attributed type cast expression.
1047      */
1048     public JCTypeCast TypeCast(Type type, JCExpression expr) {
1049         return (JCTypeCast)TypeCast(Type(type), expr).setType(type);
1050     }
1051 
1052 /* ***************************************************************************
1053  * Helper methods.
1054  ****************************************************************************/
1055 
1056     /** Can given symbol be referred to in unqualified form?
1057      */
1058     boolean isUnqualifiable(Symbol sym) {
1059         if (sym.name == names.empty ||
1060             sym.owner == null ||
1061             sym.owner == syms.rootPackage ||
1062             sym.owner.kind == MTH || sym.owner.kind == VAR) {
1063             return true;
1064         } else if (sym.kind == TYP && toplevel != null) {
1065             Iterator<Symbol> it = toplevel.namedImportScope.getSymbolsByName(sym.name).iterator();
1066             if (it.hasNext()) {
1067                 Symbol s = it.next();
1068                 return
1069                   s == sym &&
1070                   !it.hasNext();
1071             }
1072             it = toplevel.packge.members().getSymbolsByName(sym.name).iterator();
1073             if (it.hasNext()) {
1074                 Symbol s = it.next();
1075                 return
1076                   s == sym &&
1077                   !it.hasNext();
1078             }
1079             it = toplevel.starImportScope.getSymbolsByName(sym.name).iterator();
1080             if (it.hasNext()) {
1081                 Symbol s = it.next();
1082                 return
1083                   s == sym &&
1084                   !it.hasNext();
1085             }
1086         }
1087         return false;
1088     }
1089 
1090     /** The name of synthetic parameter number `i'.
1091      */
1092     public Name paramName(int i)   { return names.fromString("x" + i); }
1093 
1094     /** The name of synthetic type parameter number `i'.
1095      */
1096     public Name typaramName(int i) { return names.fromString("A" + i); }
1097 }