7029150: Project Coin: present union types from the tree API through to javax.lang.model
authorjjg
Thu, 28 Apr 2011 15:05:36 -0700
changeset 9599 0996df19ea87
parent 9598 ccb5261834f2
child 9600 1cfd668d5426
7029150: Project Coin: present union types from the tree API through to javax.lang.model Reviewed-by: mcimadamore
langtools/src/share/classes/com/sun/source/util/Trees.java
langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java
langtools/src/share/classes/com/sun/tools/javac/code/Type.java
langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java
langtools/src/share/classes/com/sun/tools/javac/model/JavacTypes.java
langtools/test/tools/javac/multicatch/model/Model01.java
langtools/test/tools/javac/multicatch/model/ModelChecker.java
langtools/test/tools/javac/multicatch/model/UnionTypeInfo.java
langtools/test/tools/javac/processing/model/type/TestUnionType.java
--- a/langtools/src/share/classes/com/sun/source/util/Trees.java	Thu Apr 28 08:46:06 2011 -0700
+++ b/langtools/src/share/classes/com/sun/source/util/Trees.java	Thu Apr 28 15:05:36 2011 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,6 +38,7 @@
 import javax.tools.Diagnostic;
 import javax.tools.JavaCompiler.CompilationTask;
 
+import com.sun.source.tree.CatchTree;
 import com.sun.source.tree.ClassTree;
 import com.sun.source.tree.CompilationUnitTree;
 import com.sun.source.tree.MethodTree;
@@ -207,4 +208,11 @@
     public abstract void printMessage(Diagnostic.Kind kind, CharSequence msg,
             com.sun.source.tree.Tree t,
             com.sun.source.tree.CompilationUnitTree root);
+
+    /**
+     * Gets the lub of an exception parameter declared in a catch clause.
+     * @param tree the tree for the catch clause
+     * @return The lub of the exception parameter
+     */
+    public abstract TypeMirror getLub(CatchTree tree);
 }
--- a/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java	Thu Apr 28 08:46:06 2011 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java	Thu Apr 28 15:05:36 2011 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,11 +34,13 @@
 import javax.lang.model.element.ExecutableElement;
 import javax.lang.model.element.TypeElement;
 import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
 import javax.lang.model.type.TypeMirror;
 import javax.tools.Diagnostic;
 import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 
+import com.sun.source.tree.CatchTree;
 import com.sun.source.tree.CompilationUnitTree;
 import com.sun.source.tree.Scope;
 import com.sun.source.tree.Tree;
@@ -49,7 +51,7 @@
 import com.sun.tools.javac.code.Symbol.ClassSymbol;
 import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import com.sun.tools.javac.code.Symbol;
-import com.sun.tools.javac.code.Type;
+import com.sun.tools.javac.code.Type.UnionClassType;
 import com.sun.tools.javac.comp.Attr;
 import com.sun.tools.javac.comp.AttrContext;
 import com.sun.tools.javac.comp.Enter;
@@ -430,4 +432,16 @@
                 log.useSource(oldSource);
         }
     }
+
+    @Override
+    public TypeMirror getLub(CatchTree tree) {
+        JCCatch ct = (JCCatch) tree;
+        JCVariableDecl v = ct.param;
+        if (v.type != null && v.type.getKind() == TypeKind.UNION) {
+            UnionClassType ut = (UnionClassType) v.type;
+            return ut.getLub();
+        } else {
+            return v.type;
+        }
+    }
 }
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Type.java	Thu Apr 28 08:46:06 2011 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Type.java	Thu Apr 28 15:05:36 2011 -0700
@@ -25,6 +25,8 @@
 
 package com.sun.tools.javac.code;
 
+import java.util.Collections;
+
 import com.sun.tools.javac.util.*;
 import com.sun.tools.javac.code.Symbol.*;
 
@@ -741,6 +743,38 @@
         }
     }
 
