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