1 /*
   2  * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import com.sun.tools.javac.code.Flags;
  29 import com.sun.tools.javac.code.Symbol.VarSymbol;
  30 import com.sun.tools.javac.code.Symtab;
  31 import com.sun.tools.javac.code.Type;
  32 import com.sun.tools.javac.code.Types;
  33 import com.sun.tools.javac.comp.MatchBindingsComputer.BindingSymbol;
  34 import com.sun.tools.javac.tree.JCTree;
  35 import com.sun.tools.javac.tree.JCTree.JCAssign;
  36 import com.sun.tools.javac.tree.JCTree.JCBinary;
  37 import com.sun.tools.javac.tree.JCTree.JCConditional;
  38 import com.sun.tools.javac.tree.JCTree.JCExpression;
  39 import com.sun.tools.javac.tree.JCTree.JCForLoop;
  40 import com.sun.tools.javac.tree.JCTree.JCIdent;
  41 import com.sun.tools.javac.tree.JCTree.JCIf;
  42 import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
  43 import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
  44 import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
  45 import com.sun.tools.javac.tree.JCTree.JCStatement;
  46 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
  47 import com.sun.tools.javac.tree.JCTree.JCBindingPattern;
  48 import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
  49 import com.sun.tools.javac.tree.JCTree.Tag;
  50 import com.sun.tools.javac.tree.TreeMaker;
  51 import com.sun.tools.javac.tree.TreeTranslator;
  52 import com.sun.tools.javac.util.Assert;
  53 import com.sun.tools.javac.util.Context;
  54 import com.sun.tools.javac.util.List;
  55 import com.sun.tools.javac.util.ListBuffer;
  56 import com.sun.tools.javac.util.Log;
  57 import com.sun.tools.javac.util.Names;
  58 import com.sun.tools.javac.util.Options;
  59 
  60 import java.util.Map;
  61 import java.util.Map.Entry;
  62 import java.util.stream.Collectors;
  63 
  64 import com.sun.tools.javac.code.Symbol.MethodSymbol;
  65 import static com.sun.tools.javac.code.TypeTag.BOOLEAN;
  66 import static com.sun.tools.javac.code.TypeTag.BOT;
  67 import com.sun.tools.javac.comp.MatchBindingsComputer.BindingSymbol;
  68 import com.sun.tools.javac.jvm.Target;
  69 import com.sun.tools.javac.tree.JCTree.JCBlock;
  70 import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
  71 import com.sun.tools.javac.tree.JCTree.JCStatement;
  72 import com.sun.tools.javac.util.List;
  73 
  74 /**
  75  * This pass translates pattern-matching constructs, such as instanceof <pattern>.
  76  */
  77 public class TransPatterns extends TreeTranslator {
  78 
  79     protected static final Context.Key<TransPatterns> transPatternsKey = new Context.Key<>();
  80 
  81     public static TransPatterns instance(Context context) {
  82         TransPatterns instance = context.get(transPatternsKey);
  83         if (instance == null)
  84             instance = new TransPatterns(context);
  85         return instance;
  86     }
  87 
  88     private final Symtab syms;
  89     private final Types types;
  90     private final Operators operators;
  91     private final Log log;
  92     private final ConstFold constFold;
  93     private final Names names;
  94     private final Target target;
  95     private final MatchBindingsComputer matchBindingsComputer;
  96     private TreeMaker make;
  97 
  98     BindingContext bindingContext = new BindingContext() {
  99         @Override
 100         VarSymbol getBindingFor(BindingSymbol varSymbol) {
 101             return null;
 102         }
 103 
 104         @Override
 105         JCStatement decorateStatement(JCStatement stat) {
 106             return stat;
 107         }
 108 
 109         @Override
 110         JCExpression decorateExpression(JCExpression expr) {
 111             return expr;
 112         }
 113 
 114         @Override
 115         BindingContext pop() {
 116             //do nothing
 117             return this;
 118         }
 119 
 120         @Override
 121         boolean tryPrepend(BindingSymbol binding, JCVariableDecl var) {
 122             return false;
 123         }
 124     };
 125 
 126     JCLabeledStatement pendingMatchLabel = null;
 127 
 128     boolean debugTransPatterns;
 129 
 130     private MethodSymbol currentMethodSym = null;
 131 
 132     protected TransPatterns(Context context) {
 133         context.put(transPatternsKey, this);
 134         syms = Symtab.instance(context);
 135         make = TreeMaker.instance(context);
 136         types = Types.instance(context);
 137         operators = Operators.instance(context);
 138         log = Log.instance(context);
 139         constFold = ConstFold.instance(context);
 140         names = Names.instance(context);
 141         target = Target.instance(context);
 142         matchBindingsComputer = MatchBindingsComputer.instance(context);
 143         debugTransPatterns = Options.instance(context).isSet("debug.patterns");
 144     }
 145 
 146     @Override
 147     public void visitTypeTest(JCInstanceOf tree) {
 148         if (tree.pattern.hasTag(Tag.BINDINGPATTERN)) {
 149             JCBindingPattern patt = (JCBindingPattern)tree.pattern;
 150             VarSymbol pattSym = patt.symbol;
 151             Type tempType = tree.expr.type.hasTag(BOT) ?
 152                     syms.objectType
 153                     : tree.expr.type;
 154             VarSymbol temp = new VarSymbol(pattSym.flags() | Flags.SYNTHETIC,
 155                     names.fromString(pattSym.name.toString() + target.syntheticNameChar() + "temp"),
 156                     tempType,
 157                     patt.symbol.owner);
 158             JCExpression translatedExpr = translate(tree.expr);
 159             Type castTargetType = types.boxedTypeOrType(pattSym.erasure(types));
 160             if (patt.vartype == null || tree.expr.type.isPrimitive()) {
 161                 result = make.Literal(BOOLEAN,1).setType(syms.booleanType);
 162             } else {
 163                 result = makeTypeTest(make.Ident(temp), make.Type(castTargetType));
 164             }
 165 
 166             VarSymbol bindingVar = bindingContext.getBindingFor(patt.symbol);
 167             if (bindingVar != null) {
 168                 JCAssign fakeInit = (JCAssign)make.at(tree.pos).Assign(
 169                         make.Ident(bindingVar), convert(make.Ident(temp), castTargetType)).setType(bindingVar.erasure(types));
 170                 result = makeBinary(Tag.AND, (JCExpression)result,
 171                         makeBinary(Tag.EQ, fakeInit, convert(make.Ident(temp), castTargetType)));
 172             }
 173             result = make.at(tree.pos).LetExpr(make.VarDef(temp, translatedExpr), (JCExpression)result).setType(syms.booleanType);
 174         } else {
 175             super.visitTypeTest(tree);
 176         }
 177     }
 178 
 179     @Override
 180     public void visitBinary(JCBinary tree) {
 181         List<BindingSymbol> matchBindings;
 182         switch (tree.getTag()) {
 183             case AND:
 184                 matchBindings = matchBindingsComputer.getMatchBindings(tree.lhs, true);
 185                 break;
 186             case OR:
 187                 matchBindings = matchBindingsComputer.getMatchBindings(tree.lhs, false);
 188                 break;
 189             default:
 190                 matchBindings = List.nil();
 191                 break;
 192         }
 193 
 194         bindingContext = new BasicBindingContext(matchBindings);
 195         try {
 196             super.visitBinary(tree);
 197             result = bindingContext.decorateExpression(tree);
 198         } finally {
 199             bindingContext.pop();
 200         }
 201     }
 202 
 203     @Override
 204     public void visitConditional(JCConditional tree) {
 205         bindingContext = new BasicBindingContext(
 206                 matchBindingsComputer.getMatchBindings(tree.cond, true)
 207                         .appendList(matchBindingsComputer.getMatchBindings(tree.cond, false)));
 208         try {
 209             super.visitConditional(tree);
 210             result = bindingContext.decorateExpression(tree);
 211         } finally {
 212             bindingContext.pop();
 213         }
 214     }
 215 
 216     @Override
 217     public void visitIf(JCIf tree) {
 218         bindingContext = new BasicBindingContext(getMatchBindings(tree.cond));
 219         try {
 220             super.visitIf(tree);
 221             result = bindingContext.decorateStatement(tree);
 222         } finally {
 223             bindingContext.pop();
 224         }
 225     }
 226 
 227     @Override
 228     public void visitForLoop(JCForLoop tree) {
 229         bindingContext = new BasicBindingContext(getMatchBindings(tree.cond));
 230         try {
 231             super.visitForLoop(tree);
 232             result = bindingContext.decorateStatement(tree);
 233         } finally {
 234             bindingContext.pop();
 235         }
 236     }
 237 
 238     @Override
 239     public void visitWhileLoop(JCWhileLoop tree) {
 240         bindingContext = new BasicBindingContext(getMatchBindings(tree.cond));
 241         try {
 242             super.visitWhileLoop(tree);
 243             result = bindingContext.decorateStatement(tree);
 244         } finally {
 245             bindingContext.pop();
 246         }
 247     }
 248 
 249     @Override
 250     public void visitDoLoop(JCDoWhileLoop tree) {
 251         bindingContext = new BasicBindingContext(getMatchBindings(tree.cond));
 252         try {
 253             super.visitDoLoop(tree);
 254             result = bindingContext.decorateStatement(tree);
 255         } finally {
 256             bindingContext.pop();
 257         }
 258     }
 259 
 260     @Override
 261     public void visitMethodDef(JCMethodDecl tree) {
 262         MethodSymbol prevMethodSym = currentMethodSym;
 263         try {
 264             currentMethodSym = tree.sym;
 265             super.visitMethodDef(tree);
 266         } finally {
 267             currentMethodSym = prevMethodSym;
 268         }
 269     }
 270 
 271     @Override
 272     public void visitIdent(JCIdent tree) {
 273         VarSymbol bindingVar = null;
 274         if ((tree.sym.flags() & Flags.MATCH_BINDING) != 0) {
 275             bindingVar = bindingContext.getBindingFor((BindingSymbol)tree.sym);
 276         }
 277         if (bindingVar == null) {
 278             super.visitIdent(tree);
 279         } else {
 280             result = make.at(tree.pos).Ident(bindingVar);
 281         }
 282     }
 283 
 284     @Override
 285     public void visitBlock(JCBlock tree) {
 286         ListBuffer<JCStatement> statements = new ListBuffer<>();
 287         bindingContext = new BasicBindingContext(List.nil()) {
 288             boolean tryPrepend(BindingSymbol binding, JCVariableDecl var) {
 289                 hoistedVarMap.put(binding, var.sym);
 290                 statements.append(var);
 291                 return true;
 292             }
 293         };
 294         try {
 295             for (List<JCStatement> l = tree.stats; l.nonEmpty(); l = l.tail) {
 296                 statements.append(translate(l.head));
 297             }
 298 
 299             tree.stats = statements.toList();
 300             result = tree;
 301         } finally {
 302             bindingContext.pop();
 303         }
 304     }
 305 
 306     public JCTree translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
 307         try {
 308             this.make = make;
 309             translate(cdef);
 310         } finally {
 311             // note that recursive invocations of this method fail hard
 312             this.make = null;
 313         }
 314 
 315         if (debugTransPatterns) {
 316             System.err.println(cdef);
 317         }
 318         return cdef;
 319     }
 320 
 321     /** Make an instanceof expression.
 322      *  @param lhs      The expression.
 323      *  @param type     The type to be tested.
 324      */
 325 
 326     JCInstanceOf makeTypeTest(JCExpression lhs, JCExpression type) {
 327         JCInstanceOf tree = make.TypeTest(lhs, type);
 328         tree.type = syms.booleanType;
 329         return tree;
 330     }
 331 
 332     /** Make an attributed binary expression (copied from Lower).
 333      *  @param optag    The operators tree tag.
 334      *  @param lhs      The operator's left argument.
 335      *  @param rhs      The operator's right argument.
 336      */
 337     JCBinary makeBinary(JCTree.Tag optag, JCExpression lhs, JCExpression rhs) {
 338         JCBinary tree = make.Binary(optag, lhs, rhs);
 339         tree.operator = operators.resolveBinary(tree, optag, lhs.type, rhs.type);
 340         tree.type = tree.operator.type.getReturnType();
 341         return tree;
 342     }
 343 
 344     JCExpression convert(JCExpression expr, Type target) {
 345         JCExpression result = make.at(expr.pos()).TypeCast(make.Type(target), expr);
 346         result.type = (expr.type.constValue() != null) ?
 347                 constFold.coerce(expr.type, target) : target;
 348         return result;
 349     }
 350 
 351     JCExpression makeDefaultValue(int pos, Type type) {
 352         if (type.isReference()) {
 353             return make.at(pos).Literal(BOT, null).setType(syms.botType);
 354         } else {
 355             final Object value;
 356             switch (type.getTag()) {
 357                 case BYTE:
 358                     value = (byte)0;
 359                     break;
 360                 case SHORT:
 361                     value = (short)0;
 362                     break;
 363                 case INT:
 364                     value = 0;
 365                     break;
 366                 case FLOAT:
 367                     value = 0f;
 368                     break;
 369                 case LONG:
 370                     value = 0L;
 371                     break;
 372                 case DOUBLE:
 373                     value = 0D;
 374                     break;
 375                 case CHAR:
 376                     value = (char)0;
 377                     break;
 378                 case BOOLEAN:
 379                     value = false;
 380                     break;
 381                 default:
 382                     Assert.error();
 383                     return null;
 384             }
 385             return make.at(pos).Literal(value);
 386         }
 387     }
 388 
 389     private List<BindingSymbol> getMatchBindings(JCExpression cond) {
 390         return matchBindingsComputer.getMatchBindings(cond, true)
 391                         .appendList(matchBindingsComputer.getMatchBindings(cond, false));
 392     }
 393     abstract class BindingContext {
 394         abstract VarSymbol getBindingFor(BindingSymbol varSymbol);
 395         abstract JCStatement decorateStatement(JCStatement stat);
 396         abstract JCExpression decorateExpression(JCExpression expr);
 397         abstract BindingContext pop();
 398         abstract boolean tryPrepend(BindingSymbol binding, JCVariableDecl var);
 399     }
 400 
 401     class BasicBindingContext extends BindingContext {
 402         List<BindingSymbol> matchBindings;
 403         Map<BindingSymbol, VarSymbol> hoistedVarMap;
 404         BindingContext parent;
 405 
 406         public BasicBindingContext(List<BindingSymbol> matchBindings) {
 407             this.matchBindings = matchBindings;
 408             this.parent = bindingContext;
 409             this.hoistedVarMap = matchBindings.stream()
 410                     .filter(v -> parent.getBindingFor(v) == null)
 411                     .collect(Collectors.toMap(v -> v, v -> new VarSymbol(v.flags(), v.name, v.type, v.owner)));
 412         }
 413 
 414         @Override
 415         VarSymbol getBindingFor(BindingSymbol varSymbol) {
 416             VarSymbol res = parent.getBindingFor(varSymbol);
 417             if (res != null) {
 418                 return res;
 419             }
 420             return hoistedVarMap.entrySet().stream()
 421                     .filter(e -> e.getKey().isAliasFor(varSymbol))
 422                     .findFirst()
 423                     .map(e -> e.getValue()).orElse(null);
 424         }
 425 
 426         @Override
 427         JCStatement decorateStatement(JCStatement stat) {
 428             if (hoistedVarMap.isEmpty()) return stat;
 429             ListBuffer<JCStatement> stats = new ListBuffer<>();
 430             for (Entry<BindingSymbol, VarSymbol> e : hoistedVarMap.entrySet()) {
 431                 JCVariableDecl decl = makeHoistedVarDecl(stat.pos, e.getValue());
 432                 if (!e.getKey().isPreserved() ||
 433                     !parent.tryPrepend(e.getKey(), decl)) {
 434                     stats.add(decl);
 435                 }
 436             }
 437             if (stats.nonEmpty()) {
 438                 stats.add(stat);
 439                 stat = make.at(stat.pos).Block(0, stats.toList());
 440             }
 441             return stat;
 442         }
 443 
 444         @Override
 445         JCExpression decorateExpression(JCExpression expr) {
 446             for (VarSymbol vsym : hoistedVarMap.values()) {
 447                 expr = make.at(expr.pos).LetExpr(makeHoistedVarDecl(expr.pos, vsym), expr).setType(expr.type);
 448             }
 449             return expr;
 450         }
 451 
 452         @Override
 453         BindingContext pop() {
 454             return bindingContext = parent;
 455         }
 456 
 457         @Override
 458         boolean tryPrepend(BindingSymbol binding, JCVariableDecl var) {
 459             return false;
 460         }
 461 
 462         private JCVariableDecl makeHoistedVarDecl(int pos, VarSymbol varSymbol) {
 463             return make.at(pos).VarDef(varSymbol, makeDefaultValue(pos, varSymbol.erasure(types)));
 464         }
 465     }
 466 }