+    // a clone of a ClassType that knows about the alternatives of a union type.
+    public static class UnionClassType extends ClassType implements UnionType {
+        final List<? extends Type> alternatives_field;
+
+        public UnionClassType(ClassType ct, List<? extends Type> alternatives) {
+            super(ct.outer_field, ct.typarams_field, ct.tsym);
+            allparams_field = ct.allparams_field;
+            supertype_field = ct.supertype_field;
+            interfaces_field = ct.interfaces_field;
+            all_interfaces_field = ct.interfaces_field;
+            alternatives_field = alternatives;
+        }
+
+        public Type getLub() {
+            return tsym.type;
+        }
+
+        public java.util.List<? extends TypeMirror> getAlternatives() {
+            return Collections.unmodifiableList(alternatives_field);
+        }
+
+        @Override
+        public TypeKind getKind() {
+            return TypeKind.UNION;
+        }
+
+        @Override
+        public <R, P> R accept(TypeVisitor<R, P> v, P p) {
+            return v.visitUnion(this, p);
+        }
+    }
+
     public static class ArrayType extends Type
             implements javax.lang.model.type.ArrayType {
 
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Thu Apr 28 08:46:06 2011 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Thu Apr 28 15:05:36 2011 -0700
@@ -2910,6 +2910,7 @@
 
     public void visitTypeUnion(JCTypeUnion tree) {
         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
+        ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
         for (JCExpression typeTree : tree.alternatives) {
             Type ctype = attribType(typeTree, env);
             ctype = chk.checkType(typeTree.pos(),
@@ -2931,9 +2932,23 @@
                     }
                 }
                 multicatchTypes.append(ctype);
+                if (all_multicatchTypes != null)
+                    all_multicatchTypes.append(ctype);
+            } else {
+                if (all_multicatchTypes == null) {
+                    all_multicatchTypes = ListBuffer.lb();
+                    all_multicatchTypes.appendList(multicatchTypes);
+                }
+                all_multicatchTypes.append(ctype);
             }
         }
-        tree.type = result = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
+        Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
+        if (t.tag == CLASS) {
+            List<Type> alternatives =
+                ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
+            t = new UnionClassType((ClassType) t, alternatives);
+        }
+        tree.type = result = t;
     }
 
     public void visitTypeParameter(JCTypeParameter tree) {
--- a/langtools/src/share/classes/com/sun/tools/javac/model/JavacTypes.java	Thu Apr 28 08:46:06 2011 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/model/JavacTypes.java	Thu Apr 28 15:05:36 2011 -0700
@@ -72,11 +72,11 @@
     }
 
     public Element asElement(TypeMirror t) {
-        Type type = cast(Type.class, t);
-        switch (type.tag) {
-            case TypeTags.CLASS:
-            case TypeTags.ERROR:
-            case TypeTags.TYPEVAR:
+        switch (t.getKind()) {
+            case DECLARED:
+            case ERROR:
+            case TYPEVAR:
+                Type type = cast(Type.class, t);
                 return type.asElement();
             default:
                 return null;
--- a/langtools/test/tools/javac/multicatch/model/Model01.java	Thu Apr 28 08:46:06 2011 -0700
+++ b/langtools/test/tools/javac/multicatch/model/Model01.java	Thu Apr 28 15:05:36 2011 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,6 +43,6 @@
             else
                 throw new B2();
         }
-        catch(B1 | B2 ex) { }
+        catch(@UnionTypeInfo({"Test.B1", "Test.B2"}) B1 | B2 ex) { }
     }
 }
--- a/langtools/test/tools/javac/multicatch/model/ModelChecker.java	Thu Apr 28 08:46:06 2011 -0700
+++ b/langtools/test/tools/javac/multicatch/model/ModelChecker.java	Thu Apr 28 15:05:36 2011 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2011 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  * @compile -processor ModelChecker Model01.java
  */
 
-import com.sun.source.tree.VariableTree;
+import com.sun.source.tree.CatchTree;
 import com.sun.source.util.TreePathScanner;
 import com.sun.source.util.Trees;
 import com.sun.source.util.TreePath;
@@ -41,6 +41,12 @@
 import javax.lang.model.element.Element;
 import javax.lang.model.element.ElementKind;
 import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.UnionType;
+import javax.lang.model.type.UnknownTypeException;
+import javax.lang.model.util.SimpleTypeVisitor6;
+import javax.lang.model.util.SimpleTypeVisitor7;
 
 @SupportedAnnotationTypes("Check")
 public class ModelChecker extends JavacTestingAbstractProcessor {
@@ -69,20 +75,59 @@
         }
 
         @Override
