1 /*
   2  * Copyright (c) 2016, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import java.io.File;
  25 import java.io.IOException;
  26 import java.util.Arrays;
  27 import java.util.HashMap;
  28 import java.util.Locale;
  29 import java.util.Map;
  30 
  31 import javax.lang.model.element.Element;
  32 import javax.lang.model.element.ElementKind;
  33 import javax.lang.model.type.TypeMirror;
  34 import javax.tools.JavaCompiler;
  35 import javax.tools.JavaFileObject;
  36 import javax.tools.StandardJavaFileManager;
  37 import javax.tools.ToolProvider;
  38 
  39 import com.sun.source.tree.CompilationUnitTree;
  40 import com.sun.source.tree.Tree;
  41 import com.sun.source.tree.VariableTree;
  42 import com.sun.source.util.JavacTask;
  43 import com.sun.source.util.TreePathScanner;
  44 import com.sun.tools.javac.api.JavacTaskImpl;
  45 import com.sun.tools.javac.api.JavacTrees;
  46 import com.sun.tools.javac.code.Printer;
  47 import com.sun.tools.javac.code.Type;
  48 import com.sun.tools.javac.code.Type.CapturedType;
  49 import com.sun.tools.javac.code.Type.ClassType;
  50 import com.sun.tools.javac.code.Types;
  51 import com.sun.tools.javac.util.Log;
  52 
  53 import static javax.tools.StandardLocation.SOURCE_PATH;
  54 
  55 public class LocalVariableInferenceTester {
  56 
  57     static final StandardJavaFileManager fm;
  58 
  59     static {
  60         final JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
  61         fm = comp.getStandardFileManager(null, null, null);
  62         File destDir = new File(System.getProperty("user.dir"));
  63         try {
  64             fm.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
  65         } catch (IOException ex) {
  66             throw new AssertionError(ex);
  67         }
  68     }
  69 
  70     public static void main(String[] args) throws IOException {
  71         try {
  72             if (args.length != 1) {
  73                 System.err.println("Usage: LocalVariableInferenceTester <sourcefile>");
  74                 System.exit(1);
  75             }
  76             File path = new File(System.getProperty("test.src"));
  77             fm.setLocation(SOURCE_PATH, Arrays.asList(path));
  78             File input = new File(path, args[0]);
  79             JavaFileObject jfo = fm.getJavaFileObjects(input).iterator().next();
  80             new LocalVariableInferenceTester().compileAndCheck(jfo);
  81         } finally {
  82             fm.close();
  83         }
  84     }
  85 
  86     int errors = 0;
  87     int checks = 0;
  88 
  89     void compileAndCheck(JavaFileObject input) throws IOException {
  90         JavaCompiler c = ToolProvider.getSystemJavaCompiler();
  91         JavacTask task = (JavacTask) c.getTask(null, fm, null, Arrays.asList("-g"), null, Arrays.asList(input));
  92         JavacTrees trees = JavacTrees.instance(task);
  93         Types types = Types.instance(((JavacTaskImpl)task).getContext());
  94         Iterable<? extends CompilationUnitTree> roots = task.parse();
  95         Log log = Log.instance(((JavacTaskImpl)task).getContext());
  96         //force code generation (to shake out non-denotable issues)
  97         boolean hasClasses = task.generate().iterator().hasNext();
  98         if (!hasClasses) {
  99             throw new AssertionError("Errors occurred during compilation!");
 100         }
 101         errors += log.nerrors;
 102         new LocalVarTypeChecker(trees, types).scan(roots, null);
 103         System.err.println("Checks executed: " + checks);
 104         if (errors != 0) {
 105             throw new AssertionError("Errors were found");
 106         }
 107     }
 108 
 109     void error(Tree node, String msg) {
 110         System.err.println(node);
 111         System.err.println("ERROR: " + msg);
 112         errors++;
 113     }
 114 
 115     class LocalVarTypeChecker extends TreePathScanner<Void, Void> {
 116 
 117         JavacTrees trees;
 118         Types types;
 119 
 120         LocalVarTypeChecker(JavacTrees trees, Types types) {
 121             this.trees = trees;
 122             this.types = types;
 123         }
 124 
 125         @Override
 126         public Void visitVariable(VariableTree node, Void aVoid) {
 127             Element e = trees.getElement(getCurrentPath());
 128             if (e.getKind() == ElementKind.LOCAL_VARIABLE) {
 129                 TypeMirror type = e.asType();
 130                 InferredType inferredAnno = e.getAnnotation(InferredType.class);
 131                 if (inferredAnno != null) {
 132                     checks++;
 133                     String req = inferredAnno.value();
 134                     String found = new TypePrinter().visit((Type)type, null);
 135                     if (!req.equals(found)) {
 136                         error(node, "Inferred type mismatch; expected: " + req + " - found: " + found);
 137                     }
 138                 }
 139             }
 140             return super.visitVariable(node, null);
 141         }
 142 
 143         class TypePrinter extends Printer {
 144 
 145             Map<Type, Integer> capturedIdMap = new HashMap<>();
 146 
 147             @Override
 148             protected String localize(Locale locale, String key, Object... args) {
 149                 throw new UnsupportedOperationException();
 150             }
 151 
 152             @Override
 153             public String visitCapturedType(CapturedType t, Locale locale) {
 154                 return "CAP#" + capturedVarId(t, locale);
 155             }
 156 
 157             @Override
 158             protected String capturedVarId(CapturedType t, Locale locale) {
 159                 return String.valueOf(capturedIdMap.getOrDefault(t, capturedIdMap.size()));
 160             }
 161 
 162             @Override
 163             public String visitClassType(ClassType t, Locale locale) {
 164                 if (!t.isCompound() && t.tsym.name.isEmpty()) {
 165                     return "#ANON(" + types.directSupertypes(t) + ")";
 166                 } else if (t.isCompound()) {
 167                     return "#INT(" + types.directSupertypes(t) + ")";
 168                 } else {
 169                     return super.visitClassType(t, locale);
 170                 }
 171             }
 172         }
 173     }
 174 }