This commit is contained in:
Lana Steuck 2010-11-09 22:54:48 -08:00
commit 1b5984baee
194 changed files with 708 additions and 4531 deletions

View File

@ -1,47 +0,0 @@
/*
* 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();
}

View File

@ -28,13 +28,13 @@ package com.sun.source.tree;
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
*
* @since 1.7
*/
public interface DisjointTypeTree extends Tree {
List<? extends Tree> getTypeComponents();
public interface DisjunctiveTypeTree extends Tree {
List<? extends Tree> getTypeAlternatives();
}

View File

@ -53,7 +53,7 @@ public interface MethodTree extends Tree {
Tree getReturnType();
List<? extends TypeParameterTree> getTypeParameters();
List<? extends VariableTree> getParameters();
List<? extends AnnotationTree> getReceiverAnnotations();
//308 List<? extends AnnotationTree> getReceiverAnnotations();
List<? extends ExpressionTree> getThrows();
BlockTree getBody();
Tree getDefaultValue(); // for annotation types

View File

@ -46,7 +46,7 @@ public interface Tree {
*/
public enum Kind {
ANNOTATED_TYPE(AnnotatedTypeTree.class),
//308 ANNOTATED_TYPE(AnnotatedTypeTree.class),
/**
* Used for instances of {@link AnnotationTree}.
@ -234,9 +234,9 @@ public interface Tree {
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}.

View File

@ -57,7 +57,7 @@ package com.sun.source.tree;
* @since 1.6
*/
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 visitMethodInvocation(MethodInvocationTree node, P p);
R visitAssert(AssertTree node, P p);
@ -96,7 +96,7 @@ public interface TreeVisitor<R,P> {
R visitCompilationUnit(CompilationUnitTree node, P p);
R visitTry(TryTree 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 visitTypeCast(TypeCastTree node, P p);
R visitPrimitiveType(PrimitiveTypeTree node, P p);

View File

@ -47,5 +47,5 @@ import javax.lang.model.element.Name;
public interface TypeParameterTree extends Tree {
Name getName();
List<? extends Tree> getBounds();
List<? extends AnnotationTree> getAnnotations();
//308 List<? extends AnnotationTree> getAnnotations();
}

View File

@ -1,245 +0,0 @@
/*
* 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);
}
}
}

View File

@ -228,7 +228,7 @@ public class SimpleTreeVisitor <R,P> implements TreeVisitor<R,P> {
return defaultAction(node, p);
}
public R visitDisjointType(DisjointTypeTree node, P p) {
public R visitDisjunctiveType(DisjunctiveTypeTree node, P p) {
return defaultAction(node, p);
}
@ -248,9 +248,9 @@ public class SimpleTreeVisitor <R,P> implements TreeVisitor<R,P> {
return defaultAction(node, p);
}
public R visitAnnotatedType(AnnotatedTypeTree node, P p) {
return defaultAction(node, p);
}
//308 public R visitAnnotatedType(AnnotatedTypeTree node, P p) {
//308 return defaultAction(node, p);
//308 }
public R visitErroneous(ErroneousTree node, P p) {
return defaultAction(node, p);

View File

@ -138,7 +138,7 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> {
r = scanAndReduce(node.getReturnType(), p, r);
r = scanAndReduce(node.getTypeParameters(), 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.getBody(), p, r);
r = scanAndReduce(node.getDefaultValue(), p, r);
@ -356,13 +356,13 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> {
return r;
}
public R visitDisjointType(DisjointTypeTree node, P p) {
return scan(node.getTypeComponents(), p);
public R visitDisjunctiveType(DisjunctiveTypeTree node, P p) {
return scan(node.getTypeAlternatives(), p);
}
public R visitTypeParameter(TypeParameterTree node, P p) {
R r = scan(node.getAnnotations(), p);
r = scanAndReduce(node.getBounds(), p, r);
R r = scan(node.getBounds(), p);
//308 R r = scanAndReduce(node.getAnnotations(), p, r);
return r;
}
@ -380,11 +380,11 @@ public class TreeScanner<R,P> implements TreeVisitor<R,P> {
return r;
}
public R visitAnnotatedType(AnnotatedTypeTree node, P p) {
R r = scan(node.getAnnotations(), p);
r = scanAndReduce(node.getUnderlyingType(), p, r);
return r;
}
//308 public R visitAnnotatedType(AnnotatedTypeTree node, P p) {
//308 R r = scan(node.getAnnotations(), p);
//308 r = scanAndReduce(node.getUnderlyingType(), p, r);
//308 return r;
//308 }
public R visitOther(Tree node, P p) {
return null;

View File

@ -282,9 +282,10 @@ public class JavacTrees extends Trees {
// System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
env = enter.getTopLevelEnv((JCCompilationUnit)tree);
break;
case ANNOTATION_TYPE:
case CLASS:
case INTERFACE:
case ENUM:
case INTERFACE:
// System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
env = enter.getClassEnv(((JCClassDecl)tree).sym);
break;

View File

@ -231,9 +231,9 @@ public class Flags {
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.

View File

@ -55,8 +55,8 @@ public class TypeAnnotations {
}
public void taFillAndLift(JCClassDecl tree, boolean visitBodies) {
new TypeAnnotationPositions().scan(tree);
new TypeAnnotationLift().scan(tree);
//308 new TypeAnnotationPositions().scan(tree);
//308 new TypeAnnotationLift().scan(tree);
}
private static class TypeAnnotationPositions extends TreeScanner {
@ -113,9 +113,10 @@ public class TypeAnnotations {
p.pos = frame.pos;
return p;
case ANNOTATION_TYPE:
case CLASS:
case INTERFACE:
case ENUM:
case INTERFACE:
p.pos = frame.pos;
if (((JCClassDecl)frame).extending == tree) {
p.type = TargetType.CLASS_EXTENDS;
@ -208,11 +209,11 @@ public class TypeAnnotations {
}
return p;
case ANNOTATED_TYPE: {
List<JCTree> newPath = path.tail;
return resolveFrame(newPath.head, newPath.tail.head,
newPath, p);
}
//308 case ANNOTATED_TYPE: {
//308 List<JCTree> newPath = path.tail;
//308 return resolveFrame(newPath.head, newPath.tail.head,
//308 newPath, p);
//308 }
case METHOD_INVOCATION: {
JCMethodInvocation invocation = (JCMethodInvocation)frame;

View File

@ -121,6 +121,8 @@ public class Attr extends JCTree.Visitor {
sourceName = source.name;
relax = (options.isSet("-retrofit") ||
options.isSet("-relax"));
findDiamonds = options.get("findDiamond") != null &&
source.allowDiamond();
useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
enableSunApiLintControl = options.isSet("enableSunApiLintControl");
}
@ -154,6 +156,16 @@ public class Attr extends JCTree.Visitor {
*/
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?
* RFE: 6425594
@ -1053,9 +1065,9 @@ public class Attr extends JCTree.Visitor {
if ((c.param.sym.flags() & FINAL) == 0) {
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);
}
chk.checkType(c.param.vartype.pos(),
@ -1572,6 +1584,24 @@ public class Attr extends JCTree.Visitor {
if (TreeInfo.isDiamond(tree)) {
clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
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...
@ -2839,9 +2869,9 @@ public class Attr extends JCTree.Visitor {
result = check(tree, owntype, TYP, pkind, pt);
}
public void visitTypeDisjoint(JCTypeDisjoint tree) {
List<Type> componentTypes = attribTypes(tree.components, env);
tree.type = result = check(tree, types.lub(componentTypes), TYP, pkind, pt);
public void visitTypeDisjunction(JCTypeDisjunction tree) {
List<Type> alternatives = attribTypes(tree.alternatives, env);
tree.type = result = check(tree, types.lub(alternatives), TYP, pkind, pt);
}
public void visitTypeParameter(JCTypeParameter tree) {

View File

@ -371,7 +371,7 @@ public class Flow extends TreeScanner {
if (sym.adr >= firstadr && trackable(sym)) {
if ((sym.flags() & FINAL) != 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",
sym);
}
@ -983,7 +983,7 @@ public class Flow extends TreeScanner {
thrown = List.nil();
for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
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);
for (JCExpression ct : subClauses) {
caught = chk.incl(ct.type, caught);
@ -1049,7 +1049,7 @@ public class Flow extends TreeScanner {
alive = true;
JCVariableDecl param = l.head.param;
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<Type> ctypes = List.nil();
List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);

View File

@ -876,7 +876,8 @@ public class TransTypes extends TreeTranslator {
make.at(tree.pos);
if (addBridges) {
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)
addBridges(tree.pos(), tree.sym, bridges);
tree.defs = bridges.toList().prependList(tree.defs);

View File

@ -1456,7 +1456,7 @@ public class Gen extends JCTree.Visitor {
List<Integer> gaps) {
if (startpc != endpc) {
List<JCExpression> subClauses = TreeInfo.isMultiCatch(tree) ?
((JCTypeDisjoint)tree.param.vartype).components :
((JCTypeDisjunction)tree.param.vartype).alternatives :
List.of(tree.param.vartype);
while (gaps.nonEmpty()) {
for (JCExpression subCatch : subClauses) {

View File

@ -1090,7 +1090,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
private boolean unrecoverableError() {
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 false;

View File

@ -30,6 +30,7 @@ import java.util.*;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.List;
import static com.sun.tools.javac.util.ListBuffer.lb;
@ -75,42 +76,6 @@ public class JavacParser implements Parser {
/** The name table. */
private Names names;
// Because of javac's limited lookahead, some contexts are ambiguous in
// the presence of type annotations even though they are not ambiguous
// in the absence of type annotations. Consider this code:
// void m(String [] m) { }
// void m(String ... m) { }
// After parsing "String", javac calls bracketsOpt which immediately
// returns if the next character is not '['. Similarly, javac can see
// if the next token is ... and in that case parse an ellipsis. But in
// the presence of type annotations:
// void m(String @A [] m) { }
// void m(String @A ... m) { }
// no finite lookahead is enough to determine whether to read array
// levels or an ellipsis. Furthermore, if you call bracketsOpt, then
// bracketsOpt first reads all the leading annotations and only then
// discovers that it needs to fail. bracketsOpt needs a way to push
// back the extra annotations that it read. (But, bracketsOpt should
// not *always* be allowed to push back extra annotations that it finds
// -- in most contexts, any such extra annotation is an error.
// Another similar case occurs with arrays and receiver annotations:
// String b() @Array [] @Receiver { }
// String b() @Receiver { }
//
// The following two variables permit type annotations that have
// already been read to be stored for later use. Alternate
// implementations are possible but would cause much larger changes to
// the parser.
/** Type annotations that have already been read but have not yet been used. **/
private List<JCTypeAnnotation> typeAnnotationsPushedBack = null;
/**
* If the parser notices extra annotations, then it either immediately
* issues an error (if this variable is false) or places the extra
* annotations in variable typeAnnotationsPushedBack (if this variable
* is true).
*/
private boolean permitTypeAnnotationsPushBack = false;
/** Construct a parser from a given scanner, tree factory and log.
*/
protected JavacParser(ParserFactory fac,
@ -134,19 +99,13 @@ public class JavacParser implements Parser {
this.allowTWR = source.allowTryWithResources();
this.allowDiamond = source.allowDiamond();
this.allowMulticatch = source.allowMulticatch();
this.allowTypeAnnotations = source.allowTypeAnnotations();
this.keepDocComments = keepDocComments;
if (keepDocComments)
docComments = new HashMap<JCTree,String>();
this.keepLineMap = keepLineMap;
this.errorTree = F.Erroneous();
this.debugJSR308 = fac.options.get("TA:parser") != null;
}
/** Switch: debug output for type-annotations operations
*/
boolean debugJSR308;
/** Switch: Should generics be recognized?
*/
boolean allowGenerics;
@ -183,10 +142,6 @@ public class JavacParser implements Parser {
*/
boolean allowAnnotations;
/** Switch: should we recognize type annotations?
*/
boolean allowTypeAnnotations;
/** Switch: should we recognize automatic resource management?
*/
boolean allowTWR;
@ -312,9 +267,9 @@ public class JavacParser implements Parser {
private void reportSyntaxError(int pos, String key, Object... args) {
if (pos > S.errPos() || pos == Position.NOPOS) {
if (S.token() == EOF)
log.error(pos, "premature.eof");
error(pos, "premature.eof");
else
log.error(pos, key, args);
error(pos, key, args);
}
S.errPos(pos);
if (S.pos() == errorPos)
@ -370,7 +325,7 @@ public class JavacParser implements Parser {
void checkNoMods(long mods) {
if (mods != 0) {
long lowestMod = mods & -mods;
log.error(S.pos(), "mod.not.allowed.here",
error(S.pos(), "mod.not.allowed.here",
Flags.asFlagSet(lowestMod));
}
}
@ -464,22 +419,22 @@ public class JavacParser implements Parser {
return name;
} else if (S.token() == ASSERT) {
if (allowAsserts) {
log.error(S.pos(), "assert.as.identifier");
error(S.pos(), "assert.as.identifier");
S.nextToken();
return names.error;
} else {
log.warning(S.pos(), "assert.as.identifier");
warning(S.pos(), "assert.as.identifier");
Name name = S.name();
S.nextToken();
return name;
}
} else if (S.token() == ENUM) {
if (allowEnums) {
log.error(S.pos(), "enum.as.identifier");
error(S.pos(), "enum.as.identifier");
S.nextToken();
return names.error;
} else {
log.warning(S.pos(), "enum.as.identifier");
warning(S.pos(), "enum.as.identifier");
Name name = S.name();
S.nextToken();
return name;
@ -525,7 +480,7 @@ public class JavacParser implements Parser {
TypeTags.INT,
Convert.string2int(strval(prefix), S.radix()));
} catch (NumberFormatException ex) {
log.error(S.pos(), "int.number.too.large", strval(prefix));
error(S.pos(), "int.number.too.large", strval(prefix));
}
break;
case LONGLITERAL:
@ -534,7 +489,7 @@ public class JavacParser implements Parser {
TypeTags.LONG,
new Long(Convert.string2long(strval(prefix), S.radix())));
} catch (NumberFormatException ex) {
log.error(S.pos(), "int.number.too.large", strval(prefix));
error(S.pos(), "int.number.too.large", strval(prefix));
}
break;
case FLOATLITERAL: {
@ -547,9 +502,9 @@ public class JavacParser implements Parser {
n = Float.NaN;
}
if (n.floatValue() == 0.0f && !isZero(proper))
log.error(S.pos(), "fp.number.too.small");
error(S.pos(), "fp.number.too.small");
else if (n.floatValue() == Float.POSITIVE_INFINITY)
log.error(S.pos(), "fp.number.too.large");
error(S.pos(), "fp.number.too.large");
else
t = F.at(pos).Literal(TypeTags.FLOAT, n);
break;
@ -564,9 +519,9 @@ public class JavacParser implements Parser {
n = Double.NaN;
}
if (n.doubleValue() == 0.0d && !isZero(proper))
log.error(S.pos(), "fp.number.too.small");
error(S.pos(), "fp.number.too.small");
else if (n.doubleValue() == Double.POSITIVE_INFINITY)
log.error(S.pos(), "fp.number.too.large");
error(S.pos(), "fp.number.too.large");
else
t = F.at(pos).Literal(TypeTags.DOUBLE, n);
break;
@ -620,33 +575,7 @@ public class JavacParser implements Parser {
return term(EXPR);
}
/**
* parses (optional) type annotations followed by a type. If the
* annotations are present before the type and are not consumed during array
* parsing, this method returns a {@link JCAnnotatedType} consisting of
* these annotations and the underlying type. Otherwise, it returns the
* underlying type.
*
* <p>
*
* Note that this method sets {@code mode} to {@code TYPE} first, before
* parsing annotations.
*/
public JCExpression parseType() {
List<JCTypeAnnotation> annotations = typeAnnotationsOpt();
return parseType(annotations);
}
public JCExpression parseType(List<JCTypeAnnotation> annotations) {
JCExpression result = unannotatedType();
if (!annotations.isEmpty())
result = F.AnnotatedType(annotations, result);
return result;
}
public JCExpression unannotatedType() {
return term(TYPE);
}
@ -895,8 +824,8 @@ public class JavacParser implements Parser {
* | [TypeArguments] THIS [Arguments]
* | [TypeArguments] SUPER SuperSuffix
* | NEW [TypeArguments] Creator
* | [Annotations] Ident { "." Ident }
* [ [Annotations] "[" ( "]" BracketsOpt "." CLASS | Expression "]" )
* | Ident { "." Ident }
* [ "[" ( "]" BracketsOpt "." CLASS | Expression "]" )
* | Arguments
* | "." ( CLASS | THIS | [TypeArguments] SUPER Arguments | NEW [TypeArguments] InnerCreator )
* ]
@ -1047,62 +976,23 @@ public class JavacParser implements Parser {
typeArgs = null;
} else return illegal();
break;
case MONKEYS_AT:
// only annotated targetting class literals or cast types are valid
List<JCTypeAnnotation> typeAnnos = typeAnnotationsOpt();
if (typeAnnos.isEmpty()) {
// else there would be no '@'
throw new AssertionError("type annos is empty");
}
JCExpression expr = term3();
// Type annotations: If term3 just parsed a non-type, expect a
// class literal (and issue a syntax error if there is no class
// literal). Otherwise, create a JCAnnotatedType.
if ((mode & TYPE) == 0) {
if (expr.getTag() != JCTree.SELECT)
return illegal(typeAnnos.head.pos);
JCFieldAccess sel = (JCFieldAccess)expr;
if (sel.name != names._class)
return illegal();
else {
sel.selected = F.AnnotatedType(typeAnnos, sel.selected);
t = expr;
}
} else {
// type annotation targeting a cast
t = toP(F.at(S.pos()).AnnotatedType(typeAnnos, expr));
}
break;
case IDENTIFIER: case ASSERT: case ENUM:
if (typeArgs != null) return illegal();
t = toP(F.at(S.pos()).Ident(ident()));
loop: while (true) {
pos = S.pos();
final List<JCTypeAnnotation> annos = typeAnnotationsOpt();
// need to report an error later if LBRACKET is for array
// index access rather than array creation level
if (!annos.isEmpty() && S.token() != LBRACKET && S.token() != ELLIPSIS)
return illegal(annos.head.pos);
switch (S.token()) {
case LBRACKET:
S.nextToken();
if (S.token() == RBRACKET) {
S.nextToken();
t = bracketsOpt(t, annos);
t = bracketsOpt(t);
t = toP(F.at(pos).TypeArray(t));
t = bracketsSuffix(t);
} else {
if ((mode & EXPR) != 0) {
mode = EXPR;
JCExpression t1 = term();
if (!annos.isEmpty()) t = illegal(annos.head.pos);
t = to(F.at(pos).Indexed(t, t1));
}
accept(RBRACKET);
@ -1155,14 +1045,6 @@ public class JavacParser implements Parser {
// typeArgs saved for next loop iteration.
t = toP(F.at(pos).Select(t, ident()));
break;
case ELLIPSIS:
if (this.permitTypeAnnotationsPushBack) {
this.typeAnnotationsPushedBack = annos;
} else if (annos.nonEmpty()) {
// Don't return here -- error recovery attempt
illegal(annos.head.pos);
}
break loop;
default:
break loop;
}
@ -1201,18 +1083,14 @@ public class JavacParser implements Parser {
if (typeArgs != null) illegal();
while (true) {
int pos1 = S.pos();
final List<JCTypeAnnotation> annos = typeAnnotationsOpt();
if (S.token() == LBRACKET) {
S.nextToken();
if ((mode & TYPE) != 0) {
int oldmode = mode;
mode = TYPE;
if (S.token() == RBRACKET) {
S.nextToken();
t = bracketsOpt(t, annos);
t = bracketsOpt(t);
t = toP(F.at(pos1).TypeArray(t));
return t;
}
@ -1247,12 +1125,6 @@ public class JavacParser implements Parser {
typeArgs = null;
}
} else {
if (!annos.isEmpty()) {
if (permitTypeAnnotationsPushBack)
typeAnnotationsPushedBack = annos;
else
return illegal(annos.head.pos);
}
break;
}
}
@ -1262,7 +1134,6 @@ public class JavacParser implements Parser {
S.token() == PLUSPLUS ? JCTree.POSTINC : JCTree.POSTDEC, t));
S.nextToken();
}
return toP(t);
}
@ -1400,26 +1271,24 @@ public class JavacParser implements Parser {
}
/** TypeArgument = Type
* | [Annotations] "?"
* | [Annotations] "?" EXTENDS Type {"&" Type}
* | [Annotations] "?" SUPER Type
* | "?"
* | "?" EXTENDS Type {"&" Type}
* | "?" SUPER Type
*/
JCExpression typeArgument() {
List<JCTypeAnnotation> annotations = typeAnnotationsOpt();
if (S.token() != QUES) return parseType(annotations);
if (S.token() != QUES) return parseType();
int pos = S.pos();
S.nextToken();
JCExpression result;
if (S.token() == EXTENDS) {
TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.EXTENDS));
S.nextToken();
JCExpression bound = parseType();
result = F.at(pos).Wildcard(t, bound);
return F.at(pos).Wildcard(t, bound);
} else if (S.token() == SUPER) {
TypeBoundKind t = to(F.at(pos).TypeBoundKind(BoundKind.SUPER));
S.nextToken();
JCExpression bound = parseType();
result = F.at(pos).Wildcard(t, bound);
return F.at(pos).Wildcard(t, bound);
} else if (S.token() == IDENTIFIER) {
//error recovery
reportSyntaxError(S.prevEndPos(), "expected3",
@ -1427,14 +1296,11 @@ public class JavacParser implements Parser {
TypeBoundKind t = F.at(Position.NOPOS).TypeBoundKind(BoundKind.UNBOUND);
JCExpression wc = toP(F.at(pos).Wildcard(t, null));
JCIdent id = toP(F.at(S.pos()).Ident(ident()));
result = F.at(pos).Erroneous(List.<JCTree>of(wc, id));
return F.at(pos).Erroneous(List.<JCTree>of(wc, id));
} else {
TypeBoundKind t = toP(F.at(pos).TypeBoundKind(BoundKind.UNBOUND));
result = toP(F.at(pos).Wildcard(t, null));
return toP(F.at(pos).Wildcard(t, null));
}
if (!annotations.isEmpty())
result = toP(F.at(annotations.head.pos).AnnotatedType(annotations,result));
return result;
}
JCTypeApply typeArguments(JCExpression t) {
@ -1443,47 +1309,21 @@ public class JavacParser implements Parser {
return toP(F.at(pos).TypeApply(t, args));
}
/**
* BracketsOpt = { [Annotations] "[" "]" }
*
* <p>
*
* <code>annotations</code> is the list of annotations targeting
* the expression <code>t</code>.
/** BracketsOpt = {"[" "]"}
*/
private JCExpression bracketsOpt(JCExpression t,
List<JCTypeAnnotation> annotations) {
List<JCTypeAnnotation> nextLevelAnnotations = typeAnnotationsOpt();
private JCExpression bracketsOpt(JCExpression t) {
if (S.token() == LBRACKET) {
int pos = S.pos();
S.nextToken();
JCExpression orig = t;
t = bracketsOptCont(t, pos, nextLevelAnnotations);
} else if (!nextLevelAnnotations.isEmpty()) {
if (permitTypeAnnotationsPushBack) {
this.typeAnnotationsPushedBack = nextLevelAnnotations;
} else
return illegal(nextLevelAnnotations.head.pos);
t = bracketsOptCont(t, pos);
F.at(pos);
}
int apos = S.pos();
if (!annotations.isEmpty())
t = F.at(apos).AnnotatedType(annotations, t);
return t;
}
/** BracketsOpt = {"[" TypeAnnotations "]"}
*/
private JCExpression bracketsOpt(JCExpression t) {
return bracketsOpt(t, List.<JCTypeAnnotation>nil());
}
private JCArrayTypeTree bracketsOptCont(JCExpression t, int pos,
List<JCTypeAnnotation> annotations) {
private JCArrayTypeTree bracketsOptCont(JCExpression t, int pos) {
accept(RBRACKET);
t = bracketsOpt(t, annotations);
t = bracketsOpt(t);
return toP(F.at(pos).TypeArray(t));
}
@ -1517,29 +1357,18 @@ public class JavacParser implements Parser {
return t;
}
/** Creator = [Annotations] Qualident [TypeArguments] ( ArrayCreatorRest | ClassCreatorRest )
/** Creator = Qualident [TypeArguments] ( ArrayCreatorRest | ClassCreatorRest )
*/
JCExpression creator(int newpos, List<JCExpression> typeArgs) {
List<JCTypeAnnotation> newAnnotations = typeAnnotationsOpt();
switch (S.token()) {
case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
case DOUBLE: case BOOLEAN:
if (typeArgs == null) {
if (newAnnotations.isEmpty())
return arrayCreatorRest(newpos, basicType());
else
return arrayCreatorRest(newpos, F.AnnotatedType(newAnnotations, basicType()));
}
if (typeArgs == null)
return arrayCreatorRest(newpos, basicType());
break;
default:
}
JCExpression t = qualident();
// handle type annotations for non primitive arrays
if (!newAnnotations.isEmpty())
t = F.AnnotatedType(newAnnotations, t);
int oldmode = mode;
mode = TYPE | DIAMOND;
if (S.token() == LT) {
@ -1556,7 +1385,7 @@ public class JavacParser implements Parser {
}
}
mode = oldmode;
if (S.token() == LBRACKET || S.token() == MONKEYS_AT) {
if (S.token() == LBRACKET) {
JCExpression e = arrayCreatorRest(newpos, t);
if (typeArgs != null) {
int pos = newpos;
@ -1572,15 +1401,7 @@ public class JavacParser implements Parser {
}
return e;
} else if (S.token() == LPAREN) {
JCNewClass newClass = classCreatorRest(newpos, null, typeArgs, t);
if (newClass.def != null) {
assert newClass.def.mods.annotations.isEmpty();
if (newAnnotations.nonEmpty()) {
newClass.def.mods.pos = earlier(newClass.def.mods.pos, newAnnotations.head.pos);
newClass.def.mods.annotations = List.convert(JCAnnotation.class, newAnnotations);
}
}
return newClass;
return classCreatorRest(newpos, null, typeArgs, t);
} else {
reportSyntaxError(S.pos(), "expected2",
LPAREN, LBRACKET);
@ -1603,67 +1424,34 @@ public class JavacParser implements Parser {
return classCreatorRest(newpos, encl, typeArgs, t);
}
/** ArrayCreatorRest = [Annotations] "[" ( "]" BracketsOpt ArrayInitializer
* | Expression "]" {[Annotations] "[" Expression "]"} BracketsOpt )
/** ArrayCreatorRest = "[" ( "]" BracketsOpt ArrayInitializer
* | Expression "]" {"[" Expression "]"} BracketsOpt )
*/
JCExpression arrayCreatorRest(int newpos, JCExpression elemtype) {
List<JCTypeAnnotation> topAnnos = List.nil();
if (elemtype.getTag() == JCTree.ANNOTATED_TYPE) {
JCAnnotatedType atype = (JCAnnotatedType) elemtype;
topAnnos = atype.annotations;
elemtype = atype.underlyingType;
}
List<JCTypeAnnotation> annos = typeAnnotationsOpt();
accept(LBRACKET);
if (S.token() == RBRACKET) {
accept(RBRACKET);
elemtype = bracketsOpt(elemtype, annos);
elemtype = bracketsOpt(elemtype);
if (S.token() == LBRACE) {
JCNewArray na = (JCNewArray)arrayInitializer(newpos, elemtype);
na.annotations = topAnnos;
return na;
return arrayInitializer(newpos, elemtype);
} else {
return syntaxError(S.pos(), "array.dimension.missing");
}
} else {
ListBuffer<JCExpression> dims = new ListBuffer<JCExpression>();
// maintain array dimension type annotations
ListBuffer<List<JCTypeAnnotation>> dimAnnotations = ListBuffer.lb();
dimAnnotations.append(annos);
dims.append(parseExpression());
accept(RBRACKET);
while (S.token() == LBRACKET
|| (S.token() == MONKEYS_AT)) {
List<JCTypeAnnotation> maybeDimAnnos = typeAnnotationsOpt();
while (S.token() == LBRACKET) {
int pos = S.pos();
S.nextToken();
if (S.token() == RBRACKET) {
elemtype = bracketsOptCont(elemtype, pos, maybeDimAnnos);
elemtype = bracketsOptCont(elemtype, pos);
} else {
if (S.token() == RBRACKET) { // no dimension
elemtype = bracketsOptCont(elemtype, pos, maybeDimAnnos);
} else {
dimAnnotations.append(maybeDimAnnos);
dims.append(parseExpression());
accept(RBRACKET);
}
dims.append(parseExpression());
accept(RBRACKET);
}
}
JCNewArray na = toP(F.at(newpos).NewArray(elemtype, dims.toList(), null));
na.annotations = topAnnos;
na.dimAnnotations = dimAnnotations.toList();
return na;
return toP(F.at(newpos).NewArray(elemtype, dims.toList(), null));
}
}
@ -1794,7 +1582,7 @@ public class JavacParser implements Parser {
case ENUM:
case ASSERT:
if (allowEnums && S.token() == ENUM) {
log.error(S.pos(), "local.enum");
error(S.pos(), "local.enum");
stats.
append(classOrInterfaceOrEnumDeclaration(modifiersOpt(),
S.docComment()));
@ -1941,9 +1729,9 @@ public class JavacParser implements Parser {
} else {
if (allowTWR) {
if (resources.isEmpty())
log.error(pos, "try.without.catch.finally.or.resource.decls");
error(pos, "try.without.catch.finally.or.resource.decls");
} else
log.error(pos, "try.without.catch.or.finally");
error(pos, "try.without.catch.or.finally");
}
return F.at(pos).Try(resources, body, catchers.toList(), finalizer);
}
@ -2040,7 +1828,7 @@ public class JavacParser implements Parser {
JCModifiers mods = optFinal(Flags.PARAMETER);
List<JCExpression> catchTypes = catchTypes();
JCExpression paramType = catchTypes.size() > 1 ?
toP(F.at(catchTypes.head.getStartPosition()).TypeDisjoint(catchTypes)) :
toP(F.at(catchTypes.head.getStartPosition()).TypeDisjunction(catchTypes)) :
catchTypes.head;
JCVariableDecl formal = variableDeclaratorId(mods, paramType);
accept(RPAREN);
@ -2142,32 +1930,17 @@ public class JavacParser implements Parser {
new ListBuffer<JCExpressionStatement>()).toList();
}
enum AnnotationKind { DEFAULT_ANNO, TYPE_ANNO };
/** AnnotationsOpt = { '@' Annotation }
*/
List<JCAnnotation> annotationsOpt(AnnotationKind kind) {
List<JCAnnotation> annotationsOpt() {
if (S.token() != MONKEYS_AT) return List.nil(); // optimization
ListBuffer<JCAnnotation> buf = new ListBuffer<JCAnnotation>();
int prevmode = mode;
while (S.token() == MONKEYS_AT) {
int pos = S.pos();
S.nextToken();
buf.append(annotation(pos, kind));
buf.append(annotation(pos));
}
lastmode = mode;
mode = prevmode;
List<JCAnnotation> annotations = buf.toList();
if (debugJSR308 && kind == AnnotationKind.TYPE_ANNO)
System.out.println("TA: parsing " + annotations
+ " in " + log.currentSourceFile());
return annotations;
}
List<JCTypeAnnotation> typeAnnotationsOpt() {
List<JCAnnotation> annotations = annotationsOpt(AnnotationKind.TYPE_ANNO);
return List.convert(JCTypeAnnotation.class, annotations);
return buf.toList();
}
/** ModifiersOpt = { Modifier }
@ -2213,13 +1986,13 @@ public class JavacParser implements Parser {
case MONKEYS_AT : flag = Flags.ANNOTATION; break;
default: break loop;
}
if ((flags & flag) != 0) log.error(S.pos(), "repeated.modifier");
if ((flags & flag) != 0) error(S.pos(), "repeated.modifier");
lastPos = S.pos();
S.nextToken();
if (flag == Flags.ANNOTATION) {
checkAnnotations();
if (S.token() != INTERFACE) {
JCAnnotation ann = annotation(lastPos, AnnotationKind.DEFAULT_ANNO);
JCAnnotation ann = annotation(lastPos);
// if first modifier is an annotation, set pos to annotation's.
if (flags == 0 && annotations.isEmpty())
pos = ann.pos;
@ -2250,18 +2023,12 @@ public class JavacParser implements Parser {
/** Annotation = "@" Qualident [ "(" AnnotationFieldValues ")" ]
* @param pos position of "@" token
*/
JCAnnotation annotation(int pos, AnnotationKind kind) {
JCAnnotation annotation(int pos) {
// accept(AT); // AT consumed by caller
checkAnnotations();
if (kind == AnnotationKind.TYPE_ANNO)
checkTypeAnnotations();
JCTree ident = qualident();
List<JCExpression> fieldValues = annotationFieldValuesOpt();
JCAnnotation ann;
if (kind == AnnotationKind.DEFAULT_ANNO)
ann = F.at(pos).Annotation(ident, fieldValues);
else
ann = F.at(pos).TypeAnnotation(ident, fieldValues);
JCAnnotation ann = F.at(pos).Annotation(ident, fieldValues);
storeEnd(ann, S.prevEndPos());
return ann;
}
@ -2314,7 +2081,7 @@ public class JavacParser implements Parser {
case MONKEYS_AT:
pos = S.pos();
S.nextToken();
return annotation(pos, AnnotationKind.DEFAULT_ANNO);
return annotation(pos);
case LBRACE:
pos = S.pos();
accept(LBRACE);
@ -2565,7 +2332,7 @@ public class JavacParser implements Parser {
}
} else {
if (S.token() == ENUM) {
log.error(S.pos(), "enums.not.supported.in.source", source.name);
error(S.pos(), "enums.not.supported.in.source", source.name);
allowEnums = true;
return enumDeclaration(mods, dc);
}
@ -2705,7 +2472,7 @@ public class JavacParser implements Parser {
S.resetDeprecatedFlag();
}
int pos = S.pos();
List<JCAnnotation> annotations = annotationsOpt(AnnotationKind.DEFAULT_ANNO);
List<JCAnnotation> annotations = annotationsOpt();
JCModifiers mods = F.at(annotations.isEmpty() ? Position.NOPOS : pos).Modifiers(flags, annotations);
List<JCExpression> typeArgs = typeArgumentsOpt();
int identPos = S.pos();
@ -2802,29 +2569,19 @@ public class JavacParser implements Parser {
} else {
pos = S.pos();
List<JCTypeParameter> typarams = typeParametersOpt();
List<JCAnnotation> annosAfterParams = annotationsOpt(AnnotationKind.DEFAULT_ANNO);
Name name = S.name();
pos = S.pos();
JCExpression type;
boolean isVoid = S.token() == VOID;
if (isVoid) {
if (annosAfterParams.nonEmpty())
illegal(annosAfterParams.head.pos);
type = to(F.at(pos).TypeIdent(TypeTags.VOID));
S.nextToken();
} else {
if (annosAfterParams.nonEmpty()) {
mods.annotations = mods.annotations.appendList(annosAfterParams);
if (mods.pos == Position.NOPOS)
mods.pos = mods.annotations.head.pos;
}
// method returns types are un-annotated types
type = unannotatedType();
type = parseType();
}
if (S.token() == LPAREN && !isInterface && type.getTag() == JCTree.IDENT) {
if (isInterface || name != className)
log.error(pos, "invalid.meth.decl.ret.type.req");
error(pos, "invalid.meth.decl.ret.type.req");
return List.of(methodDeclaratorRest(
pos, mods, null, names.init, typarams,
isInterface, true, dc));
@ -2856,15 +2613,15 @@ public class JavacParser implements Parser {
}
/** MethodDeclaratorRest =
* FormalParameters BracketsOpt [Annotations] [Throws TypeList] ( MethodBody | [DEFAULT AnnotationValue] ";")
* FormalParameters BracketsOpt [Throws TypeList] ( MethodBody | [DEFAULT AnnotationValue] ";")
* VoidMethodDeclaratorRest =
* FormalParameters [Annotations] [Throws TypeList] ( MethodBody | ";")
* FormalParameters [Throws TypeList] ( MethodBody | ";")
* InterfaceMethodDeclaratorRest =
* FormalParameters BracketsOpt [Annotations] [THROWS TypeList] ";"
* FormalParameters BracketsOpt [THROWS TypeList] ";"
* VoidInterfaceMethodDeclaratorRest =
* FormalParameters [Annotations] [THROWS TypeList] ";"
* FormalParameters [THROWS TypeList] ";"
* ConstructorDeclaratorRest =
* "(" FormalParameterListOpt ")" [Annotations] [THROWS TypeList] MethodBody
* "(" FormalParameterListOpt ")" [THROWS TypeList] MethodBody
*/
JCTree methodDeclaratorRest(int pos,
JCModifiers mods,
@ -2874,22 +2631,7 @@ public class JavacParser implements Parser {
boolean isInterface, boolean isVoid,
String dc) {
List<JCVariableDecl> params = formalParameters();
List<JCTypeAnnotation> receiverAnnotations;
if (!isVoid) {
// need to distinguish between receiver anno and array anno
// look at typeAnnotationsPushedBack comment
this.permitTypeAnnotationsPushBack = true;
type = methodReturnArrayRest(type);
this.permitTypeAnnotationsPushBack = false;
if (typeAnnotationsPushedBack == null)
receiverAnnotations = List.nil();
else
receiverAnnotations = typeAnnotationsPushedBack;
typeAnnotationsPushedBack = null;
} else
receiverAnnotations = typeAnnotationsOpt();
if (!isVoid) type = bracketsOpt(type);
List<JCExpression> thrown = List.nil();
if (S.token() == THROWS) {
S.nextToken();
@ -2919,51 +2661,20 @@ public class JavacParser implements Parser {
JCMethodDecl result =
toP(F.at(pos).MethodDef(mods, name, type, typarams,
params, receiverAnnotations, thrown,
params, thrown,
body, defaultValue));
attach(result, dc);
return result;
}
/** Parses the array levels after the format parameters list, and append
* them to the return type, while preseving the order of type annotations
*/
private JCExpression methodReturnArrayRest(JCExpression type) {
if (type.getTag() != JCTree.TYPEARRAY)
return bracketsOpt(type);
JCArrayTypeTree baseArray = (JCArrayTypeTree)type;
while (TreeInfo.typeIn(baseArray.elemtype) instanceof JCArrayTypeTree)
baseArray = (JCArrayTypeTree)TreeInfo.typeIn(baseArray.elemtype);
if (baseArray.elemtype.getTag() == JCTree.ANNOTATED_TYPE) {
JCAnnotatedType at = (JCAnnotatedType)baseArray.elemtype;
at.underlyingType = bracketsOpt(at.underlyingType);
} else {
baseArray.elemtype = bracketsOpt(baseArray.elemtype);
}
return type;
}
/** QualidentList = [Annotations] Qualident {"," [Annotations] Qualident}
/** QualidentList = Qualident {"," Qualident}
*/
List<JCExpression> qualidentList() {
ListBuffer<JCExpression> ts = new ListBuffer<JCExpression>();
List<JCTypeAnnotation> typeAnnos = typeAnnotationsOpt();
if (!typeAnnos.isEmpty())
ts.append(F.AnnotatedType(typeAnnos, qualident()));
else
ts.append(qualident());
ts.append(qualident());
while (S.token() == COMMA) {
S.nextToken();
typeAnnos = typeAnnotationsOpt();
if (!typeAnnos.isEmpty())
ts.append(F.AnnotatedType(typeAnnos, qualident()));
else
ts.append(qualident());
ts.append(qualident());
}
return ts.toList();
}
@ -2987,13 +2698,12 @@ public class JavacParser implements Parser {
}
}
/** TypeParameter = [Annotations] TypeVariable [TypeParameterBound]
/** TypeParameter = TypeVariable [TypeParameterBound]
* TypeParameterBound = EXTENDS Type {"&" Type}
* TypeVariable = Ident
*/
JCTypeParameter typeParameter() {
int pos = S.pos();
List<JCTypeAnnotation> annos = typeAnnotationsOpt();
Name name = ident();
ListBuffer<JCExpression> bounds = new ListBuffer<JCExpression>();
if (S.token() == EXTENDS) {
@ -3004,7 +2714,7 @@ public class JavacParser implements Parser {
bounds.append(parseType());
}
}
return toP(F.at(pos).TypeParameter(name, bounds.toList(), annos));
return toP(F.at(pos).TypeParameter(name, bounds.toList()));
}
/** FormalParameters = "(" [ FormalParameterList ] ")"
@ -3038,37 +2748,26 @@ public class JavacParser implements Parser {
*/
JCVariableDecl formalParameter() {
JCModifiers mods = optFinal(Flags.PARAMETER);
// need to distinguish between vararg annos and array annos
// look at typeAnnotaitonsPushedBack comment
this.permitTypeAnnotationsPushBack = true;
JCExpression type = parseType();
this.permitTypeAnnotationsPushBack = false;
if (S.token() == ELLIPSIS) {
List<JCTypeAnnotation> varargsAnnos = typeAnnotationsPushedBack;
typeAnnotationsPushedBack = null;
checkVarargs();
mods.flags |= Flags.VARARGS;
// insert var arg type annotations
if (varargsAnnos != null && varargsAnnos.nonEmpty())
type = F.at(S.pos()).AnnotatedType(varargsAnnos, type);
type = to(F.at(S.pos()).TypeArray(type));
S.nextToken();
} else {
// if not a var arg, then typeAnnotationsPushedBack should be null
if (typeAnnotationsPushedBack != null
&& !typeAnnotationsPushedBack.isEmpty()) {
reportSyntaxError(typeAnnotationsPushedBack.head.pos,
"illegal.start.of.type");
}
typeAnnotationsPushedBack = null;
}
return variableDeclaratorId(mods, type);
}
/* ---------- auxiliary methods -------------- */
void error(int pos, String key, Object ... args) {
log.error(DiagnosticFlag.SYNTAX, pos, key, args);
}
void warning(int pos, String key, Object ... args) {
log.warning(pos, key, args);
}
/** Check that given tree is a legal expression statement.
*/
protected JCExpression checkExprStat(JCExpression t) {
@ -3084,7 +2783,7 @@ public class JavacParser implements Parser {
case JCTree.ERRONEOUS:
return t;
default:
log.error(t.pos, "not.stmt");
error(t.pos, "not.stmt");
return F.at(t.pos).Erroneous(List.<JCTree>of(t));
}
}
@ -3231,55 +2930,49 @@ public class JavacParser implements Parser {
void checkGenerics() {
if (!allowGenerics) {
log.error(S.pos(), "generics.not.supported.in.source", source.name);
error(S.pos(), "generics.not.supported.in.source", source.name);
allowGenerics = true;
}
}
void checkVarargs() {
if (!allowVarargs) {
log.error(S.pos(), "varargs.not.supported.in.source", source.name);
error(S.pos(), "varargs.not.supported.in.source", source.name);
allowVarargs = true;
}
}
void checkForeach() {
if (!allowForeach) {
log.error(S.pos(), "foreach.not.supported.in.source", source.name);
error(S.pos(), "foreach.not.supported.in.source", source.name);
allowForeach = true;
}
}
void checkStaticImports() {
if (!allowStaticImport) {
log.error(S.pos(), "static.import.not.supported.in.source", source.name);
error(S.pos(), "static.import.not.supported.in.source", source.name);
allowStaticImport = true;
}
}
void checkAnnotations() {
if (!allowAnnotations) {
log.error(S.pos(), "annotations.not.supported.in.source", source.name);
error(S.pos(), "annotations.not.supported.in.source", source.name);
allowAnnotations = true;
}
}
void checkTypeAnnotations() {
if (!allowTypeAnnotations) {
log.error(S.pos(), "type.annotations.not.supported.in.source", source.name);
allowTypeAnnotations = true;
}
}
void checkDiamond() {
if (!allowDiamond) {
log.error(S.pos(), "diamond.not.supported.in.source", source.name);
error(S.pos(), "diamond.not.supported.in.source", source.name);
allowDiamond = true;
}
}
void checkMulticatch() {
if (!allowMulticatch) {
log.error(S.pos(), "multicatch.not.supported.in.source", source.name);
error(S.pos(), "multicatch.not.supported.in.source", source.name);
allowMulticatch = true;
}
}
void checkAutomaticResourceManagement() {
if (!allowTWR) {
log.error(S.pos(), "automatic.resource.management.not.supported.in.source", source.name);
error(S.pos(), "automatic.resource.management.not.supported.in.source", source.name);
allowTWR = true;
}
}

View File

@ -49,11 +49,11 @@ import javax.tools.StandardJavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.DiagnosticListener;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.source.util.AbstractTypeProcessor;
//308 import com.sun.source.util.AbstractTypeProcessor;
import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener;
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.Symbol.*;
import com.sun.tools.javac.file.JavacFileManager;
@ -712,7 +712,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
}
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);
ps.contributed = true;
ps.removeSupportedOptions(unmatchedProcessorOptions);
@ -939,7 +939,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
break;
case ERROR:
if (fatalErrors || !d.isFlagSet(RESOLVE_ERROR))
if (fatalErrors || !d.isFlagSet(RECOVERABLE))
return true;
break;
}

View File

@ -873,6 +873,13 @@ compiler.warn.raw.class.use=\
found raw type: {0}\n\
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
@ -1299,9 +1306,9 @@ compiler.err.annotations.not.supported.in.source=\
annotations are not supported in -source {0}\n\
(use -source 5 or higher to enable annotations)
compiler.err.type.annotations.not.supported.in.source=\
type annotations are not supported in -source {0}\n\
(use -source 7 or higher to enable type annotations)
#308 compiler.err.type.annotations.not.supported.in.source=\
#308 type annotations are not supported in -source {0}\n\
#308 (use -source 7 or higher to enable type annotations)
compiler.err.foreach.not.supported.in.source=\
for-each loops are not supported in -source {0}\n\

View File

@ -236,13 +236,13 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
*/
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.
*/
public static final int TYPEPARAMETER = TYPEDISJOINT + 1;
public static final int TYPEPARAMETER = TYPEDISJUNCTION + 1;
/** Type argument.
*/
@ -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) {
this.components = components;
protected JCTypeDisjunction(List<JCExpression> components) {
this.alternatives = components;
}
@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() {
return components;
public List<JCExpression> getTypeAlternatives() {
return alternatives;
}
@Override
public <R,D> R accept(TreeVisitor<R,D> v, D d) {
return v.visitDisjointType(this, d);
return v.visitDisjunctiveType(this, d);
}
@Override
public int getTag() {
return TYPEDISJOINT;
return TYPEDISJUNCTION;
}
}
@ -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 JCExpression underlyingType;
protected JCAnnotatedType(List<JCTypeAnnotation> annotations, JCExpression underlyingType) {
this.annotations = annotations;
this.underlyingType = underlyingType;
throw new UnsupportedOperationException();
//308 this.annotations = annotations;
//308 this.underlyingType = underlyingType;
}
@Override
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() {
return annotations;
}
@ -2086,7 +2092,8 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
}
@Override
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
public int getTag() {
@ -2277,7 +2284,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
public void visitTypeIdent(JCPrimitiveTypeTree that) { visitTree(that); }
public void visitTypeArray(JCArrayTypeTree 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 visitWildcard(JCWildcard that) { visitTree(that); }
public void visitTypeBoundKind(TypeBoundKind that) { visitTree(that); }

View File

@ -1195,9 +1195,9 @@ public class Pretty extends JCTree.Visitor {
}
}
public void visitTypeDisjoint(JCTypeDisjoint tree) {
public void visitTypeDisjunction(JCTypeDisjunction tree) {
try {
printExprs(tree.components, " | ");
printExprs(tree.alternatives, " | ");
} catch (IOException e) {
throw new UncheckedIOException(e);
}

View File

@ -71,12 +71,12 @@ public class TreeCopier<P> implements TreeVisitor<JCTree,P> {
return lb.toList();
}
public JCTree visitAnnotatedType(AnnotatedTypeTree node, P p) {
JCAnnotatedType t = (JCAnnotatedType) node;
List<JCTypeAnnotation> annotations = copy(t.annotations, p);
JCExpression underlyingType = copy(t.underlyingType, p);
return M.at(t.pos).AnnotatedType(annotations, underlyingType);
}
//308 public JCTree visitAnnotatedType(AnnotatedTypeTree node, P p) {
//308 JCAnnotatedType t = (JCAnnotatedType) node;
//308 List<JCTypeAnnotation> annotations = copy(t.annotations, p);
//308 JCExpression underlyingType = copy(t.underlyingType, p);
//308 return M.at(t.pos).AnnotatedType(annotations, underlyingType);
//308 }
public JCTree visitAnnotation(AnnotationTree node, P p) {
JCAnnotation t = (JCAnnotation) node;
@ -346,10 +346,10 @@ public class TreeCopier<P> implements TreeVisitor<JCTree,P> {
return M.at(t.pos).TypeApply(clazz, arguments);
}
public JCTree visitDisjointType(DisjointTypeTree node, P p) {
JCTypeDisjoint t = (JCTypeDisjoint) node;
List<JCExpression> components = copy(t.components, p);
return M.at(t.pos).TypeDisjoint(components);
public JCTree visitDisjunctiveType(DisjunctiveTypeTree node, P p) {
JCTypeDisjunction t = (JCTypeDisjunction) node;
List<JCExpression> components = copy(t.alternatives, p);
return M.at(t.pos).TypeDisjunction(components);
}
public JCTree visitArrayType(ArrayTypeTree node, P p) {

View File

@ -119,7 +119,7 @@ public class TreeInfo {
}
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?

View File

@ -451,8 +451,8 @@ public class TreeMaker implements JCTree.Factory {
return tree;
}
public JCTypeDisjoint TypeDisjoint(List<JCExpression> components) {
JCTypeDisjoint tree = new JCTypeDisjoint(components);
public JCTypeDisjunction TypeDisjunction(List<JCExpression> components) {
JCTypeDisjunction tree = new JCTypeDisjunction(components);
tree.pos = pos;
return tree;
}

View File

@ -276,8 +276,8 @@ public class TreeScanner extends Visitor {
scan(tree.arguments);
}
public void visitTypeDisjoint(JCTypeDisjoint tree) {
scan(tree.components);
public void visitTypeDisjunction(JCTypeDisjunction tree) {
scan(tree.alternatives);
}
public void visitTypeParameter(JCTypeParameter tree) {

View File

@ -368,8 +368,8 @@ public class TreeTranslator extends JCTree.Visitor {
result = tree;
}
public void visitTypeDisjoint(JCTypeDisjoint tree) {
tree.components = translate(tree.components);
public void visitTypeDisjunction(JCTypeDisjunction tree) {
tree.alternatives = translate(tree.alternatives);
result = tree;
}

View File

@ -30,6 +30,7 @@ import java.util.Map;
import javax.tools.JavaFileObject;
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.SimpleDiagnosticPosition;
@ -103,6 +104,19 @@ public abstract class AbstractLog {
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
* maximum number of warnings has been reached.
* @param pos The source position at which to report the warning.

View File

@ -63,17 +63,23 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
DiagnosticFormatter<JCDiagnostic> formatter;
final String prefix;
final Set<DiagnosticFlag> defaultErrorFlags;
/** Create a new diagnostic factory. */
protected Factory(Context context) {
this(JavacMessages.instance(context), "compiler");
context.put(diagnosticFactoryKey, this);
Options options = Options.instance(context);
if (options.isSet("onlySyntaxErrorsUnrecoverable"))
defaultErrorFlags.add(DiagnosticFlag.RECOVERABLE);
}
/** Create a new diagnostic factory. */
public Factory(JavacMessages messages, String prefix) {
this.prefix = prefix;
this.formatter = new BasicDiagnosticFormatter(messages);
defaultErrorFlags = EnumSet.of(DiagnosticFlag.MANDATORY);
}
/**
@ -85,7 +91,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic error(
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> {
public enum DiagnosticFlag {
MANDATORY,
RESOLVE_ERROR
RESOLVE_ERROR,
SYNTAX,
RECOVERABLE
}
private final DiagnosticType type;
@ -547,6 +555,17 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
public void setFlag(DiagnosticFlag 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) {

View File

@ -850,6 +850,12 @@ public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc {
String[] paramTypes, Set<ClassDocImpl> searched) {
//### 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;
MethodDocImpl mdi;
@ -876,7 +882,6 @@ public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc {
*---------------------------------*/
// search current class
Names names = tsym.name.table.names;
Scope.Entry e = tsym.members().lookup(names.fromString(methodName));
//### Using modifier filter here isn't really correct,

View File

@ -637,6 +637,7 @@ public class DocEnv {
* Should be called only on symbols representing methods.
*/
public MethodDocImpl getMethodDoc(MethodSymbol meth) {
assert !meth.isConstructor() : "not expecting a constructor symbol";
MethodDocImpl result = (MethodDocImpl)methodMap.get(meth);
if (result != null) return result;
result = new MethodDocImpl(this, meth);
@ -665,6 +666,7 @@ public class DocEnv {
* Should be called only on symbols representing constructors.
*/
public ConstructorDocImpl getConstructorDoc(MethodSymbol meth) {
assert meth.isConstructor() : "expecting a constructor symbol";
ConstructorDocImpl result = (ConstructorDocImpl)methodMap.get(meth);
if (result != null) return result;
result = new ConstructorDocImpl(this, meth);

View File

@ -26,6 +26,7 @@
package com.sun.tools.javah;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
@ -74,6 +75,7 @@ import javax.tools.ToolProvider;
import static javax.tools.Diagnostic.Kind.*;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.main.CommandLine;
/**
* Javah generates support files for native methods.
@ -362,7 +364,7 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
if (fileManager == null)
fileManager = getDefaultFileManager(diagnosticListener, log);
Iterator<String> iter = args.iterator();
Iterator<String> iter = expandAtArgs(args).iterator();
noArgs = !iter.hasNext();
while (iter.hasNext()) {
@ -416,6 +418,18 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
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() {
return run();
}
@ -607,8 +621,8 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
}
};
}
private String getMessage(String key, Object... args) {
return getMessage(task_locale, key, args);
}

View File

@ -30,6 +30,8 @@ cant.create.dir=\
The directory {0} could not be create for output.
at.args.cant.read=\
Can''t read command line arguments from file {1}.
at.args.file.not.found=\
Can''t find file {0}.
at.args.io.exception=\
The following I/O problem was encountered when processing an @ \
argument on the command line: {0}.

View File

@ -1,86 +0,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 6985181
* @summary Annotations lost from classfile
*/
import java.io.*;
import java.util.*;
public class T6985181 {
public static void main(String... args) throws Exception{
new T6985181().run();
}
public void run() throws Exception {
String code = "@interface Simple { }\ninterface Test<@Simple T> { }";
File srcFile = writeFile("Test.java", code);
File classesDir = new File("classes");
classesDir.mkdirs();
compile("-d", classesDir.getPath(), srcFile.getPath());
String out = javap(new File(classesDir, srcFile.getName().replace(".java", ".class")));
if (!out.contains("RuntimeInvisibleTypeAnnotations"))
throw new Exception("RuntimeInvisibleTypeAnnotations not found");
}
void compile(String... args) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
int rc = com.sun.tools.javac.Main.compile(args, pw);
pw.close();
String out = sw.toString();
if (out.length() > 0)
System.err.println(out);
if (rc != 0)
throw new Exception("Compilation failed: rc=" + rc);
}
String javap(File classFile) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
String[] args = { "-v", classFile.getPath() };
int rc = com.sun.tools.javap.Main.run(args, pw);
pw.close();
String out = sw.toString();
if (out.length() > 0)
System.err.println(out);
if (rc != 0)
throw new Exception("javap failed: rc=" + rc);
return out;
}
File writeFile(String path, String body) throws IOException {
File f = new File(path);
FileWriter out = new FileWriter(f);
try {
out.write(body);
} finally {
out.close();
}
return f;
}
}

View File

@ -0,0 +1,105 @@
/*
* 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);
}
}

View File

@ -16,5 +16,5 @@
}
@A(b = @B(b2 = 1, b2 = 2),
b_arr = {@B(), @B(b2 = 1, b2 = 2)})
class T6881115<@A(b = @B(b2 = 1, b2 = 2),
b_arr = {@B(), @B(b2 = 1, b2 = 2)}) X> {}
class T6881115</*308 @A(b = @B(b2 = 1, b2 = 2),
b_arr = {@B(), @B(b2 = 1, b2 = 2)})*/ X> {}

View File

@ -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:30: compiler.err.duplicate.annotation.member.value: b2, B
T6881115.java:18:19: compiler.err.annotation.missing.default.value: B, b1
T6881115.java:19:34: compiler.err.duplicate.annotation.member.value: b2, B
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
10 errors

View File

@ -21,13 +21,9 @@
* questions.
*/
// key: compiler.err.type.annotations.not.supported.in.source
// options: -source 6
// key: compiler.warn.diamond.redundant.args
// options: -XDfindDiamond
@interface Anno { }
class TypeAnnotationsNotSupported {
void m() {
int i = (@Anno int) 3.14;
}
class Foo<X> {
Foo<String> fs = new Foo<String>();
}

View File

@ -21,15 +21,9 @@
* questions.
*/
/*
* @test
* @bug 6967002
* @summary JDK7 b99 javac compilation error (java.lang.AssertionError)
* @author Maurizio Cimadamore
* @compile/fail/ref=T6967002.out -XDrawDiagnostics T6967002.java
*/
class Test {
private static void m(byte[] octets) {
return m(octets..., ?);
}
// key: compiler.warn.diamond.redundant.args.1
// options: -XDfindDiamond
class Foo<X> {
Foo<?> fs = new Foo<String>();
}

View File

@ -23,7 +23,8 @@
/*
* @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
* @run main OverrideBridge
*/

View File

@ -0,0 +1,25 @@
/*
* @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>() {};
}
}

View File

@ -0,0 +1,5 @@
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

View File

@ -0,0 +1,2 @@
SemanticErrorTest.java:11:46: compiler.err.repeated.interface
1 error

View File

@ -0,0 +1,4 @@
SemanticErrorTest.java:11:46: compiler.err.repeated.interface
- compiler.err.proc.messager: Deliberate Error
SemanticErrorTest.java:11:46: compiler.err.repeated.interface
1 error

View File

@ -0,0 +1,13 @@
/*
* @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() { }
}

View File

@ -0,0 +1,13 @@
/*
* @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
}

View File

@ -0,0 +1,2 @@
SyntaxErrorTest.java:12:10: compiler.err.expected: ';'
1 error

View File

@ -21,24 +21,20 @@
* questions.
*/
/*
* @test
* @build DA TA Test TestProcessor
* @compile -proc:only -processor TestProcessor AnnoTreeTests.java
*/
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import static javax.tools.Diagnostic.Kind.*;
@Test(6)
class AnnoTreeTests {
// primitive types
@DA("int") int i1;
int i2 = (@TA("int") int) 0;
public class TestProcessor extends JavacTestingAbstractProcessor {
private int round = 0;
// simple array types
@DA("int[]") int[] a1;
int @TA("int") [] a2;
int[] a3 = (@TA("int[]") int[]) a1;
int[] a4 = (int @TA("int") []) a1;
// multi-dimensional array types
// (still to come)
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
if (++round == 1)
messager.printMessage(ERROR, "Deliberate Error");
return false;
}
}

View File

@ -78,7 +78,7 @@ public class TestAnonClassNames {
@Nesting(LOCAL)
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() {
return "I have no name!";
}
@ -95,9 +95,10 @@ public class TestAnonClassNames {
for(Class<?> clazz : classes) {
String name = clazz.getName();
Nesting anno = clazz.getAnnotation(Nesting.class);
System.out.format("%s is %s%n",
clazz.getName(),
clazz.getAnnotation(Nesting.class).value());
anno == null ? "(unset/ANONYMOUS)" : anno.value());
testClassName(name);
}
}
@ -161,8 +162,8 @@ class ClassNameProber extends JavacTestingAbstractProcessor {
typeElt.getQualifiedName().toString(),
typeElt.getKind().toString(),
nestingKind.toString());
if (typeElt.getAnnotation(Nesting.class).value() != nestingKind) {
Nesting anno = typeElt.getAnnotation(Nesting.class);
if ((anno == null ? NestingKind.ANONYMOUS : anno.value()) != nestingKind) {
throw new RuntimeException("Mismatch of expected and reported nesting kind.");
}
}

View File

@ -357,7 +357,9 @@ public class TreePosTest {
check("encl.start <= start", encl, self, encl.start <= self.start);
check("start <= pos", encl, self, self.start <= self.pos);
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",
encl, self, encl.pos <= self.start || self.end <= encl.pos);
}

View File

@ -1,8 +0,0 @@
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

View File

@ -1,59 +0,0 @@
/*
* 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 { }
}

View File

@ -1,41 +0,0 @@
/*
* 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 { }

View File

@ -1,46 +0,0 @@
/*
* 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 { }

View File

@ -1,55 +0,0 @@
/*
* 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 { }

View File

@ -1,38 +0,0 @@
/*
* 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(); }
}

View File

@ -1,181 +0,0 @@
/*
* 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();
}
}
}
}

View File

@ -1,12 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
AnnotationVersion.java:9:25: compiler.err.type.annotations.not.supported.in.source: 1.6
1 error

View File

@ -1,12 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
IncompleteArray.java:9:13: compiler.err.illegal.start.of.type
1 error

View File

@ -1,13 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
IncompleteVararg.java:10:19: compiler.err.illegal.start.of.type
1 error

View File

@ -1,13 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
IndexArray.java:10:15: compiler.err.illegal.start.of.expr
1 error

View File

@ -1,42 +0,0 @@
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 { }

View File

@ -1,6 +0,0 @@
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

View File

@ -1,35 +0,0 @@
/*
* 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 { }

View File

@ -1,10 +0,0 @@
/*
* @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 { };
}

View File

@ -1,2 +0,0 @@
Scopes.java:8:25: compiler.err.cant.resolve: kindname.class, UniqueInner, ,
1 error

View File

@ -1,13 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
StaticFields.java:10:17: compiler.err.illegal.start.of.expr
1 error

View File

@ -1,12 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
StaticMethods.java:9:22: compiler.err.annotation.type.not.applicable
1 error

View File

@ -1,35 +0,0 @@
/*
* 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 { }

View File

@ -1,14 +0,0 @@
/*
* @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(); }

View File

@ -1,2 +0,0 @@
DuplicateAnnotationValue.java:10:37: compiler.err.duplicate.annotation.member.value: value, A
1 error

View File

@ -1,15 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
DuplicateTypeAnnotation.java:11:26: compiler.err.duplicate.annotation
1 error

View File

@ -1,16 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
InvalidLocation.java:11:23: compiler.err.annotation.type.not.applicable
1 error

View File

@ -1,14 +0,0 @@
/*
* @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(); }

View File

@ -1,2 +0,0 @@
MissingAnnotationValue.java:10:23: compiler.err.annotation.missing.default.value: A, field
1 error

View File

@ -1,14 +0,0 @@
/*
* @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(); }

View File

@ -1,2 +0,0 @@
DuplicateAnnotationValue.java:10:26: compiler.err.duplicate.annotation.member.value: value, A
1 error

View File

@ -1,15 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
DuplicateTypeAnnotation.java:11:15: compiler.err.duplicate.annotation
1 error

View File

@ -1,16 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
InvalidLocation.java:11:12: compiler.err.annotation.type.not.applicable
1 error

View File

@ -1,14 +0,0 @@
/*
* @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(); }

View File

@ -1,2 +0,0 @@
MissingAnnotationValue.java:10:12: compiler.err.annotation.missing.default.value: A, field
1 error

View File

@ -1,14 +0,0 @@
/*
* @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(); }

View File

@ -1,2 +0,0 @@
DuplicateAnnotationValue.java:10:31: compiler.err.duplicate.annotation.member.value: value, A
1 error

View File

@ -1,14 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
DuplicateTypeAnnotation.java:10:20: compiler.err.duplicate.annotation
1 error

View File

@ -1,15 +0,0 @@
/*
* @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 { }

View File

@ -1,2 +0,0 @@
InvalidLocation.java:10:17: compiler.err.annotation.type.not.applicable
1 error

View File

@ -1,14 +0,0 @@
/*
* @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(); }

View File

@ -1,2 +0,0 @@
MissingAnnotationValue.java:10:17: compiler.err.annotation.missing.default.value: A, field
1 error

View File

@ -1,14 +0,0 @@
/*
* @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(); }

Some files were not shown because too many files have changed in this diff Show More