提交 b7cadf9f 编写于 作者: L lana

Merge

/*
* Copyright (c) 2008, 2009, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package com.sun.source.tree;
import java.util.List;
/**
* A tree node for an annotated type
*
* For example:
* <pre>
* {@code @}<em>annotationType String</em>
* {@code @}<em>annotationType</em> ( <em>arguments</em> ) <em>Date</em>
* </pre>
*
* @see "JSR 308: Annotations on Java Types"
*
* @author Mahmood Ali
* @since 1.7
*/
public interface AnnotatedTypeTree extends ExpressionTree {
List<? extends AnnotationTree> getAnnotations();
ExpressionTree getUnderlyingType();
}
...@@ -28,13 +28,13 @@ package com.sun.source.tree; ...@@ -28,13 +28,13 @@ package com.sun.source.tree;
import java.util.List; import java.util.List;
/** /**
* A tree node for a disjoint type expression in a multicatch var declaration. * A tree node for a disjunctive type expression in a multicatch var declaration.
* *
* *
* @author Maurizio Cimadamore * @author Maurizio Cimadamore
* *
* @since 1.7 * @since 1.7
*/ */
public interface DisjointTypeTree extends Tree { public interface DisjunctiveTypeTree extends Tree {
List<? extends Tree> getTypeComponents(); List<? extends Tree> getTypeAlternatives();
} }
...@@ -53,7 +53,7 @@ public interface MethodTree extends Tree { ...@@ -53,7 +53,7 @@ public interface MethodTree extends Tree {
Tree getReturnType(); Tree getReturnType();
List<? extends TypeParameterTree> getTypeParameters(); List<? extends TypeParameterTree> getTypeParameters();
List<? extends VariableTree> getParameters(); List<? extends VariableTree> getParameters();
List<? extends AnnotationTree> getReceiverAnnotations(); //308 List<? extends AnnotationTree> getReceiverAnnotations();
List<? extends ExpressionTree> getThrows(); List<? extends ExpressionTree> getThrows();
BlockTree getBody(); BlockTree getBody();
Tree getDefaultValue(); // for annotation types Tree getDefaultValue(); // for annotation types
......
...@@ -46,7 +46,7 @@ public interface Tree { ...@@ -46,7 +46,7 @@ public interface Tree {
*/ */
public enum Kind { public enum Kind {
ANNOTATED_TYPE(AnnotatedTypeTree.class), //308 ANNOTATED_TYPE(AnnotatedTypeTree.class),
/** /**
* Used for instances of {@link AnnotationTree}. * Used for instances of {@link AnnotationTree}.
...@@ -234,9 +234,9 @@ public interface Tree { ...@@ -234,9 +234,9 @@ public interface Tree {
PARAMETERIZED_TYPE(ParameterizedTypeTree.class), PARAMETERIZED_TYPE(ParameterizedTypeTree.class),
/** /**
* Used for instances of {@link DisjointTypeTree}. * Used for instances of {@link DisjunctiveTypeTree}.
*/ */
DISJOINT_TYPE(DisjointTypeTree.class), DISJUNCTIVE_TYPE(DisjunctiveTypeTree.class),
/** /**
* Used for instances of {@link TypeCastTree}. * Used for instances of {@link TypeCastTree}.
......
...@@ -57,7 +57,7 @@ package com.sun.source.tree; ...@@ -57,7 +57,7 @@ package com.sun.source.tree;
* @since 1.6 * @since 1.6
*/ */
public interface TreeVisitor<R,P> { public interface TreeVisitor<R,P> {
R visitAnnotatedType(AnnotatedTypeTree node, P p); //308 R visitAnnotatedType(AnnotatedTypeTree node, P p);
R visitAnnotation(AnnotationTree node, P p); R visitAnnotation(AnnotationTree node, P p);
R visitMethodInvocation(MethodInvocationTree node, P p); R visitMethodInvocation(MethodInvocationTree node, P p);
R visitAssert(AssertTree node, P p); R visitAssert(AssertTree node, P p);
...@@ -96,7 +96,7 @@ public interface TreeVisitor<R,P> { ...@@ -96,7 +96,7 @@ public interface TreeVisitor<R,P> {
R visitCompilationUnit(CompilationUnitTree node, P p); R visitCompilationUnit(CompilationUnitTree node, P p);
R visitTry(TryTree node, P p); R visitTry(TryTree node, P p);
R visitParameterizedType(ParameterizedTypeTree node, P p); R visitParameterizedType(ParameterizedTypeTree node, P p);
R visitDisjointType(DisjointTypeTree node, P p); R visitDisjunctiveType(DisjunctiveTypeTree node, P p);
R visitArrayType(ArrayTypeTree node, P p); R visitArrayType(ArrayTypeTree node, P p);
R visitTypeCast(TypeCastTree node, P p); R visitTypeCast(TypeCastTree node, P p);
R visitPrimitiveType(PrimitiveTypeTree node, P p); R visitPrimitiveType(PrimitiveTypeTree node, P p);
......
...@@ -47,5 +47,5 @@ import javax.lang.model.element.Name; ...@@ -47,5 +47,5 @@ import javax.lang.model.element.Name;
public interface TypeParameterTree extends Tree { public interface TypeParameterTree extends Tree {
Name getName(); Name getName();
List<? extends Tree> getBounds(); List<? extends Tree> getBounds();
List<? extends AnnotationTree> getAnnotations(); //308 List<? extends AnnotationTree> getAnnotations();
} }
/*
* Copyright (c) 2009, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package com.sun.source.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.*;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.source.tree.ClassTree;
/**
* This class is an abstract annotation processor designed to be a
* convenient superclass for concrete "type processors", processors that
* require the type information in the processed source.
*
* <p>Type processing occurs in one round after the tool (e.g. java compiler)
* analyzes the source (all sources taken as input to the tool and sources
* generated by other annotation processors).
*
* <p>The tool infrastructure will interact with classes extending this abstract
* class as follows:
*
* <ol>
* [1-3: Identical to {@link Processor} life cycle]
*
* <li>If an existing {@code Processor} object is not being used, to
* create an instance of a processor the tool calls the no-arg
* constructor of the processor class.
*
* <li>Next, the tool calls the {@link #init init} method with
* an appropriate {@code ProcessingEnvironment}.
*
* <li>Afterwards, the tool calls {@link #getSupportedAnnotationTypes
* getSupportedAnnotationTypes}, {@link #getSupportedOptions
* getSupportedOptions}, and {@link #getSupportedSourceVersion
* getSupportedSourceVersion}. These methods are only called once per
* run, not on each round.
*
* [4-5Unique to {@code AbstractTypeProcessor} subclasses]
*
* <li>For each class containing a supported annotation, the tool calls
* {@link #typeProcess(TypeElement, TreePath) typeProcess} method on the
* {@code Processor}. The class is guaranteed to be type-checked Java code
* and all the tree type and symbol information is resolved.
*
* <li>Finally, the tools calls the
* {@link #typeProcessingOver() typeProcessingOver} method
* on the {@code Processor}.
*
* </ol>
*
* <p>The tool is permitted to ask type processors to process a class once
* it is analyzed before the rest of classes are analyzed. The tool is also
* permitted to stop type processing immediately if any errors are raised,
* without invoking {@code typeProcessingOver}
*
* <p>A subclass may override any of the methods in this class, as long as the
* general {@link javax.annotation.processing.Processor Processor}
* contract is obeyed, with one notable exception.
* {@link #process(Set, RoundEnvironment)} may not be overridden, as it
* is called during the regular annotation phase before classes are analyzed.
*
* @author Mahmood Ali
* @since 1.7
*/
public abstract class AbstractTypeProcessor extends AbstractProcessor {
private final Set<Name> elements = new HashSet<Name>();
private boolean hasInvokedTypeProcessingOver = false;
private JavacProcessingEnvironment env;
private final AttributionTaskListener listener = new AttributionTaskListener();
/**
* Constructor for subclasses to call.
*/
protected AbstractTypeProcessor() { }
/**
* {@inheritDoc}
*/
@Override
public void init(ProcessingEnvironment env) {
super.init(env);
this.env = (JavacProcessingEnvironment)env;
prepareContext(this.env.getContext());
}
/**
* The use of this method is obsolete in type processors. The method is
* called during regular annotation processing phase only.
*/
@Override
public final boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (TypeElement elem : ElementFilter.typesIn(roundEnv.getRootElements())) {
elements.add(elem.getQualifiedName());
}
return false;
}
/**
* Processes a fully analyzed class that contains a supported annotation
* (look {@link #getSupportedAnnotationTypes()}).
*
* <p>The passed class is always a valid type-checked Java code.
*
* @param element element of the analyzed class
* @param tree the tree path to the element, with the leaf being a
* {@link ClassTree}
*/
public abstract void typeProcess(TypeElement element, TreePath tree);
/**
* A method to be called once all the classes are processed and no error
* is reported.
*
* <p>Subclasses may override this method to do any aggregate analysis
* (e.g. generate report, persistence) or resource deallocation.
*
* <p>If an error (a Java error or a processor error) is reported, this
* method is not guaranteed to be invoked.
*/
public void typeProcessingOver() { }
/**
* adds a listener for attribution.
*/
private void prepareContext(Context context) {
TaskListener otherListener = context.get(TaskListener.class);
if (otherListener == null) {
context.put(TaskListener.class, listener);
} else {
// handle cases of multiple listeners
context.put(TaskListener.class, (TaskListener)null);
TaskListeners listeners = new TaskListeners();
listeners.add(otherListener);
listeners.add(listener);
context.put(TaskListener.class, listeners);
}
}
/**
* A task listener that invokes the processor whenever a class is fully
* analyzed.
*/
private final class AttributionTaskListener implements TaskListener {
@Override
public void finished(TaskEvent e) {
Log log = Log.instance(env.getContext());
if (!hasInvokedTypeProcessingOver && elements.isEmpty() && log.nerrors == 0) {
typeProcessingOver();
hasInvokedTypeProcessingOver = true;
}
if (e.getKind() != TaskEvent.Kind.ANALYZE)
return;
if (e.getTypeElement() == null)
throw new AssertionError("event task without a type element");
if (e.getCompilationUnit() == null)
throw new AssertionError("even task without compilation unit");
if (!elements.remove(e.getTypeElement().getQualifiedName()))
return;
if (log.nerrors != 0)
return;
TypeElement elem = e.getTypeElement();
TreePath p = Trees.instance(env).getPath(elem);
typeProcess(elem, p);
if (!hasInvokedTypeProcessingOver && elements.isEmpty() && log.nerrors == 0) {
typeProcessingOver();
hasInvokedTypeProcessingOver = true;
}
}
@Override
public void started(TaskEvent e) { }
}
/**
* A task listener multiplexer.
*/
private static class TaskListeners implements TaskListener {
private final List<TaskListener> listeners = new ArrayList<TaskListener>();
public void add(TaskListener listener) {
listeners.add(listener);
}
public void remove(TaskListener listener) {
listeners.remove(listener);
}
@Override
public void finished(TaskEvent e) {
for (TaskListener listener : listeners)
listener.finished(e);
}
@Override
public void started(TaskEvent e) {
for (TaskListener listener : listeners)
listener.started(e);
}
}
}
...@@ -228,7 +228,7 @@ public class SimpleTreeVisitor <R,P> implements TreeVisitor<R,P> { ...@@ -228,7 +228,7 @@ public class SimpleTreeVisitor <R,P> implements TreeVisitor<R,P> {
return defaultAction(node, p); return defaultAction(node, p);
} }
public R visitDisjointType(DisjointTypeTree node, P p) { public R visitDisjunctiveType(DisjunctiveTypeTree node, P p) {
return defaultAction(node, p); return defaultAction(node, p);
} }
...@@ -248,9 +248,9 @@ public class SimpleTreeVisitor <R,P> implements TreeVisitor<R,P> { ...@@ -248,9 +248,9 @@ public class SimpleTreeVisitor <R,P> implements TreeVisitor<R,P> {
return defaultAction(node, p); return defaultAction(node, p);
} }
public R visitAnnotatedType(AnnotatedTypeTree node, P p) { //308 public R visitAnnotatedType(AnnotatedTypeTree node, P p) {
return defaultAction(node, p); //308 return defaultAction(node, p);
} //308 }
public R visitErroneous(ErroneousTree node, P p) { public R visitErroneous(ErroneousTree node, P p) {
return defaultAction(node, p); return defaultAction(node, p);
......
...@@ -138,7 +138,7 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> { ...@@ -138,7 +138,7 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> {
r = scanAndReduce(node.getReturnType(), p, r); r = scanAndReduce(node.getReturnType(), p, r);
r = scanAndReduce(node.getTypeParameters(), p, r); r = scanAndReduce(node.getTypeParameters(), p, r);
r = scanAndReduce(node.getParameters(), p, r); r = scanAndReduce(node.getParameters(), p, r);
r = scanAndReduce(node.getReceiverAnnotations(), p, r); //308 r = scanAndReduce(node.getReceiverAnnotations(), p, r);
r = scanAndReduce(node.getThrows(), p, r); r = scanAndReduce(node.getThrows(), p, r);
r = scanAndReduce(node.getBody(), p, r); r = scanAndReduce(node.getBody(), p, r);
r = scanAndReduce(node.getDefaultValue(), p, r); r = scanAndReduce(node.getDefaultValue(), p, r);
...@@ -356,13 +356,13 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> { ...@@ -356,13 +356,13 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> {
return r; return r;
} }
public R visitDisjointType(DisjointTypeTree node, P p) { public R visitDisjunctiveType(DisjunctiveTypeTree node, P p) {
return scan(node.getTypeComponents(), p); return scan(node.getTypeAlternatives(), p);
} }
public R visitTypeParameter(TypeParameterTree node, P p) { public R visitTypeParameter(TypeParameterTree node, P p) {
R r = scan(node.getAnnotations(), p); R r = scan(node.getBounds(), p);
r = scanAndReduce(node.getBounds(), p, r); //308 R r = scanAndReduce(node.getAnnotations(), p, r);
return r; return r;
} }
...@@ -380,11 +380,11 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> { ...@@ -380,11 +380,11 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> {
return r; return r;
} }
public R visitAnnotatedType(AnnotatedTypeTree node, P p) { //308 public R visitAnnotatedType(AnnotatedTypeTree node, P p) {
R r = scan(node.getAnnotations(), p); //308 R r = scan(node.getAnnotations(), p);
r = scanAndReduce(node.getUnderlyingType(), p, r); //308 r = scanAndReduce(node.getUnderlyingType(), p, r);
return r; //308 return r;
} //308 }
public R visitOther(Tree node, P p) { public R visitOther(Tree node, P p) {
return null; return null;
......
...@@ -282,9 +282,10 @@ public class JavacTrees extends Trees { ...@@ -282,9 +282,10 @@ public class JavacTrees extends Trees {
// System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile); // System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
env = enter.getTopLevelEnv((JCCompilationUnit)tree); env = enter.getTopLevelEnv((JCCompilationUnit)tree);
break; break;
case ANNOTATION_TYPE:
case CLASS: case CLASS:
case INTERFACE:
case ENUM: case ENUM:
case INTERFACE:
// System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName()); // System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
env = enter.getClassEnv(((JCClassDecl)tree).sym); env = enter.getClassEnv(((JCClassDecl)tree).sym);
break; break;
......
...@@ -231,9 +231,9 @@ public class Flags { ...@@ -231,9 +231,9 @@ public class Flags {
public static final long PROPRIETARY = 1L<<38; public static final long PROPRIETARY = 1L<<38;
/** /**
* Flag that marks a disjoint var in a multi-catch clause * Flag that marks a disjunction var in a multi-catch clause
*/ */
public static final long DISJOINT = 1L<<39; public static final long DISJUNCTION = 1L<<39;
/** /**
* Flag that marks a signature-polymorphic invoke method. * Flag that marks a signature-polymorphic invoke method.
......
...@@ -55,8 +55,8 @@ public class TypeAnnotations { ...@@ -55,8 +55,8 @@ public class TypeAnnotations {
} }
public void taFillAndLift(JCClassDecl tree, boolean visitBodies) { public void taFillAndLift(JCClassDecl tree, boolean visitBodies) {
new TypeAnnotationPositions().scan(tree); //308 new TypeAnnotationPositions().scan(tree);
new TypeAnnotationLift().scan(tree); //308 new TypeAnnotationLift().scan(tree);
} }
private static class TypeAnnotationPositions extends TreeScanner { private static class TypeAnnotationPositions extends TreeScanner {
...@@ -113,9 +113,10 @@ public class TypeAnnotations { ...@@ -113,9 +113,10 @@ public class TypeAnnotations {
p.pos = frame.pos; p.pos = frame.pos;
return p; return p;
case ANNOTATION_TYPE:
case CLASS: case CLASS:
case INTERFACE:
case ENUM: case ENUM:
case INTERFACE:
p.pos = frame.pos; p.pos = frame.pos;
if (((JCClassDecl)frame).extending == tree) { if (((JCClassDecl)frame).extending == tree) {
p.type = TargetType.CLASS_EXTENDS; p.type = TargetType.CLASS_EXTENDS;
...@@ -208,11 +209,11 @@ public class TypeAnnotations { ...@@ -208,11 +209,11 @@ public class TypeAnnotations {
} }
return p; return p;
case ANNOTATED_TYPE: { //308 case ANNOTATED_TYPE: {
List<JCTree> newPath = path.tail; //308 List<JCTree> newPath = path.tail;
return resolveFrame(newPath.head, newPath.tail.head, //308 return resolveFrame(newPath.head, newPath.tail.head,
newPath, p); //308 newPath, p);
} //308 }
case METHOD_INVOCATION: { case METHOD_INVOCATION: {
JCMethodInvocation invocation = (JCMethodInvocation)frame; JCMethodInvocation invocation = (JCMethodInvocation)frame;
......
...@@ -121,6 +121,8 @@ public class Attr extends JCTree.Visitor { ...@@ -121,6 +121,8 @@ public class Attr extends JCTree.Visitor {
sourceName = source.name; sourceName = source.name;
relax = (options.isSet("-retrofit") || relax = (options.isSet("-retrofit") ||
options.isSet("-relax")); options.isSet("-relax"));
findDiamonds = options.get("findDiamond") != null &&
source.allowDiamond();
useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning"); useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
enableSunApiLintControl = options.isSet("enableSunApiLintControl"); enableSunApiLintControl = options.isSet("enableSunApiLintControl");
} }
...@@ -154,6 +156,16 @@ public class Attr extends JCTree.Visitor { ...@@ -154,6 +156,16 @@ public class Attr extends JCTree.Visitor {
*/ */
boolean allowAnonOuterThis; boolean allowAnonOuterThis;
/** Switch: generates a warning if diamond can be safely applied
* to a given new expression
*/
boolean findDiamonds;
/**
* Internally enables/disables diamond finder feature
*/
static final boolean allowDiamondFinder = true;
/** /**
* Switch: warn about use of variable before declaration? * Switch: warn about use of variable before declaration?
* RFE: 6425594 * RFE: 6425594
...@@ -1053,9 +1065,9 @@ public class Attr extends JCTree.Visitor { ...@@ -1053,9 +1065,9 @@ public class Attr extends JCTree.Visitor {
if ((c.param.sym.flags() & FINAL) == 0) { if ((c.param.sym.flags() & FINAL) == 0) {
log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym); log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
} }
c.param.sym.flags_field = c.param.sym.flags() | DISJOINT; c.param.sym.flags_field = c.param.sym.flags() | DISJUNCTION;
} }
if (c.param.type.tsym.kind == Kinds.VAR) { if (c.param.sym.kind == Kinds.VAR) {
c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
} }
chk.checkType(c.param.vartype.pos(), chk.checkType(c.param.vartype.pos(),
...@@ -1572,6 +1584,24 @@ public class Attr extends JCTree.Visitor { ...@@ -1572,6 +1584,24 @@ public class Attr extends JCTree.Visitor {
if (TreeInfo.isDiamond(tree)) { if (TreeInfo.isDiamond(tree)) {
clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes); clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
clazz.type = clazztype; clazz.type = clazztype;
} else if (allowDiamondFinder &&
clazztype.getTypeArguments().nonEmpty() &&
findDiamonds) {
Type inferred = attribDiamond(localEnv,
tree,
clazztype,
mapping,
argtypes,
typeargtypes);
if (!inferred.isErroneous() &&
inferred.tag == CLASS &&
types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings) &&
chk.checkDiamond((ClassType)inferred).isEmpty()) {
String key = types.isSameType(clazztype, inferred) ?
"diamond.redundant.args" :
"diamond.redundant.args.1";
log.warning(tree.clazz.pos(), key, clazztype, inferred);
}
} }
// If we have made no mistakes in the class type... // If we have made no mistakes in the class type...
...@@ -2839,9 +2869,9 @@ public class Attr extends JCTree.Visitor { ...@@ -2839,9 +2869,9 @@ public class Attr extends JCTree.Visitor {
result = check(tree, owntype, TYP, pkind, pt); result = check(tree, owntype, TYP, pkind, pt);
} }
public void visitTypeDisjoint(JCTypeDisjoint tree) { public void visitTypeDisjunction(JCTypeDisjunction tree) {
List<Type> componentTypes = attribTypes(tree.components, env); List<Type> alternatives = attribTypes(tree.alternatives, env);
tree.type = result = check(tree, types.lub(componentTypes), TYP, pkind, pt); tree.type = result = check(tree, types.lub(alternatives), TYP, pkind, pt);
} }
public void visitTypeParameter(JCTypeParameter tree) { public void visitTypeParameter(JCTypeParameter tree) {
......
...@@ -371,7 +371,7 @@ public class Flow extends TreeScanner { ...@@ -371,7 +371,7 @@ public class Flow extends TreeScanner {
if (sym.adr >= firstadr && trackable(sym)) { if (sym.adr >= firstadr && trackable(sym)) {
if ((sym.flags() & FINAL) != 0) { if ((sym.flags() & FINAL) != 0) {
if ((sym.flags() & PARAMETER) != 0) { if ((sym.flags() & PARAMETER) != 0) {
if ((sym.flags() & DISJOINT) != 0) { //multi-catch parameter if ((sym.flags() & DISJUNCTION) != 0) { //multi-catch parameter
log.error(pos, "multicatch.parameter.may.not.be.assigned", log.error(pos, "multicatch.parameter.may.not.be.assigned",
sym); sym);
} }
...@@ -983,7 +983,7 @@ public class Flow extends TreeScanner { ...@@ -983,7 +983,7 @@ public class Flow extends TreeScanner {
thrown = List.nil(); thrown = List.nil();
for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ? List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
((JCTypeDisjoint)l.head.param.vartype).components : ((JCTypeDisjunction)l.head.param.vartype).alternatives :
List.of(l.head.param.vartype); List.of(l.head.param.vartype);
for (JCExpression ct : subClauses) { for (JCExpression ct : subClauses) {
caught = chk.incl(ct.type, caught); caught = chk.incl(ct.type, caught);
...@@ -1049,7 +1049,7 @@ public class Flow extends TreeScanner { ...@@ -1049,7 +1049,7 @@ public class Flow extends TreeScanner {
alive = true; alive = true;
JCVariableDecl param = l.head.param; JCVariableDecl param = l.head.param;
List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ? List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
((JCTypeDisjoint)l.head.param.vartype).components : ((JCTypeDisjunction)l.head.param.vartype).alternatives :
List.of(l.head.param.vartype); List.of(l.head.param.vartype);
List<Type> ctypes = List.nil(); List<Type> ctypes = List.nil();
List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry); List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);
......
...@@ -876,7 +876,8 @@ public class TransTypes extends TreeTranslator { ...@@ -876,7 +876,8 @@ public class TransTypes extends TreeTranslator {
make.at(tree.pos); make.at(tree.pos);
if (addBridges) { if (addBridges) {
ListBuffer<JCTree> bridges = new ListBuffer<JCTree>(); ListBuffer<JCTree> bridges = new ListBuffer<JCTree>();
bridges.appendList(addOverrideBridgesIfNeeded(tree, c)); if (false) //see CR: 6996415
bridges.appendList(addOverrideBridgesIfNeeded(tree, c));
if ((tree.sym.flags() & INTERFACE) == 0) if ((tree.sym.flags() & INTERFACE) == 0)
addBridges(tree.pos(), tree.sym, bridges); addBridges(tree.pos(), tree.sym, bridges);
tree.defs = bridges.toList().prependList(tree.defs); tree.defs = bridges.toList().prependList(tree.defs);
......
...@@ -1456,7 +1456,7 @@ public class Gen extends JCTree.Visitor { ...@@ -1456,7 +1456,7 @@ public class Gen extends JCTree.Visitor {
List<Integer> gaps) { List<Integer> gaps) {
if (startpc != endpc) { if (startpc != endpc) {
List<JCExpression> subClauses = TreeInfo.isMultiCatch(tree) ? List<JCExpression> subClauses = TreeInfo.isMultiCatch(tree) ?
((JCTypeDisjoint)tree.param.vartype).components : ((JCTypeDisjunction)tree.param.vartype).alternatives :
List.of(tree.param.vartype); List.of(tree.param.vartype);
while (gaps.nonEmpty()) { while (gaps.nonEmpty()) {
for (JCExpression subCatch : subClauses) { for (JCExpression subCatch : subClauses) {
......
...@@ -1090,7 +1090,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter { ...@@ -1090,7 +1090,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
private boolean unrecoverableError() { private boolean unrecoverableError() {
for (JCDiagnostic d: log.deferredDiagnostics) { for (JCDiagnostic d: log.deferredDiagnostics) {
if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RESOLVE_ERROR)) if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
return true; return true;
} }
return false; return false;
......
...@@ -49,11 +49,11 @@ import javax.tools.StandardJavaFileManager; ...@@ -49,11 +49,11 @@ import javax.tools.StandardJavaFileManager;
import javax.tools.JavaFileObject; import javax.tools.JavaFileObject;
import javax.tools.DiagnosticListener; import javax.tools.DiagnosticListener;
import com.sun.tools.javac.api.JavacTrees; //308 import com.sun.source.util.AbstractTypeProcessor;
import com.sun.source.util.AbstractTypeProcessor;
import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener; import com.sun.source.util.TaskListener;
import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.*; import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*; import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.file.JavacFileManager;
...@@ -712,7 +712,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -712,7 +712,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
} }
if (matchedNames.size() > 0 || ps.contributed) { if (matchedNames.size() > 0 || ps.contributed) {
foundTypeProcessors = foundTypeProcessors || (ps.processor instanceof AbstractTypeProcessor); //308 foundTypeProcessors = foundTypeProcessors || (ps.processor instanceof AbstractTypeProcessor);
boolean processingResult = callProcessor(ps.processor, typeElements, renv); boolean processingResult = callProcessor(ps.processor, typeElements, renv);
ps.contributed = true; ps.contributed = true;
ps.removeSupportedOptions(unmatchedProcessorOptions); ps.removeSupportedOptions(unmatchedProcessorOptions);
...@@ -939,7 +939,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -939,7 +939,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
break; break;
case ERROR: case ERROR:
if (fatalErrors || !d.isFlagSet(RESOLVE_ERROR)) if (fatalErrors || !d.isFlagSet(RECOVERABLE))
return true; return true;
break; break;
} }
......
...@@ -873,6 +873,13 @@ compiler.warn.raw.class.use=\ ...@@ -873,6 +873,13 @@ compiler.warn.raw.class.use=\
found raw type: {0}\n\ found raw type: {0}\n\
missing type parameters for generic class {1} missing type parameters for generic class {1}
compiler.warn.diamond.redundant.args=\
redundant type arguments in new expression (use diamond operator instead).
compiler.warn.diamond.redundant.args.1=\
redundant type arguments in new expression (use diamond operator instead).\n\
explicit: {0}\n\
inferred: {1}
##### #####
## The following are tokens which are non-terminals in the language. They should ## The following are tokens which are non-terminals in the language. They should
...@@ -1299,9 +1306,9 @@ compiler.err.annotations.not.supported.in.source=\ ...@@ -1299,9 +1306,9 @@ compiler.err.annotations.not.supported.in.source=\
annotations are not supported in -source {0}\n\ annotations are not supported in -source {0}\n\
(use -source 5 or higher to enable annotations) (use -source 5 or higher to enable annotations)
compiler.err.type.annotations.not.supported.in.source=\ #308 compiler.err.type.annotations.not.supported.in.source=\
type annotations are not supported in -source {0}\n\ #308 type annotations are not supported in -source {0}\n\
(use -source 7 or higher to enable type annotations) #308 (use -source 7 or higher to enable type annotations)
compiler.err.foreach.not.supported.in.source=\ compiler.err.foreach.not.supported.in.source=\
for-each loops are not supported in -source {0}\n\ for-each loops are not supported in -source {0}\n\
......
...@@ -236,13 +236,13 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { ...@@ -236,13 +236,13 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
*/ */
public static final int TYPEAPPLY = TYPEARRAY + 1; public static final int TYPEAPPLY = TYPEARRAY + 1;
/** Disjunctive types, of type TypeDisjoint. /** Disjunction types, of type TypeDisjunction
*/ */
public static final int TYPEDISJOINT = TYPEAPPLY + 1; public static final int TYPEDISJUNCTION = TYPEAPPLY + 1;
/** Formal type parameters, of type TypeParameter. /** Formal type parameters, of type TypeParameter.
*/ */
public static final int TYPEPARAMETER = TYPEDISJOINT + 1; public static final int TYPEPARAMETER = TYPEDISJUNCTION + 1;
/** Type argument. /** Type argument.
*/ */
...@@ -1888,30 +1888,30 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { ...@@ -1888,30 +1888,30 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
} }
/** /**
* A disjoint type, T1 | T2 | ... Tn (used in multicatch statements) * A disjunction type, T1 | T2 | ... Tn (used in multicatch statements)
*/ */
public static class JCTypeDisjoint extends JCExpression implements DisjointTypeTree { public static class JCTypeDisjunction extends JCExpression implements DisjunctiveTypeTree {
public List<JCExpression> components; public List<JCExpression> alternatives;
protected JCTypeDisjoint(List<JCExpression> components) { protected JCTypeDisjunction(List<JCExpression> components) {
this.components = components; this.alternatives = components;
} }
@Override @Override
public void accept(Visitor v) { v.visitTypeDisjoint(this); } public void accept(Visitor v) { v.visitTypeDisjunction(this); }
public Kind getKind() { return Kind.DISJOINT_TYPE; } public Kind getKind() { return Kind.DISJUNCTIVE_TYPE; }
public List<JCExpression> getTypeComponents() { public List<JCExpression> getTypeAlternatives() {
return components; return alternatives;
} }
@Override @Override
public <R,D> R accept(TreeVisitor<R,D> v, D d) { public <R,D> R accept(TreeVisitor<R,D> v, D d) {
return v.visitDisjointType(this, d); return v.visitDisjunctiveType(this, d);
} }
@Override @Override
public int getTag() { public int getTag() {
return TYPEDISJOINT; return TYPEDISJUNCTION;
} }
} }
...@@ -2067,17 +2067,23 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { ...@@ -2067,17 +2067,23 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
} }
} }
public static class JCAnnotatedType extends JCExpression implements com.sun.source.tree.AnnotatedTypeTree { public static class JCAnnotatedType extends JCExpression
//308 implements com.sun.source.tree.AnnotatedTypeTree
{
public List<JCTypeAnnotation> annotations; public List<JCTypeAnnotation> annotations;
public JCExpression underlyingType; public JCExpression underlyingType;
protected JCAnnotatedType(List<JCTypeAnnotation> annotations, JCExpression underlyingType) { protected JCAnnotatedType(List<JCTypeAnnotation> annotations, JCExpression underlyingType) {
this.annotations = annotations; throw new UnsupportedOperationException();
this.underlyingType = underlyingType; //308 this.annotations = annotations;
//308 this.underlyingType = underlyingType;
} }
@Override @Override
public void accept(Visitor v) { v.visitAnnotatedType(this); } public void accept(Visitor v) { v.visitAnnotatedType(this); }
public Kind getKind() { return Kind.ANNOTATED_TYPE; } public Kind getKind() {
throw new UnsupportedOperationException();
//308 return Kind.ANNOTATED_TYPE;
}
public List<JCTypeAnnotation> getAnnotations() { public List<JCTypeAnnotation> getAnnotations() {
return annotations; return annotations;
} }
...@@ -2086,7 +2092,8 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { ...@@ -2086,7 +2092,8 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
} }
@Override @Override
public <R,D> R accept(TreeVisitor<R,D> v, D d) { public <R,D> R accept(TreeVisitor<R,D> v, D d) {
return v.visitAnnotatedType(this, d); throw new UnsupportedOperationException();
//308 return v.visitAnnotatedType(this, d);
} }
@Override @Override
public int getTag() { public int getTag() {
...@@ -2277,7 +2284,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { ...@@ -2277,7 +2284,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
public void visitTypeIdent(JCPrimitiveTypeTree that) { visitTree(that); } public void visitTypeIdent(JCPrimitiveTypeTree that) { visitTree(that); }
public void visitTypeArray(JCArrayTypeTree that) { visitTree(that); } public void visitTypeArray(JCArrayTypeTree that) { visitTree(that); }
public void visitTypeApply(JCTypeApply that) { visitTree(that); } public void visitTypeApply(JCTypeApply that) { visitTree(that); }
public void visitTypeDisjoint(JCTypeDisjoint that) { visitTree(that); } public void visitTypeDisjunction(JCTypeDisjunction that) { visitTree(that); }
public void visitTypeParameter(JCTypeParameter that) { visitTree(that); } public void visitTypeParameter(JCTypeParameter that) { visitTree(that); }
public void visitWildcard(JCWildcard that) { visitTree(that); } public void visitWildcard(JCWildcard that) { visitTree(that); }
public void visitTypeBoundKind(TypeBoundKind that) { visitTree(that); } public void visitTypeBoundKind(TypeBoundKind that) { visitTree(that); }
......
...@@ -1195,9 +1195,9 @@ public class Pretty extends JCTree.Visitor { ...@@ -1195,9 +1195,9 @@ public class Pretty extends JCTree.Visitor {
} }
} }
public void visitTypeDisjoint(JCTypeDisjoint tree) { public void visitTypeDisjunction(JCTypeDisjunction tree) {
try { try {
printExprs(tree.components, " | "); printExprs(tree.alternatives, " | ");
} catch (IOException e) { } catch (IOException e) {
throw new UncheckedIOException(e); throw new UncheckedIOException(e);
} }
......
...@@ -71,12 +71,12 @@ public class TreeCopier<P> implements TreeVisitor<JCTree,P> { ...@@ -71,12 +71,12 @@ public class TreeCopier<P> implements TreeVisitor<JCTree,P> {
return lb.toList(); return lb.toList();
} }
public JCTree visitAnnotatedType(AnnotatedTypeTree node, P p) { //308 public JCTree visitAnnotatedType(AnnotatedTypeTree node, P p) {
JCAnnotatedType t = (JCAnnotatedType) node; //308 JCAnnotatedType t = (JCAnnotatedType) node;
List<JCTypeAnnotation> annotations = copy(t.annotations, p); //308 List<JCTypeAnnotation> annotations = copy(t.annotations, p);
JCExpression underlyingType = copy(t.underlyingType, p); //308 JCExpression underlyingType = copy(t.underlyingType, p);
return M.at(t.pos).AnnotatedType(annotations, underlyingType); //308 return M.at(t.pos).AnnotatedType(annotations, underlyingType);
} //308 }
public JCTree visitAnnotation(AnnotationTree node, P p) { public JCTree visitAnnotation(AnnotationTree node, P p) {
JCAnnotation t = (JCAnnotation) node; JCAnnotation t = (JCAnnotation) node;
...@@ -346,10 +346,10 @@ public class TreeCopier<P> implements TreeVisitor<JCTree,P> { ...@@ -346,10 +346,10 @@ public class TreeCopier<P> implements TreeVisitor<JCTree,P> {
return M.at(t.pos).TypeApply(clazz, arguments); return M.at(t.pos).TypeApply(clazz, arguments);
} }
public JCTree visitDisjointType(DisjointTypeTree node, P p) { public JCTree visitDisjunctiveType(DisjunctiveTypeTree node, P p) {
JCTypeDisjoint t = (JCTypeDisjoint) node; JCTypeDisjunction t = (JCTypeDisjunction) node;
List<JCExpression> components = copy(t.components, p); List<JCExpression> components = copy(t.alternatives, p);
return M.at(t.pos).TypeDisjoint(components); return M.at(t.pos).TypeDisjunction(components);
} }
public JCTree visitArrayType(ArrayTypeTree node, P p) { public JCTree visitArrayType(ArrayTypeTree node, P p) {
......
...@@ -119,7 +119,7 @@ public class TreeInfo { ...@@ -119,7 +119,7 @@ public class TreeInfo {
} }
public static boolean isMultiCatch(JCCatch catchClause) { public static boolean isMultiCatch(JCCatch catchClause) {
return catchClause.param.vartype.getTag() == JCTree.TYPEDISJOINT; return catchClause.param.vartype.getTag() == JCTree.TYPEDISJUNCTION;
} }
/** Is statement an initializer for a synthetic field? /** Is statement an initializer for a synthetic field?
......
...@@ -451,8 +451,8 @@ public class TreeMaker implements JCTree.Factory { ...@@ -451,8 +451,8 @@ public class TreeMaker implements JCTree.Factory {
return tree; return tree;
} }
public JCTypeDisjoint TypeDisjoint(List<JCExpression> components) { public JCTypeDisjunction TypeDisjunction(List<JCExpression> components) {
JCTypeDisjoint tree = new JCTypeDisjoint(components); JCTypeDisjunction tree = new JCTypeDisjunction(components);
tree.pos = pos; tree.pos = pos;
return tree; return tree;
} }
......
...@@ -276,8 +276,8 @@ public class TreeScanner extends Visitor { ...@@ -276,8 +276,8 @@ public class TreeScanner extends Visitor {
scan(tree.arguments); scan(tree.arguments);
} }
public void visitTypeDisjoint(JCTypeDisjoint tree) { public void visitTypeDisjunction(JCTypeDisjunction tree) {
scan(tree.components); scan(tree.alternatives);
} }
public void visitTypeParameter(JCTypeParameter tree) { public void visitTypeParameter(JCTypeParameter tree) {
......
...@@ -368,8 +368,8 @@ public class TreeTranslator extends JCTree.Visitor { ...@@ -368,8 +368,8 @@ public class TreeTranslator extends JCTree.Visitor {
result = tree; result = tree;
} }
public void visitTypeDisjoint(JCTypeDisjoint tree) { public void visitTypeDisjunction(JCTypeDisjunction tree) {
tree.components = translate(tree.components); tree.alternatives = translate(tree.alternatives);
result = tree; result = tree;
} }
......
...@@ -30,6 +30,7 @@ import java.util.Map; ...@@ -30,6 +30,7 @@ import java.util.Map;
import javax.tools.JavaFileObject; import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Lint.LintCategory; import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition; import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
...@@ -103,6 +104,19 @@ public abstract class AbstractLog { ...@@ -103,6 +104,19 @@ public abstract class AbstractLog {
report(diags.error(source, wrap(pos), key, args)); report(diags.error(source, wrap(pos), key, args));
} }
/** Report an error, unless another error was already reported at same
* source position.
* @param flag A flag to set on the diagnostic
* @param pos The source position at which to report the error.
* @param key The key for the localized error message.
* @param args Fields of the error message.
*/
public void error(DiagnosticFlag flag, int pos, String key, Object ... args) {
JCDiagnostic d = diags.error(source, wrap(pos), key, args);
d.setFlag(flag);
report(d);
}
/** Report a warning, unless suppressed by the -nowarn option or the /** Report a warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached. * maximum number of warnings has been reached.
* @param pos The source position at which to report the warning. * @param pos The source position at which to report the warning.
......
...@@ -63,17 +63,23 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> { ...@@ -63,17 +63,23 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
DiagnosticFormatter<JCDiagnostic> formatter; DiagnosticFormatter<JCDiagnostic> formatter;
final String prefix; final String prefix;
final Set<DiagnosticFlag> defaultErrorFlags;
/** Create a new diagnostic factory. */ /** Create a new diagnostic factory. */
protected Factory(Context context) { protected Factory(Context context) {
this(JavacMessages.instance(context), "compiler"); this(JavacMessages.instance(context), "compiler");
context.put(diagnosticFactoryKey, this); context.put(diagnosticFactoryKey, this);
Options options = Options.instance(context);
if (options.isSet("onlySyntaxErrorsUnrecoverable"))
defaultErrorFlags.add(DiagnosticFlag.RECOVERABLE);
} }
/** Create a new diagnostic factory. */ /** Create a new diagnostic factory. */
public Factory(JavacMessages messages, String prefix) { public Factory(JavacMessages messages, String prefix) {
this.prefix = prefix; this.prefix = prefix;
this.formatter = new BasicDiagnosticFormatter(messages); this.formatter = new BasicDiagnosticFormatter(messages);
defaultErrorFlags = EnumSet.of(DiagnosticFlag.MANDATORY);
} }
/** /**
...@@ -85,7 +91,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> { ...@@ -85,7 +91,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/ */
public JCDiagnostic error( public JCDiagnostic error(
DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) { DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(ERROR, null, EnumSet.of(DiagnosticFlag.MANDATORY), source, pos, key, args); return create(ERROR, null, defaultErrorFlags, source, pos, key, args);
} }
/** /**
...@@ -331,7 +337,9 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> { ...@@ -331,7 +337,9 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
public enum DiagnosticFlag { public enum DiagnosticFlag {
MANDATORY, MANDATORY,
RESOLVE_ERROR RESOLVE_ERROR,
SYNTAX,
RECOVERABLE
} }
private final DiagnosticType type; private final DiagnosticType type;
...@@ -547,6 +555,17 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> { ...@@ -547,6 +555,17 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
public void setFlag(DiagnosticFlag flag) { public void setFlag(DiagnosticFlag flag) {
flags.add(flag); flags.add(flag);
if (type == DiagnosticType.ERROR) {
switch (flag) {
case SYNTAX:
flags.remove(DiagnosticFlag.RECOVERABLE);
break;
case RESOLVE_ERROR:
flags.add(DiagnosticFlag.RECOVERABLE);
break;
}
}
} }
public boolean isFlagSet(DiagnosticFlag flag) { public boolean isFlagSet(DiagnosticFlag flag) {
......
...@@ -850,6 +850,12 @@ public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc { ...@@ -850,6 +850,12 @@ public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc {
String[] paramTypes, Set<ClassDocImpl> searched) { String[] paramTypes, Set<ClassDocImpl> searched) {
//### Note that this search is not necessarily what the compiler would do! //### Note that this search is not necessarily what the compiler would do!
Names names = tsym.name.table.names;
// do not match constructors
if (names.init.contentEquals(methodName)) {
return null;
}
ClassDocImpl cdi; ClassDocImpl cdi;
MethodDocImpl mdi; MethodDocImpl mdi;
...@@ -876,7 +882,6 @@ public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc { ...@@ -876,7 +882,6 @@ public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc {
*---------------------------------*/ *---------------------------------*/
// search current class // search current class
Names names = tsym.name.table.names;
Scope.Entry e = tsym.members().lookup(names.fromString(methodName)); Scope.Entry e = tsym.members().lookup(names.fromString(methodName));
//### Using modifier filter here isn't really correct, //### Using modifier filter here isn't really correct,
......
...@@ -637,6 +637,7 @@ public class DocEnv { ...@@ -637,6 +637,7 @@ public class DocEnv {
* Should be called only on symbols representing methods. * Should be called only on symbols representing methods.
*/ */
public MethodDocImpl getMethodDoc(MethodSymbol meth) { public MethodDocImpl getMethodDoc(MethodSymbol meth) {
assert !meth.isConstructor() : "not expecting a constructor symbol";
MethodDocImpl result = (MethodDocImpl)methodMap.get(meth); MethodDocImpl result = (MethodDocImpl)methodMap.get(meth);
if (result != null) return result; if (result != null) return result;
result = new MethodDocImpl(this, meth); result = new MethodDocImpl(this, meth);
...@@ -665,6 +666,7 @@ public class DocEnv { ...@@ -665,6 +666,7 @@ public class DocEnv {
* Should be called only on symbols representing constructors. * Should be called only on symbols representing constructors.
*/ */
public ConstructorDocImpl getConstructorDoc(MethodSymbol meth) { public ConstructorDocImpl getConstructorDoc(MethodSymbol meth) {
assert meth.isConstructor() : "expecting a constructor symbol";
ConstructorDocImpl result = (ConstructorDocImpl)methodMap.get(meth); ConstructorDocImpl result = (ConstructorDocImpl)methodMap.get(meth);
if (result != null) return result; if (result != null) return result;
result = new ConstructorDocImpl(this, meth); result = new ConstructorDocImpl(this, meth);
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
package com.sun.tools.javah; package com.sun.tools.javah;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
...@@ -74,6 +75,7 @@ import javax.tools.ToolProvider; ...@@ -74,6 +75,7 @@ import javax.tools.ToolProvider;
import static javax.tools.Diagnostic.Kind.*; import static javax.tools.Diagnostic.Kind.*;
import com.sun.tools.javac.code.Symbol.CompletionFailure; import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.main.CommandLine;
/** /**
* Javah generates support files for native methods. * Javah generates support files for native methods.
...@@ -362,7 +364,7 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask { ...@@ -362,7 +364,7 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
if (fileManager == null) if (fileManager == null)
fileManager = getDefaultFileManager(diagnosticListener, log); fileManager = getDefaultFileManager(diagnosticListener, log);
Iterator<String> iter = args.iterator(); Iterator<String> iter = expandAtArgs(args).iterator();
noArgs = !iter.hasNext(); noArgs = !iter.hasNext();
while (iter.hasNext()) { while (iter.hasNext()) {
...@@ -416,6 +418,18 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask { ...@@ -416,6 +418,18 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
throw new BadArgs("err.unknown.option", name).showUsage(true); throw new BadArgs("err.unknown.option", name).showUsage(true);
} }
private Iterable<String> expandAtArgs(Iterable<String> args) throws BadArgs {
try {
List<String> l = new ArrayList<String>();
for (String arg: args) l.add(arg);
return Arrays.asList(CommandLine.parse(l.toArray(new String[l.size()])));
} catch (FileNotFoundException e) {
throw new BadArgs("at.args.file.not.found", e.getLocalizedMessage());
} catch (IOException e) {
throw new BadArgs("at.args.io.exception", e.getLocalizedMessage());
}
}
public Boolean call() { public Boolean call() {
return run(); return run();
} }
...@@ -607,8 +621,8 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask { ...@@ -607,8 +621,8 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
} }
}; };
} }
private String getMessage(String key, Object... args) { private String getMessage(String key, Object... args) {
return getMessage(task_locale, key, args); return getMessage(task_locale, key, args);
} }
......
...@@ -30,6 +30,8 @@ cant.create.dir=\ ...@@ -30,6 +30,8 @@ cant.create.dir=\
The directory {0} could not be create for output. The directory {0} could not be create for output.
at.args.cant.read=\ at.args.cant.read=\
Can''t read command line arguments from file {1}. Can''t read command line arguments from file {1}.
at.args.file.not.found=\
Can''t find file {0}.
at.args.io.exception=\ at.args.io.exception=\
The following I/O problem was encountered when processing an @ \ The following I/O problem was encountered when processing an @ \
argument on the command line: {0}. argument on the command line: {0}.
......
/*
* Copyright (c) 2010, 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 6993301
* @summary catch parameters do not have correct kind (i.e. ElementKind.EXCEPTION_PARAMETER)
*/
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
import com.sun.tools.javac.api.JavacTaskImpl;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
/**
*
* @author Jan Lahoda
*/
public class T6993301 {
public static void main(String... args) throws Exception {
new T6993301().testExceptionParameterCorrectKind();
}
static class MyFileObject extends SimpleJavaFileObject {
private String text;
public MyFileObject(String text) {
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
this.text = text;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return text;
}
}
public void testExceptionParameterCorrectKind() throws IOException {
final String bootPath = System.getProperty("sun.boot.class.path");
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
assert tool != null;
String code = "package test; public class Test { { try { } catch (NullPointerException ex) {} } }";
final JavacTaskImpl ct = (JavacTaskImpl)tool.getTask(null, null, null,
Arrays.asList("-bootclasspath", bootPath),
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ct.analyze();
new TreePathScanner<Void, Void>() {
@Override
public Void visitVariable(VariableTree node, Void p) {
Element el = Trees.instance(ct).getElement(getCurrentPath());
assertNotNull(el);
assertEquals(ElementKind.EXCEPTION_PARAMETER, el.getKind());
return super.visitVariable(node, p);
}
}.scan(cut, null);
}
private void assertNotNull(Object o) {
if (o == null)
throw new AssertionError();
}
private <T> void assertEquals(T expected, T actual) {
if (expected == null ? actual == null : expected.equals(actual))
return;
throw new AssertionError("expected: " + expected + ", actual: " + actual);
}
}
...@@ -16,5 +16,5 @@ ...@@ -16,5 +16,5 @@
} }
@A(b = @B(b2 = 1, b2 = 2), @A(b = @B(b2 = 1, b2 = 2),
b_arr = {@B(), @B(b2 = 1, b2 = 2)}) b_arr = {@B(), @B(b2 = 1, b2 = 2)})
class T6881115<@A(b = @B(b2 = 1, b2 = 2), class T6881115</*308 @A(b = @B(b2 = 1, b2 = 2),
b_arr = {@B(), @B(b2 = 1, b2 = 2)}) X> {} b_arr = {@B(), @B(b2 = 1, b2 = 2)})*/ X> {}
...@@ -8,9 +8,4 @@ T6881115.java:17:8: compiler.err.annotation.missing.default.value: B, b1 ...@@ -8,9 +8,4 @@ T6881115.java:17:8: compiler.err.annotation.missing.default.value: B, b1
T6881115.java:18:13: compiler.err.annotation.missing.default.value.1: B, b1,b2 T6881115.java:18:13: compiler.err.annotation.missing.default.value.1: B, b1,b2
T6881115.java:18:30: compiler.err.duplicate.annotation.member.value: b2, B T6881115.java:18:30: compiler.err.duplicate.annotation.member.value: b2, B
T6881115.java:18:19: compiler.err.annotation.missing.default.value: B, b1 T6881115.java:18:19: compiler.err.annotation.missing.default.value: B, b1
T6881115.java:19:34: compiler.err.duplicate.annotation.member.value: b2, B 10 errors
T6881115.java:19:23: compiler.err.annotation.missing.default.value: B, b1
T6881115.java:20:28: compiler.err.annotation.missing.default.value.1: B, b1,b2
T6881115.java:20:45: compiler.err.duplicate.annotation.member.value: b2, B
T6881115.java:20:34: compiler.err.annotation.missing.default.value: B, b1
15 errors
...@@ -21,13 +21,9 @@ ...@@ -21,13 +21,9 @@
* questions. * questions.
*/ */
// key: compiler.err.type.annotations.not.supported.in.source // key: compiler.warn.diamond.redundant.args
// options: -source 6 // options: -XDfindDiamond
@interface Anno { } class Foo<X> {
Foo<String> fs = new Foo<String>();
class TypeAnnotationsNotSupported {
void m() {
int i = (@Anno int) 3.14;
}
} }
...@@ -21,15 +21,9 @@ ...@@ -21,15 +21,9 @@
* questions. * questions.
*/ */
/* // key: compiler.warn.diamond.redundant.args.1
* @test // options: -XDfindDiamond
* @bug 6967002
* @summary JDK7 b99 javac compilation error (java.lang.AssertionError) class Foo<X> {
* @author Maurizio Cimadamore Foo<?> fs = new Foo<String>();
* @compile/fail/ref=T6967002.out -XDrawDiagnostics T6967002.java
*/
class Test {
private static void m(byte[] octets) {
return m(octets..., ?);
}
} }
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/* /*
* @test * @test
* @bug 6337171 * @bug 6337171 6996415
* @ignore fix has been disabled as a consequence of 6996415
* @summary javac should create bridge methods when type variable bounds restricted * @summary javac should create bridge methods when type variable bounds restricted
* @run main OverrideBridge * @run main OverrideBridge
*/ */
......
/*
* @test /nodynamiccopyright/
* @bug 6939780
*
* @summary add a warning to detect diamond sites
* @author mcimadamore
* @compile/ref=T6939780.out T6939780.java -XDrawDiagnostics -XDfindDiamond
*
*/
class T6939780 {
void test() {
class Foo<X extends Number> {
Foo() {}
Foo(X x) {}
}
Foo<Number> f1 = new Foo<Number>(1);
Foo<?> f2 = new Foo<Number>();
Foo<?> f3 = new Foo<Integer>();
Foo<Number> f4 = new Foo<Number>(1) {};
Foo<?> f5 = new Foo<Number>() {};
Foo<?> f6 = new Foo<Integer>() {};
}
}
T6939780.java:19:28: compiler.warn.diamond.redundant.args: Foo<java.lang.Number>, Foo<java.lang.Number>
T6939780.java:20:28: compiler.warn.diamond.redundant.args.1: Foo<java.lang.Integer>, Foo<java.lang.Number>
T6939780.java:22:28: compiler.warn.diamond.redundant.args: Foo<java.lang.Number>, Foo<java.lang.Number>
T6939780.java:23:28: compiler.warn.diamond.redundant.args.1: Foo<java.lang.Integer>, Foo<java.lang.Number>
4 warnings
SemanticErrorTest.java:11:46: compiler.err.repeated.interface
1 error
SemanticErrorTest.java:11:46: compiler.err.repeated.interface
- compiler.err.proc.messager: Deliberate Error
SemanticErrorTest.java:11:46: compiler.err.repeated.interface
1 error
/*
* @test /nodynamiccopyright/
* @bug 6994946
* @summary option to specify only syntax errors as unrecoverable
* @library ../../lib
* @build JavacTestingAbstractProcessor TestProcessor
* @compile/fail/ref=SemanticErrorTest.1.out -XDrawDiagnostics -processor TestProcessor SemanticErrorTest.java
* @compile/fail/ref=SemanticErrorTest.2.out -XDrawDiagnostics -XDonlySyntaxErrorsUnrecoverable -processor TestProcessor SemanticErrorTest.java
*/
class SemanticErrorTest implements Runnable, Runnable {
public void run() { }
}
/*
* @test /nodynamiccopyright/
* @bug 6994946
* @summary option to specify only syntax errors as unrecoverable
* @library ../../lib
* @build JavacTestingAbstractProcessor TestProcessor
* @compile/fail/ref=SyntaxErrorTest.out -XDrawDiagnostics -processor TestProcessor SyntaxErrorTest.java
* @compile/fail/ref=SyntaxErrorTest.out -XDrawDiagnostics -XDonlySyntaxErrorsUnrecoverable -processor TestProcessor SyntaxErrorTest.java
*/
class SyntaxErrorTest {
int i
}
SyntaxErrorTest.java:12:10: compiler.err.expected: ';'
1 error
...@@ -21,24 +21,20 @@ ...@@ -21,24 +21,20 @@
* questions. * questions.
*/ */
/* import java.util.*;
* @test import javax.annotation.processing.*;
* @build DA TA Test TestProcessor import javax.lang.model.*;
* @compile -proc:only -processor TestProcessor AnnoTreeTests.java import javax.lang.model.element.*;
*/ import static javax.tools.Diagnostic.Kind.*;
@Test(6) public class TestProcessor extends JavacTestingAbstractProcessor {
class AnnoTreeTests { private int round = 0;
// primitive types
@DA("int") int i1;
int i2 = (@TA("int") int) 0;
// simple array types public boolean process(Set<? extends TypeElement> annotations,
@DA("int[]") int[] a1; RoundEnvironment roundEnv) {
int @TA("int") [] a2; if (++round == 1)
int[] a3 = (@TA("int[]") int[]) a1; messager.printMessage(ERROR, "Deliberate Error");
int[] a4 = (int @TA("int") []) a1; return false;
}
// multi-dimensional array types
// (still to come)
} }
...@@ -78,7 +78,7 @@ public class TestAnonClassNames { ...@@ -78,7 +78,7 @@ public class TestAnonClassNames {
@Nesting(LOCAL) @Nesting(LOCAL)
class LocalClass{}; class LocalClass{};
Object o = new @Nesting(ANONYMOUS) Object() { // An anonymous annotated class Object o = new /*@Nesting(ANONYMOUS)*/ Object() { // An anonymous annotated class
public String toString() { public String toString() {
return "I have no name!"; return "I have no name!";
} }
...@@ -95,9 +95,10 @@ public class TestAnonClassNames { ...@@ -95,9 +95,10 @@ public class TestAnonClassNames {
for(Class<?> clazz : classes) { for(Class<?> clazz : classes) {
String name = clazz.getName(); String name = clazz.getName();
Nesting anno = clazz.getAnnotation(Nesting.class);
System.out.format("%s is %s%n", System.out.format("%s is %s%n",
clazz.getName(), clazz.getName(),
clazz.getAnnotation(Nesting.class).value()); anno == null ? "(unset/ANONYMOUS)" : anno.value());
testClassName(name); testClassName(name);
} }
} }
...@@ -161,8 +162,8 @@ class ClassNameProber extends JavacTestingAbstractProcessor { ...@@ -161,8 +162,8 @@ class ClassNameProber extends JavacTestingAbstractProcessor {
typeElt.getQualifiedName().toString(), typeElt.getQualifiedName().toString(),
typeElt.getKind().toString(), typeElt.getKind().toString(),
nestingKind.toString()); nestingKind.toString());
Nesting anno = typeElt.getAnnotation(Nesting.class);
if (typeElt.getAnnotation(Nesting.class).value() != nestingKind) { if ((anno == null ? NestingKind.ANONYMOUS : anno.value()) != nestingKind) {
throw new RuntimeException("Mismatch of expected and reported nesting kind."); throw new RuntimeException("Mismatch of expected and reported nesting kind.");
} }
} }
......
...@@ -357,7 +357,9 @@ public class TreePosTest { ...@@ -357,7 +357,9 @@ public class TreePosTest {
check("encl.start <= start", encl, self, encl.start <= self.start); check("encl.start <= start", encl, self, encl.start <= self.start);
check("start <= pos", encl, self, self.start <= self.pos); check("start <= pos", encl, self, self.start <= self.pos);
if (!(self.tag == JCTree.TYPEARRAY if (!(self.tag == JCTree.TYPEARRAY
&& (encl.tag == JCTree.VARDEF || encl.tag == JCTree.TYPEARRAY))) { && (encl.tag == JCTree.VARDEF ||
encl.tag == JCTree.METHODDEF ||
encl.tag == JCTree.TYPEARRAY))) {
check("encl.pos <= start || end <= encl.pos", check("encl.pos <= start || end <= encl.pos",
encl, self, encl.pos <= self.start || self.end <= encl.pos); encl, self, encl.pos <= self.start || self.end <= encl.pos);
} }
......
T6967002.java:33:22: compiler.err.expected: ')'
T6967002.java:33:25: compiler.err.illegal.start.of.expr
T6967002.java:33:28: compiler.err.illegal.start.of.expr
T6967002.java:33:29: compiler.err.illegal.start.of.expr
T6967002.java:33:27: compiler.err.not.stmt
T6967002.java:33:30: compiler.err.expected: ';'
T6967002.java:35:2: compiler.err.premature.eof
7 errors
/*
* Copyright (c) 2009, 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 6843077
* @summary compiler crashes when visiting inner classes
* @author Mahmood Ali
* @compile -source 1.7 InnerClass.java
*/
class InnerClass {
InnerClass() {}
InnerClass(Object o) {}
private void a() {
new Object() {
public <R> void method() { }
};
}
Object f1 = new InnerClass() {
<R> void method() { }
};
Object f2 = new InnerClass() {
<@A R> void method() { }
};
Object f3 = new InnerClass(null) {
<R> void method() { }
};
Object f4 = new InnerClass(null) {
<@A R> void method() { }
};
@interface A { }
}
/*
* Copyright (c) 2008, 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 6843077
* @summary check that type annotations may appear on void method if it is a
* method annotation too.
* @author Mahmood Ali
* @compile -source 1.7 MultipleTargets.java
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
class TypeUseTarget<K extends @A Object> {
@A void voidMethod() { }
}
@Target({ElementType.TYPE_USE, ElementType.METHOD})
@interface A { }
/*
* Copyright (c) 2008, 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 6843077
* @summary check that type annotations may appear on all type parameter
* @author Mahmood Ali
* @compile -source 1.7 TypeParameterTarget.java
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
class TypeUseTarget<@A K extends Object> {
String[] field;
<@A K, @A V> String genericMethod(K k) { return null; }
}
interface MyInterface { }
@interface MyAnnotation { }
@Target(ElementType.TYPE_PARAMETER)
@interface A { }
/*
* Copyright (c) 2008, 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 6843077
* @summary check that type annotations may appear on all type declarations
* @author Mahmood Ali
* @compile -source 1.7 TypeUseTarget.java
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@A
class TypeUseTarget<K extends @A Object> {
@A String @A [] field;
@A String test(@A String param, @A String @A ... vararg) @A {
@A Object o = new @A String @A [3];
TypeUseTarget<@A String> target;
return (@A String) null;
}
<K> @A String genericMethod(K k) { return null; }
}
@A
interface MyInterface { }
@A
@interface MyAnnotation { }
@Target(ElementType.TYPE_USE)
@interface A { }
/*
* Copyright (c) 2008, 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 6843077
* @summary test scopes of attribution
* @author Mahmood Ali
* @compile -source 1.7 Scopes.java
*/
class Scopes {
void test() @A(VALUE) { }
void test1() @A(value=VALUE) { }
private static final int VALUE = 1;
@interface A { int value(); }
}
/*
* Copyright (c) 2009, 2010, 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.
*/
import java.io.*;
import java.net.URL;
import java.util.List;
import com.sun.tools.classfile.*;
/*
* @test
* @bug 6917130
* @summary test that optimized away annotations are not emited to classfile
*/
public class DeadCode {
public static void main(String[] args) throws Exception {
new DeadCode().run();
}
public void run() throws Exception {
ClassFile cf = getClassFile("DeadCode$Test.class");
test(cf);
for (Field f : cf.fields) {
test(cf, f);
}
for (Method m: cf.methods) {
test(cf, m);
}
countAnnotations();
if (errors > 0)
throw new Exception(errors + " errors found");
System.out.println("PASSED");
}
ClassFile getClassFile(String name) throws IOException, ConstantPoolException {
URL url = getClass().getResource(name);
InputStream in = url.openStream();
try {
return ClassFile.read(in);
} finally {
in.close();
}
}
/************ Helper annotations counting methods ******************/
void test(ClassFile cf) {
test(cf, Attribute.RuntimeVisibleTypeAnnotations, true);
test(cf, Attribute.RuntimeInvisibleTypeAnnotations, false);
}
void test(ClassFile cf, Method m) {
test(cf, m, Attribute.RuntimeVisibleTypeAnnotations, true);
test(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, false);
}
void test(ClassFile cf, Field m) {
test(cf, m, Attribute.RuntimeVisibleTypeAnnotations, true);
test(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, false);
}
// test the result of Attributes.getIndex according to expectations
// encoded in the method's name
void test(ClassFile cf, String name, boolean visible) {
int index = cf.attributes.getIndex(cf.constant_pool, name);
if (index != -1) {
Attribute attr = cf.attributes.get(index);
assert attr instanceof RuntimeTypeAnnotations_attribute;
RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr;
all += tAttr.annotations.length;
if (visible)
visibles += tAttr.annotations.length;
else
invisibles += tAttr.annotations.length;
}
}
// test the result of Attributes.getIndex according to expectations
// encoded in the method's name
void test(ClassFile cf, Method m, String name, boolean visible) {
int index = m.attributes.getIndex(cf.constant_pool, name);
if (index != -1) {
Attribute attr = m.attributes.get(index);
assert attr instanceof RuntimeTypeAnnotations_attribute;
RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr;
all += tAttr.annotations.length;
if (visible)
visibles += tAttr.annotations.length;
else
invisibles += tAttr.annotations.length;
}
}
// test the result of Attributes.getIndex according to expectations
// encoded in the method's name
void test(ClassFile cf, Field m, String name, boolean visible) {
int index = m.attributes.getIndex(cf.constant_pool, name);
if (index != -1) {
Attribute attr = m.attributes.get(index);
assert attr instanceof RuntimeTypeAnnotations_attribute;
RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr;
all += tAttr.annotations.length;
if (visible)
visibles += tAttr.annotations.length;
else
invisibles += tAttr.annotations.length;
}
}
void countAnnotations() {
int expected_all = expected_visibles + expected_invisibles;
if (expected_all != all) {
errors++;
System.err.println("expected " + expected_all
+ " annotations but found " + all);
}
if (expected_visibles != visibles) {
errors++;
System.err.println("expected " + expected_visibles
+ " visibles annotations but found " + visibles);
}
if (expected_invisibles != invisibles) {
errors++;
System.err.println("expected " + expected_invisibles
+ " invisibles annotations but found " + invisibles);
}
}
int errors;
int all;
int visibles;
int invisibles;
/*********************** Test class *************************/
static int expected_invisibles = 1;
static int expected_visibles = 0;
static class Test {
@interface A {}
void test() {
List<? extends @A Object> o = null;
o.toString();
@A String m;
if (false) {
@A String a;
@A String b = "m";
b.toString();
List<? extends @A Object> c = null;
c.toString();
}
}
}
}
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary test that only java 7 allows type annotations
* @author Mahmood Ali
* @compile/fail/ref=AnnotationVersion.out -XDrawDiagnostics -source 1.6 AnnotationVersion.java
*/
class AnnotationVersion {
public void method() @A { }
}
@interface A { }
AnnotationVersion.java:9:25: compiler.err.type.annotations.not.supported.in.source: 1.6
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary test incomplete array declaration
* @author Mahmood Ali
* @compile/fail/ref=IncompleteArray.out -XDrawDiagnostics -source 1.7 IncompleteArray.java
*/
class IncompleteArray {
int @A [] @A var;
}
@interface A { }
IncompleteArray.java:9:13: compiler.err.illegal.start.of.type
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary test incomplete vararg declaration
* @author Mahmood Ali
* @compile/fail/ref=IncompleteVararg.out -XDrawDiagnostics -source 1.7 IncompleteVararg.java
*/
class IncompleteArray {
// the last variable may be vararg
void method(int @A test) { }
}
@interface A { }
IncompleteVararg.java:10:19: compiler.err.illegal.start.of.type
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary test indexing of an array
* @author Mahmood Ali
* @compile/fail/ref=IndexArray.out -XDrawDiagnostics -source 1.7 IndexArray.java
*/
class IndexArray {
int[] var;
int a = var @A [1];
}
@interface A { }
IndexArray.java:10:15: compiler.err.illegal.start.of.expr
1 error
import java.util.List;
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary test that compiler doesn't warn about annotated redundant casts
* @author Mahmood Ali
* @compile/ref=LintCast.out -Xlint:cast -XDrawDiagnostics -source 1.7 LintCast.java
*/
class LintCast {
void unparameterized() {
String s = "m";
String s1 = (String)s;
String s2 = (@A String)s;
}
void parameterized() {
List<String> l = null;
List<String> l1 = (List<String>)l;
List<String> l2 = (List<@A String>)l;
}
void array() {
int @A [] a = null;
int[] a1 = (int[])a;
int[] a2 = (int @A [])a;
}
void sameAnnotations() {
@A String annotated = null;
String unannotated = null;
// compiler ignore annotated casts even if redundant
@A String anno1 = (@A String)annotated;
// warn if redundant without an annotation
String anno2 = (String)annotated;
String unanno2 = (String)unannotated;
}
}
@interface A { }
LintCast.java:13:21: compiler.warn.redundant.cast: java.lang.String
LintCast.java:19:27: compiler.warn.redundant.cast: java.util.List<java.lang.String>
LintCast.java:25:20: compiler.warn.redundant.cast: int[]
LintCast.java:37:24: compiler.warn.redundant.cast: java.lang.String
LintCast.java:38:26: compiler.warn.redundant.cast: java.lang.String
5 warnings
/*
* Copyright (c) 2008, 2009, 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 6843077
* @summary test old array syntax
* @author Mahmood Ali
* @compile/fail -XDrawDiagnostics -source 1.7 OldArray.java
*/
class OldArray {
String [@A] s() { return null; }
}
@interface A { }
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check that A is accessible in the class type parameters
* @author Mahmood Ali
* @compile/fail/ref=Scopes.out -XDrawDiagnostics -source 1.7 Scopes.java
*/
class Scopes<T extends @UniqueInner Object> {
@interface UniqueInner { };
}
Scopes.java:8:25: compiler.err.cant.resolve: kindname.class, UniqueInner, ,
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary static field access isn't a valid location
* @author Mahmood Ali
* @compile/fail/ref=StaticFields.out -XDrawDiagnostics -source 1.7 StaticFields.java
*/
class C {
int f;
int a = @A C.f;
}
@interface A { }
StaticFields.java:10:17: compiler.err.illegal.start.of.expr
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary static methods don't have receivers
* @author Mahmood Ali
* @compile/fail/ref=StaticMethods.out -XDrawDiagnostics -source 1.7 StaticMethods.java
*/
class StaticMethods {
static void main() @A { }
}
@interface A { }
StaticMethods.java:9:22: compiler.err.annotation.type.not.applicable
1 error
/*
* Copyright (c) 2008, 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 6843077
* @summary test type annotation on void generic methods
* @author Mahmood Ali
* @compile/fail -source 1.7 VoidGenericMethod.java
*/
class VoidGenericMethod {
public <T> @A void method() { }
}
@interface A { }
/*
* @test /nodynamiccopyright/
* @bug 6843077 6919944
* @summary check for duplicate annotation values
* @author Mahmood Ali
* @compile/fail/ref=DuplicateAnnotationValue.out -XDrawDiagnostics -source 1.7 DuplicateAnnotationValue.java
*/
class DuplicateAnnotationValue {
void test() {
Object a = String @A(value = 2, value = 1) [].class;
}
}
@interface A { int value(); }
DuplicateAnnotationValue.java:10:37: compiler.err.duplicate.annotation.member.value: value, A
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for duplicate annotations
* @author Mahmood Ali
* @compile/fail/ref=DuplicateTypeAnnotation.out -XDrawDiagnostics -source 1.7 DuplicateTypeAnnotation.java
*/
class DuplicateTypeAnnotation {
void test() {
Object a = String @A @A [].class;
}
}
@interface A { }
DuplicateTypeAnnotation.java:11:26: compiler.err.duplicate.annotation
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for invalid annotatins given the target
* @author Mahmood Ali
* @compile/fail/ref=InvalidLocation.out -XDrawDiagnostics -source 1.7 InvalidLocation.java
*/
class InvalidLocation {
void test() {
Object a = String @A [].class;
}
}
@java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE)
@interface A { }
InvalidLocation.java:11:23: compiler.err.annotation.type.not.applicable
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for missing annotation value
* @author Mahmood Ali
* @compile/fail/ref=MissingAnnotationValue.out -XDrawDiagnostics -source 1.7 MissingAnnotationValue.java
*/
class MissingAnnotationValue {
void test() {
Object a = String @A [].class;
}
}
@interface A { int field(); }
MissingAnnotationValue.java:10:23: compiler.err.annotation.missing.default.value: A, field
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077 6919944
* @summary check for duplicate annotation values
* @author Mahmood Ali
* @compile/fail/ref=DuplicateAnnotationValue.out -XDrawDiagnostics -source 1.7 DuplicateAnnotationValue.java
*/
class DuplicateAnnotationValue {
void test() {
String @A(value = 2, value = 1) [] s;
}
}
@interface A { int value(); }
DuplicateAnnotationValue.java:10:26: compiler.err.duplicate.annotation.member.value: value, A
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for duplicate annotations
* @author Mahmood Ali
* @compile/fail/ref=DuplicateTypeAnnotation.out -XDrawDiagnostics -source 1.7 DuplicateTypeAnnotation.java
*/
class DuplicateTypeAnnotation {
void test() {
String @A @A [] s;
}
}
@interface A { }
DuplicateTypeAnnotation.java:11:15: compiler.err.duplicate.annotation
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for invalid annotatins given the target
* @author Mahmood Ali
* @compile/fail/ref=InvalidLocation.out -XDrawDiagnostics -source 1.7 InvalidLocation.java
*/
class InvalidLocation {
void test() {
String @A [] s;
}
}
@java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE)
@interface A { }
InvalidLocation.java:11:12: compiler.err.annotation.type.not.applicable
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for missing annotation value
* @author Mahmood Ali
* @compile/fail/ref=MissingAnnotationValue.out -XDrawDiagnostics -source 1.7 MissingAnnotationValue.java
*/
class MissingAnnotationValue {
void test() {
String @A [] s;
}
}
@interface A { int field(); }
MissingAnnotationValue.java:10:12: compiler.err.annotation.missing.default.value: A, field
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077 6919944
* @summary check for duplicate annotation values for type parameter
* @author Mahmood Ali
* @compile/fail/ref=DuplicateAnnotationValue.out -XDrawDiagnostics -source 1.7 DuplicateAnnotationValue.java
*/
class DuplicateAnnotationValue {
void method() {
class Inner<@A(value = 2, value = 1) K> {}
}
}
@interface A { int value(); }
DuplicateAnnotationValue.java:10:31: compiler.err.duplicate.annotation.member.value: value, A
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for duplicate annotations
* @author Mahmood Ali
* @compile/fail/ref=DuplicateTypeAnnotation.out -XDrawDiagnostics -source 1.7 DuplicateTypeAnnotation.java
*/
class DuplicateTypeAnno {
void innermethod() {
class Inner<@A @A K> { }
}
}
@interface A { }
DuplicateTypeAnnotation.java:10:20: compiler.err.duplicate.annotation
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for invalid annotatins given the target
* @author Mahmood Ali
* @compile/fail/ref=InvalidLocation.out -XDrawDiagnostics -source 1.7 InvalidLocation.java
*/
class InvalidLocation {
void innermethod() {
class Inner<@A K> {}
}
}
@java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE)
@interface A { }
InvalidLocation.java:10:17: compiler.err.annotation.type.not.applicable
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077
* @summary check for missing annotation value
* @author Mahmood Ali
* @compile/fail/ref=MissingAnnotationValue.out -XDrawDiagnostics -source 1.7 MissingAnnotationValue.java
*/
class MissingAnnotationValue {
void innermethod() {
class Inner<@A K> { }
}
}
@interface A { int field(); }
MissingAnnotationValue.java:10:17: compiler.err.annotation.missing.default.value: A, field
1 error
/*
* @test /nodynamiccopyright/
* @bug 6843077 6919944
* @summary check for duplicate annotation values
* @author Mahmood Ali
* @compile/fail/ref=DuplicateAnnotationValue.out -XDrawDiagnostics -source 1.7 DuplicateAnnotationValue.java
*/
class DuplicateAnnotationValue {
void test() {
String[] a = new String @A(value = 2, value = 1) [5] ;
}
}
@interface A { int value(); }
DuplicateAnnotationValue.java:10:43: compiler.err.duplicate.annotation.member.value: value, A
1 error
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册