-        public Void visitVariable(VariableTree node, Void p) {
-            Element ex = trees.getElement(getCurrentPath());
+        public Void visitCatch(CatchTree node, Void p) {
+            TreePath param = new TreePath(getCurrentPath(), node.getParameter());
+            Element ex = trees.getElement(param);
+            validateUnionTypeInfo(ex);
             if (ex.getSimpleName().contentEquals("ex")) {
                 assertTrue(ex.getKind() == ElementKind.EXCEPTION_PARAMETER, "Expected EXCEPTION_PARAMETER - found " + ex.getKind());
-                for (Element e : types.asElement(ex.asType()).getEnclosedElements()) {
+                for (Element e : types.asElement(trees.getLub(node)).getEnclosedElements()) {
                     Member m = e.getAnnotation(Member.class);
                     if (m != null) {
                         assertTrue(e.getKind() == m.value(), "Expected " + m.value() + " - found " + e.getKind());
                     }
                 }
-                assertTrue(assertionCount == 3, "Expected 3 assertions - found " + assertionCount);
+                assertTrue(assertionCount == 9, "Expected 9 assertions - found " + assertionCount);
             }
-            return super.visitVariable(node, p);
+            return super.visitCatch(node, p);
+        }
+    }
+
+    private void validateUnionTypeInfo(Element ex) {
+        UnionTypeInfo ut = ex.getAnnotation(UnionTypeInfo.class);
+        assertTrue(ut != null, "UnionType annotation must be present");
+
+        TypeMirror expectedUnionType = ex.asType();
+        assertTrue(expectedUnionType.getKind() == TypeKind.UNION, "UNION kind expected");
+
+        try {
+            new SimpleTypeVisitor6<Void, Void>(){}.visit(expectedUnionType);
+            throw new RuntimeException("Expected UnknownTypeException not thrown.");
+        } catch (UnknownTypeException ute) {
+            ; // Expected
         }
+
+        UnionType unionType = new SimpleTypeVisitor7<UnionType, Void>(){
+            @Override
+            protected UnionType defaultAction(TypeMirror e, Void p) {return null;}
+
+            @Override
+            public UnionType visitUnion(UnionType t, Void p) {return t;}
+        }.visit(expectedUnionType);
+        assertTrue(unionType != null, "Must get a non-null union type.");
+
+        assertTrue(ut.value().length == unionType.getAlternatives().size(), "Cardinalities do not match");
+
+        String[] typeNames = ut.value();
+        for(int i = 0; i < typeNames.length; i++) {
+            TypeMirror typeFromAnnotation = nameToType(typeNames[i]);
+            assertTrue(types.isSameType(typeFromAnnotation, unionType.getAlternatives().get(i)),
+                       "Types were not equal.");
+        }
+    }
+
+    private TypeMirror nameToType(String name) {
+        return elements.getTypeElement(name).asType();
     }
 
     private static void assertTrue(boolean cond, String msg) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/multicatch/model/UnionTypeInfo.java	Thu Apr 28 15:05:36 2011 -0700
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * Used by ModelChecker to validate the modeling information of a union type.
+ */
+@interface UnionTypeInfo {
+    String[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/type/TestUnionType.java	Thu Apr 28 15:05:36 2011 -0700
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug     7029150
+ * @summary Test support for union types
+ * @library ../../../lib
+ */
+
+import java.net.URI;
+import java.util.*;
+import javax.annotation.processing.*;
+import javax.lang.model.element.*;
+import javax.lang.model.type.*;
+import javax.lang.model.util.*;
+import javax.tools.*;
+
+import com.sun.source.tree.*;
+import com.sun.source.util.*;
+
+
+public class TestUnionType extends JavacTestingAbstractProcessor {
+    enum TestKind {
+        SingleType("E1", "E1",
+                "VariableTree: E1 e",
+                "VariableTree: elem EXCEPTION_PARAMETER e",
+                "VariableTree: elem.type DECLARED",
+                "VariableTree: elem.type.elem CLASS E1",
+                "VariableTree: type DECLARED",
+                "VariableTree: type.elem CLASS E1",
+                "VariableTree: type.elem.type DECLARED"),
+
+        ValidTypes("E1, E2", "E1 | E2",
+                "VariableTree: E1 | E2 e",
+                "VariableTree: elem EXCEPTION_PARAMETER e",
+                "VariableTree: elem.type UNION Test.E1,Test.E2",
+                "VariableTree: elem.type.elem null",
+                "VariableTree: type UNION Test.E1,Test.E2",
+                "VariableTree: type.elem null"),
+
+        InvalidTypes("E1, E2", "E1 | EMissing",
+                "VariableTree: E1 | EMissing e",
+                "VariableTree: elem EXCEPTION_PARAMETER e",
+                "VariableTree: elem.type UNION Test.E1,EMissing",
+                "VariableTree: elem.type.elem null",
+                "VariableTree: type UNION Test.E1,EMissing",
+                "VariableTree: type.elem null"),
+
+        Uncaught("E1", "E1 | E2",
+                "VariableTree: E1 | E2 e",
+                "VariableTree: elem EXCEPTION_PARAMETER e",
+                "VariableTree: elem.type UNION Test.E1,Test.E2",
+                "VariableTree: elem.type.elem null",
+                "VariableTree: type UNION Test.E1,Test.E2",
+                "VariableTree: type.elem null");
+
+        TestKind(String throwsTypes, String catchTypes, String... gold) {
+            this.throwsTypes = throwsTypes;
+            this.catchTypes = catchTypes;
+            this.gold = Arrays.asList(gold);
+        }
+
+        final String throwsTypes;
+        final String catchTypes;
+        final List<String> gold;
+    }
+
+    static class TestFileObject extends SimpleJavaFileObject {
+        public static final String template =
+                  "class Test {\n"
+                + "    class E1 extends Exception { }\n"
+                + "    class E2 extends Exception { }\n"
+                + "    void doSomething() throws #T { }\n"
+                + "    void test() {\n"
+                + "        try {\n"
+                + "            doSomething();\n"
+                + "        } catch (#C e) {\n"
+                + "        }\n"
+                + "    }\n"
+                + "}\n";
+
+        public TestFileObject(TestKind tk) {
+            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
+            this.tk = tk;
+        }
+
+        @Override
+        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+            return template
+                    .replace("#T", tk.throwsTypes)
+                    .replace("#C", tk.catchTypes);
+        }
+        final TestKind tk;
+    }
+
+    public static void main(String... args) throws Exception {
+        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
+        List<String> options = Arrays.asList("-proc:only");
+        for (TestKind tk: TestKind.values()) {
+            System.err.println("Test: " + tk);
+            TestUnionType p = new TestUnionType();
+            JavaFileObject fo = new TestFileObject(tk);
+            JavaCompiler.CompilationTask task = comp.getTask(null, null, null, options, null, Arrays.asList(fo));
+            task.setProcessors(Arrays.asList(p));
+            boolean ok = task.call();
+            System.err.println("compilation " + (ok ? "passed" : "failed"));
+            if (!ok)
+                throw new Exception("compilation failed unexpectedly");
+            if (!p.log.equals(tk.gold)) {
+                System.err.println("Expected output:");
+                for (String g: tk.gold)
+                    System.err.println(g);
+                throw new Exception("unexpected output from test");
+            }
+            System.err.println();
+        }
+    }
+
+    Trees trees;
+    List<String> log;
+
+    @Override
+    public void init(ProcessingEnvironment env) {
+        super.init(env);
+        trees = Trees.instance(env);
+        log = new ArrayList<String>();
+    }
+
+    @Override
+    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+        if (!roundEnv.processingOver()) {
+            for (Element e: roundEnv.getRootElements()) {
+                scan(trees.getPath(e));
+            }
+        }
+        return true;
+    }
+
+    void scan(TreePath path) {
+        new Scanner().scan(path, null);
+    }
+
+    class Scanner extends TreePathScanner<Void,Void> {
+        @Override
+        public Void visitVariable(VariableTree tree, Void ignore) {
+            TreePath p = getCurrentPath();
+            Element e = trees.getElement(p);
+            if (e.getKind() == ElementKind.EXCEPTION_PARAMETER) {
+                log("VariableTree: " + tree);
+                log("VariableTree: elem " + print(e));
+                log("VariableTree: elem.type " + print(e.asType()));
+                log("VariableTree: elem.type.elem " + print(types.asElement(e.asType())));
+                TypeMirror tm = trees.getTypeMirror(p);
+                log("VariableTree: type " + print(tm));
+                log("VariableTree: type.elem " + print(types.asElement(tm)));
+                if (types.asElement(tm) != null)
+                    log("VariableTree: type.elem.type " + print(types.asElement(tm).asType()));
+            }
+            return super.visitVariable(tree, null);
+        }
+
+        String print(TypeMirror tm) {
+            return (tm == null) ? null : new TypePrinter().visit(tm);
+        }
+
+        String print(Element e) {
+            return (e == null) ? null : (e.getKind() + " " + e.getSimpleName());
+        }
+
+        void log(String msg) {
+            System.err.println(msg);
+            log.add(msg);
+        }
+    }
+
+    class TypePrinter extends SimpleTypeVisitor7<String, Void> {
+        @Override
+        protected String defaultAction(TypeMirror tm, Void ignore) {
+            return String.valueOf(tm.getKind());
+        }
+
+        @Override
+        public String visitUnion(UnionType t, Void ignore) {
+            return (t.getKind() + " " + t.getAlternatives());
+        }
+    }
+}