提交 59bf4070 编写于 作者: L lana

Merge

...@@ -31,44 +31,44 @@ ...@@ -31,44 +31,44 @@
--> -->
<project name="langtools-netbeans" default="build" basedir="../../.."> <project name="langtools-netbeans" default="build" basedir="../../..">
<property name="langtools.properties" <property name="langtools.properties"
location="make/netbeans/langtools/nbproject/private/langtools.properties"/> location="make/netbeans/langtools/nbproject/private/langtools.properties"/>
<!-- <!--
Instead of importing the main build file, we could call it when needed. Instead of importing the main build file, we could call it when needed.
That would reduce the list of Ant targets that get displayed for this That would reduce the list of Ant targets that get displayed for this
file, but it also complicates the interface between the project build file, but it also complicates the interface between the project build
file and the main build file. For example, some imported targets file and the main build file. For example, some imported targets
would have to be reclared, properties would have to be restructured, would have to be reclared, properties would have to be restructured,
and it would be harder to run results (e.g. in properties) from nested and it would be harder to run results (e.g. in properties) from nested
targets. targets.
--> -->
<import file="../../build.xml"/> <import file="../../build.xml"/>
<!-- Build project. (action: build; F11) <!-- Build project. (action: build; F11)
If langtools.tool.name is set, then just build that tool; otherwise If langtools.tool.name is set, then just build that tool; otherwise
build all tools. build all tools.
--> -->
<target name="build" depends="-get-tool-if-set,-build-tool,-build-all" <target name="build" depends="-get-tool-if-set,-build-tool,-build-all"
description="Build one or all langtools tools" description="Build one or all langtools tools"
/> />
<target name="-build-tool" if="langtools.tool.name"> <target name="-build-tool" if="langtools.tool.name">
<echo level="info" message="Building ${langtools.tool.name}"/> <echo level="info" message="Building ${langtools.tool.name}"/>
<echo level="verbose" message="(Unset langtools.tool.name to build all tools)"/> <echo level="verbose" message="(Unset langtools.tool.name to build all tools)"/>
<antcall target="build-${langtools.tool.name}"/> <antcall target="build-${langtools.tool.name}"/>
</target> </target>
<target name="-build-all" unless="langtools.tool.name"> <target name="-build-all" unless="langtools.tool.name">
<echo level="info" message="Building all tools"/> <echo level="info" message="Building all tools"/>
<echo level="verbose" message="(Set langtools.tool.name to build a single tool)"/> <echo level="verbose" message="(Set langtools.tool.name to build a single tool)"/>
<antcall target="build-all-tools"/> <antcall target="build-all-tools"/>
</target> </target>
<!-- Compile a single file. (action: compile.single; F9) --> <!-- Compile a single file. (action: compile.single; F9) -->
<target name="compile-single" depends="build-bootstrap-javac"> <target name="compile-single" depends="build-bootstrap-javac">
<fail unless="includes">Must set property 'includes'</fail> <fail unless="includes">Must set property 'includes'</fail>
<javac fork="true" executable="${build.bootstrap.dir}/bin/javac" <javac fork="true" executable="${build.bootstrap.dir}/bin/javac"
...@@ -78,38 +78,38 @@ ...@@ -78,38 +78,38 @@
sourcepath="" sourcepath=""
includeAntRuntime="no" includeAntRuntime="no"
target="${javac.target}" target="${javac.target}"
debug="${javac.debug}" debug="${javac.debug}"
debuglevel="${javac.debuglevel}"/> debuglevel="${javac.debuglevel}"/>
</target> </target>
<!-- Run tool. (action: run; F6) <!-- Run tool. (action: run; F6)
Use langtools.tool.name and langtools.tool.args properties if set; otherwise prompt Use langtools.tool.name and langtools.tool.args properties if set; otherwise prompt
the user. the user.
--> -->
<target name="run" depends="-check-target.java.home,build,-def-run,-get-tool-and-args" <target name="run" depends="-check-target.java.home,build,-def-run,-get-tool-and-args"
description="run tool"> description="run tool">
<echo level="info" message="Run ${langtools.tool.name} with args ${langtools.tool.args}"/> <echo level="info" message="Run ${langtools.tool.name} with args ${langtools.tool.args}"/>
<run mainclass="com.sun.tools.${langtools.tool.name}.Main" args="${langtools.tool.args}"/> <run mainclass="com.sun.tools.${langtools.tool.name}.Main" args="${langtools.tool.args}"/>
</target> </target>
<!-- Run a selected class. (action: run.single; shift-F6) --> <!-- Run a selected class. (action: run.single; shift-F6) -->
<target name="run-single" depends="-check-target.java.home,-def-run"> <target name="run-single" depends="-check-target.java.home,-def-run">
<fail unless="run.classname">Must set property 'run.classname' </fail> <fail unless="run.classname">Must set property 'run.classname' </fail>
<echo level="info" message="run ${run.classname}"/> <echo level="info" message="run ${run.classname}"/>
<run mainclass="${run.classname}" args=""/> <run mainclass="${run.classname}" args=""/>
</target> </target>
<!-- Test project, and display results if tests failed. (action: test; Alt-F6) <!-- Test project, and display results if tests failed. (action: test; Alt-F6)
If langtools.tool.name is set, then just test that tool; otherwise If langtools.tool.name is set, then just test that tool; otherwise
test all tools. test all tools.
--> -->
<target name="jtreg" depends="-get-tool-if-set,-jtreg-tool,-jtreg-all" <target name="jtreg" depends="-get-tool-if-set,-jtreg-tool,-jtreg-all"
description="Test one or all langtools tools" description="Test one or all langtools tools"
/> />
<target name="-jtreg-tool" if="langtools.tool.name"> <target name="-jtreg-tool" if="langtools.tool.name">
<echo level="info" message="Testing ${langtools.tool.name}"/> <echo level="info" message="Testing ${langtools.tool.name}"/>
<echo level="verbose" message="(Unset langtools.tool.name to test all tools)"/> <echo level="verbose" message="(Unset langtools.tool.name to test all tools)"/>
...@@ -118,7 +118,7 @@ ...@@ -118,7 +118,7 @@
<target name="-show-jtreg"/> <target name="-show-jtreg"/>
</antcall> </antcall>
</target> </target>
<target name="-jtreg-all" unless="langtools.tool.name"> <target name="-jtreg-all" unless="langtools.tool.name">
<echo level="info" message="Testing all tools"/> <echo level="info" message="Testing all tools"/>
<echo level="verbose" message="(Set langtools.tool.name to test a single tool)"/> <echo level="verbose" message="(Set langtools.tool.name to test a single tool)"/>
...@@ -127,36 +127,36 @@ ...@@ -127,36 +127,36 @@
<target name="-show-jtreg"/> <target name="-show-jtreg"/>
</antcall> </antcall>
</target> </target>
<target name="-show-jtreg" if="netbeans.home" unless="jtreg.passed"> <target name="-show-jtreg" if="netbeans.home" unless="jtreg.passed">
<nbbrowse file="${jtreg.report}/report.html"/> <nbbrowse file="${jtreg.report}/report.html"/>
<fail>Some tests failed; see report for details.</fail> <fail>Some tests failed; see report for details.</fail>
</target> </target>
<!-- Debug tool in NetBeans. --> <!-- Debug tool in NetBeans. -->
<target name="debug" depends="-check-target.java.home,-def-run,-def-start-debugger,-get-tool-and-args,build" if="netbeans.home"> <target name="debug" depends="-check-target.java.home,-def-run,-def-start-debugger,-get-tool-and-args,build" if="netbeans.home">
<echo level="info" message="Debug ${langtools.tool.name} with args ${langtools.tool.args}"/> <echo level="info" message="Debug ${langtools.tool.name} with args ${langtools.tool.args}"/>
<start-debugger/> <start-debugger/>
<run mainclass="com.sun.tools.${langtools.tool.name}.Main" args="${langtools.tool.args}" jpda.jvmargs="${jpda.jvmargs}"/> <run mainclass="com.sun.tools.${langtools.tool.name}.Main" args="${langtools.tool.args}" jpda.jvmargs="${jpda.jvmargs}"/>
</target> </target>
<!-- Debug a selected class . --> <!-- Debug a selected class . -->
<target name="debug-single" depends="-check-target.java.home,-def-start-debugger,-def-run"> <target name="debug-single" depends="-check-target.java.home,-def-start-debugger,-def-run">
<fail unless="debug.classname">Must set property 'debug.classname'</fail> <fail unless="debug.classname">Must set property 'debug.classname'</fail>
<start-debugger/> <start-debugger/>
<run mainclass="${debug.classname}" default.args="" jpda.jvmargs="${jpda.jvmargs}"/> <run mainclass="${debug.classname}" default.args="" jpda.jvmargs="${jpda.jvmargs}"/>
</target> </target>
<!-- Debug a jtreg test. --> <!-- Debug a jtreg test. -->
<target name="debug-jtreg" depends="-check-target.java.home,-def-start-debugger,-def-jtreg"> <target name="debug-jtreg" depends="-check-target.java.home,-def-start-debugger,-def-jtreg">
<fail unless="jtreg.tests">Must set property 'jtreg.tests'</fail> <fail unless="jtreg.tests">Must set property 'jtreg.tests'</fail>
<start-debugger/> <start-debugger/>
<jtreg-tool name="debug" samevm="false" tests="${jtreg.tests}" jpda.jvmargs="${jpda.jvmargs}"/> <jtreg-tool name="debug" samevm="false" tests="${jtreg.tests}" jpda.jvmargs="${jpda.jvmargs}"/>
</target> </target>
<!-- Update a class being debugged. --> <!-- Update a class being debugged. -->
<target name="debug-fix" if="langtools.tool.name"> <target name="debug-fix" if="langtools.tool.name">
<fail unless="class">Must set property 'class' <fail unless="class">Must set property 'class'
</fail> </fail>
...@@ -169,16 +169,16 @@ ...@@ -169,16 +169,16 @@
</fileset> </fileset>
</nbjpdareload> </nbjpdareload>
</target> </target>
<!-- Generate javadoc for one or all tools. (action: javadoc; Alt-F6) <!-- Generate javadoc for one or all tools. (action: javadoc; Alt-F6)
If langtools.tool.name is set, then just test that tool; otherwise If langtools.tool.name is set, then just test that tool; otherwise
test all tools. test all tools.
--> -->
<target name="javadoc" depends="-javadoc-tool,-javadoc-all" <target name="javadoc" depends="-javadoc-tool,-javadoc-all"
description="Generate javadoc for one or all langtools tools" description="Generate javadoc for one or all langtools tools"
/> />
<target name="-javadoc-tool" if="langtools.tool.name"> <target name="-javadoc-tool" if="langtools.tool.name">
<echo level="info" message="Generate javadoc for ${langtools.tool.name}"/> <echo level="info" message="Generate javadoc for ${langtools.tool.name}"/>
<echo level="verbose" message="(Unset langtools.tool.name to generate javadoc for all tools)"/> <echo level="verbose" message="(Unset langtools.tool.name to generate javadoc for all tools)"/>
...@@ -187,7 +187,7 @@ ...@@ -187,7 +187,7 @@
<target name="-show-javadoc"/> <target name="-show-javadoc"/>
</antcall> </antcall>
</target> </target>
<target name="-javadoc-all" unless="langtools.tool.name"> <target name="-javadoc-all" unless="langtools.tool.name">
<echo level="info" message="Generate javadoc for all tools"/> <echo level="info" message="Generate javadoc for all tools"/>
<echo level="verbose" message="(Set langtools.tool.name to generate javadoc for a single tool)"/> <echo level="verbose" message="(Set langtools.tool.name to generate javadoc for a single tool)"/>
...@@ -196,26 +196,26 @@ ...@@ -196,26 +196,26 @@
<target name="-show-javadoc"/> <target name="-show-javadoc"/>
</antcall> </antcall>
</target> </target>
<target name="-show-javadoc" if="netbeans.home"> <target name="-show-javadoc" if="netbeans.home">
<!-- what if doing javadoc for all? --> <!-- what if doing javadoc for all? -->
<nbbrowse file="${build.javadoc.dir}/${langtools.tool.name}/index.html"/> <nbbrowse file="${build.javadoc.dir}/${langtools.tool.name}/index.html"/>
</target> </target>
<!-- Prompt for values. --> <!-- Prompt for values. -->
<target name="-get-tool-if-set" depends="-def-select-tool"> <target name="-get-tool-if-set" depends="-def-select-tool">
<select-tool <select-tool
toolproperty="langtools.tool.name" toolproperty="langtools.tool.name"
propertyfile="${langtools.properties}" propertyfile="${langtools.properties}"
askIfUnset="false" askIfUnset="false"
/> />
</target> </target>
<target name="-get-tool-and-args" depends="-def-select-tool"> <target name="-get-tool-and-args" depends="-def-select-tool">
<select-tool <select-tool
toolproperty="langtools.tool.name" toolproperty="langtools.tool.name"
argsproperty="langtools.tool.args" argsproperty="langtools.tool.args"
propertyfile="${langtools.properties}" propertyfile="${langtools.properties}"
askIfUnset="true" askIfUnset="true"
/> />
...@@ -236,7 +236,7 @@ ...@@ -236,7 +236,7 @@
</sequential> </sequential>
</macrodef> </macrodef>
</target> </target>
<!-- Macro to start the debugger and set a property containg the args needed by the run task --> <!-- Macro to start the debugger and set a property containg the args needed by the run task -->
<target name="-def-start-debugger" if="netbeans.home"> <target name="-def-start-debugger" if="netbeans.home">
<macrodef name="start-debugger"> <macrodef name="start-debugger">
...@@ -251,28 +251,29 @@ ...@@ -251,28 +251,29 @@
<pathelement location="${src.classes.dir}"/> <pathelement location="${src.classes.dir}"/>
</sourcepath> </sourcepath>
</nbjpdastart> </nbjpdastart>
<property <property
name="@{jpda.jvmargs.property}" name="@{jpda.jvmargs.property}"
value="-Xdebug -Xnoagent -Djava.compiler=none -Xrunjdwp:transport=dt_socket,address=${jpda.address}" value="-Xdebug -Xnoagent -Djava.compiler=none -Xrunjdwp:transport=dt_socket,address=${jpda.address}"
/> />
</sequential> </sequential>
</macrodef> </macrodef>
</target> </target>
<target name="-def-select-tool"> <target name="-def-select-tool">
<mkdir dir="${build.toolclasses.dir}"/> <mkdir dir="${build.toolclasses.dir}"/>
<javac srcdir="${make.tools.dir}/SelectTool" <javac srcdir="${make.tools.dir}/SelectTool"
destdir="${build.toolclasses.dir}/" destdir="${build.toolclasses.dir}/"
classpath="${ant.home}/lib/ant.jar" classpath="${ant.core.lib}"
debug="${javac.debug}" includeantruntime="false"
debug="${javac.debug}"
debuglevel="${javac.debuglevel}"> debuglevel="${javac.debuglevel}">
<compilerarg line="-Xlint"/> <compilerarg line="-Xlint"/>
</javac> </javac>
<taskdef name="select-tool" <taskdef name="select-tool"
classname="SelectToolTask" classname="SelectToolTask"
classpath="${build.toolclasses.dir}/"/> classpath="${build.toolclasses.dir}/"/>
</target> </target>
<target name="select-tool" depends="-def-select-tool"> <target name="select-tool" depends="-def-select-tool">
<select-tool propertyfile="${langtools.properties}"/> <select-tool propertyfile="${langtools.properties}"/>
</target> </target>
......
/* /*
* Copyright (c) 2004, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -99,9 +99,6 @@ public class JavaCompiler extends com.sun.tools.javac.main.JavaCompiler { ...@@ -99,9 +99,6 @@ public class JavaCompiler extends com.sun.tools.javac.main.JavaCompiler {
private static Context preRegister(Context context) { private static Context preRegister(Context context) {
Bark.preRegister(context); Bark.preRegister(context);
// force the use of the scanner that captures Javadoc comments
DocCommentScanner.Factory.preRegister(context);
if (context.get(JavaFileManager.class) == null) if (context.get(JavaFileManager.class) == null)
JavacFileManager.preRegister(context); JavacFileManager.preRegister(context);
......
/* /*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -96,9 +96,6 @@ public class JavacTaskImpl extends JavacTask { ...@@ -96,9 +96,6 @@ public class JavacTaskImpl extends JavacTask {
args.getClass(); args.getClass();
context.getClass(); context.getClass();
fileObjects.getClass(); fileObjects.getClass();
// force the use of the scanner that captures Javadoc comments
com.sun.tools.javac.parser.DocCommentScanner.Factory.preRegister(context);
} }
JavacTaskImpl(JavacTool tool, JavacTaskImpl(JavacTool tool,
...@@ -337,9 +334,13 @@ public class JavacTaskImpl extends JavacTask { ...@@ -337,9 +334,13 @@ public class JavacTaskImpl extends JavacTask {
ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>(); ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
for (JCCompilationUnit unit : units) { for (JCCompilationUnit unit : units) {
for (JCTree node : unit.defs) for (JCTree node : unit.defs) {
if (node.getTag() == JCTree.CLASSDEF) if (node.getTag() == JCTree.CLASSDEF) {
elements.append(((JCTree.JCClassDecl) node).sym); JCClassDecl cdef = (JCClassDecl) node;
if (cdef.sym != null) // maybe null if errors in anno processing
elements.append(cdef.sym);
}
}
} }
return elements.toList(); return elements.toList();
} }
......
/* /*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -56,7 +56,6 @@ import com.sun.tools.javac.comp.Env; ...@@ -56,7 +56,6 @@ import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.MemberEnter; import com.sun.tools.javac.comp.MemberEnter;
import com.sun.tools.javac.comp.Resolve; import com.sun.tools.javac.comp.Resolve;
import com.sun.tools.javac.model.JavacElements; import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.processing.JavacMessager;
import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree.*; import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree;
...@@ -81,14 +80,15 @@ import com.sun.tools.javac.util.Pair; ...@@ -81,14 +80,15 @@ import com.sun.tools.javac.util.Pair;
*/ */
public class JavacTrees extends Trees { public class JavacTrees extends Trees {
private final Resolve resolve; // in a world of a single context per compilation, these would all be final
private final Enter enter; private Resolve resolve;
private final Log log; private Enter enter;
private final MemberEnter memberEnter; private Log log;
private final Attr attr; private MemberEnter memberEnter;
private final TreeMaker treeMaker; private Attr attr;
private final JavacElements elements; private TreeMaker treeMaker;
private final JavacTaskImpl javacTaskImpl; private JavacElements elements;
private JavacTaskImpl javacTaskImpl;
public static JavacTrees instance(JavaCompiler.CompilationTask task) { public static JavacTrees instance(JavaCompiler.CompilationTask task) {
if (!(task instanceof JavacTaskImpl)) if (!(task instanceof JavacTaskImpl))
...@@ -111,6 +111,14 @@ public class JavacTrees extends Trees { ...@@ -111,6 +111,14 @@ public class JavacTrees extends Trees {
private JavacTrees(Context context) { private JavacTrees(Context context) {
context.put(JavacTrees.class, this); context.put(JavacTrees.class, this);
init(context);
}
public void updateContext(Context context) {
init(context);
}
private void init(Context context) {
attr = Attr.instance(context); attr = Attr.instance(context);
enter = Enter.instance(context); enter = Enter.instance(context);
elements = JavacElements.instance(context); elements = JavacElements.instance(context);
...@@ -337,6 +345,7 @@ public class JavacTrees extends Trees { ...@@ -337,6 +345,7 @@ public class JavacTrees extends Trees {
super(M); super(M);
} }
@Override
public <T extends JCTree> T copy(T t, JCTree leaf) { public <T extends JCTree> T copy(T t, JCTree leaf) {
T t2 = super.copy(t, leaf); T t2 = super.copy(t, leaf);
if (t == leaf) if (t == leaf)
......
...@@ -70,6 +70,45 @@ public class Scope { ...@@ -70,6 +70,45 @@ public class Scope {
*/ */
public int nelems = 0; public int nelems = 0;
/** A timestamp - useful to quickly check whether a scope has changed or not
*/
public ScopeCounter scopeCounter;
static ScopeCounter dummyCounter = new ScopeCounter() {
@Override
public void inc() {
//do nothing
}
};
public static class ScopeCounter {
protected static final Context.Key<ScopeCounter> scopeCounterKey =
new Context.Key<ScopeCounter>();
public static ScopeCounter instance(Context context) {
ScopeCounter instance = context.get(scopeCounterKey);
if (instance == null)
instance = new ScopeCounter(context);
return instance;
}
protected ScopeCounter(Context context) {
context.put(scopeCounterKey, this);
}
private ScopeCounter() {};
private long val = 0;
public void inc() {
val++;
}
public long val() {
return val;
}
}
/** Every hash bucket is a list of Entry's which ends in sentinel. /** Every hash bucket is a list of Entry's which ends in sentinel.
*/ */
private static final Entry sentinel = new Entry(null, null, null, null); private static final Entry sentinel = new Entry(null, null, null, null);
...@@ -80,12 +119,12 @@ public class Scope { ...@@ -80,12 +119,12 @@ public class Scope {
/** A value for the empty scope. /** A value for the empty scope.
*/ */
public static final Scope emptyScope = new Scope(null, null, new Entry[]{}); public static final Scope emptyScope = new Scope(null, null, new Entry[]{}, dummyCounter);
/** Construct a new scope, within scope next, with given owner, using /** Construct a new scope, within scope next, with given owner, using
* given table. The table's length must be an exponent of 2. * given table. The table's length must be an exponent of 2.
*/ */
Scope(Scope next, Symbol owner, Entry[] table) { private Scope(Scope next, Symbol owner, Entry[] table, ScopeCounter scopeCounter) {
this.next = next; this.next = next;
assert emptyScope == null || owner != null; assert emptyScope == null || owner != null;
this.owner = owner; this.owner = owner;
...@@ -94,13 +133,18 @@ public class Scope { ...@@ -94,13 +133,18 @@ public class Scope {
this.elems = null; this.elems = null;
this.nelems = 0; this.nelems = 0;
this.shared = 0; this.shared = 0;
this.scopeCounter = scopeCounter;
} }
/** Construct a new scope, within scope next, with given owner, /** Construct a new scope, within scope next, with given owner,
* using a fresh table of length INITIAL_SIZE. * using a fresh table of length INITIAL_SIZE.
*/ */
public Scope(Symbol owner) { public Scope(Symbol owner) {
this(null, owner, new Entry[INITIAL_SIZE]); this(owner, dummyCounter);
}
protected Scope(Symbol owner, ScopeCounter scopeCounter) {
this(null, owner, new Entry[INITIAL_SIZE], scopeCounter);
for (int i = 0; i < INITIAL_SIZE; i++) table[i] = sentinel; for (int i = 0; i < INITIAL_SIZE; i++) table[i] = sentinel;
} }
...@@ -110,7 +154,7 @@ public class Scope { ...@@ -110,7 +154,7 @@ public class Scope {
* of fresh tables. * of fresh tables.
*/ */
public Scope dup() { public Scope dup() {
Scope result = new Scope(this, this.owner, this.table); Scope result = new Scope(this, this.owner, this.table, scopeCounter);
shared++; shared++;
// System.out.println("====> duping scope " + this.hashCode() + " owned by " + this.owner + " to " + result.hashCode()); // System.out.println("====> duping scope " + this.hashCode() + " owned by " + this.owner + " to " + result.hashCode());
// new Error().printStackTrace(System.out); // new Error().printStackTrace(System.out);
...@@ -123,7 +167,7 @@ public class Scope { ...@@ -123,7 +167,7 @@ public class Scope {
* of fresh tables. * of fresh tables.
*/ */
public Scope dup(Symbol newOwner) { public Scope dup(Symbol newOwner) {
Scope result = new Scope(this, newOwner, this.table); Scope result = new Scope(this, newOwner, this.table, scopeCounter);
shared++; shared++;
// System.out.println("====> duping scope " + this.hashCode() + " owned by " + newOwner + " to " + result.hashCode()); // System.out.println("====> duping scope " + this.hashCode() + " owned by " + newOwner + " to " + result.hashCode());
// new Error().printStackTrace(System.out); // new Error().printStackTrace(System.out);
...@@ -135,7 +179,7 @@ public class Scope { ...@@ -135,7 +179,7 @@ public class Scope {
* the table of its outer scope. * the table of its outer scope.
*/ */
public Scope dupUnshared() { public Scope dupUnshared() {
return new Scope(this, this.owner, this.table.clone()); return new Scope(this, this.owner, this.table.clone(), scopeCounter);
} }
/** Remove all entries of this scope from its table, if shared /** Remove all entries of this scope from its table, if shared
...@@ -211,6 +255,7 @@ public class Scope { ...@@ -211,6 +255,7 @@ public class Scope {
table[hash] = e; table[hash] = e;
elems = e; elems = e;
nelems++; nelems++;
scopeCounter.inc();
} }
Entry makeEntry(Symbol sym, Entry shadowed, Entry sibling, Scope scope, Scope origin) { Entry makeEntry(Symbol sym, Entry shadowed, Entry sibling, Scope scope, Scope origin) {
...@@ -226,6 +271,8 @@ public class Scope { ...@@ -226,6 +271,8 @@ public class Scope {
while (e.scope == this && e.sym != sym) e = e.next(); while (e.scope == this && e.sym != sym) e = e.next();
if (e.scope == null) return; if (e.scope == null) return;
scopeCounter.inc();
// remove e from table and shadowed list; // remove e from table and shadowed list;
Entry te = table[sym.name.hashCode() & hashMask]; Entry te = table[sym.name.hashCode() & hashMask];
if (te == e) if (te == e)
...@@ -472,7 +519,7 @@ public class Scope { ...@@ -472,7 +519,7 @@ public class Scope {
public static final Entry[] emptyTable = new Entry[0]; public static final Entry[] emptyTable = new Entry[0];
public DelegatedScope(Scope outer) { public DelegatedScope(Scope outer) {
super(outer, outer.owner, emptyTable); super(outer, outer.owner, emptyTable, outer.scopeCounter);
delegatee = outer; delegatee = outer;
} }
public Scope dup() { public Scope dup() {
...@@ -498,10 +545,22 @@ public class Scope { ...@@ -498,10 +545,22 @@ public class Scope {
} }
} }
/** A class scope, for which a scope counter should be provided */
public static class ClassScope extends Scope {
ClassScope(Scope next, Symbol owner, Entry[] table, ScopeCounter scopeCounter) {
super(next, owner, table, scopeCounter);
}
public ClassScope(Symbol owner, ScopeCounter scopeCounter) {
super(owner, scopeCounter);
}
}
/** An error scope, for which the owner should be an error symbol. */ /** An error scope, for which the owner should be an error symbol. */
public static class ErrorScope extends Scope { public static class ErrorScope extends Scope {
ErrorScope(Scope next, Symbol errSymbol, Entry[] table) { ErrorScope(Scope next, Symbol errSymbol, Entry[] table) {
super(next, /*owner=*/errSymbol, table); super(next, /*owner=*/errSymbol, table, dummyCounter);
} }
public ErrorScope(Symbol errSymbol) { public ErrorScope(Symbol errSymbol) {
super(errSymbol); super(errSymbol);
......
...@@ -25,11 +25,14 @@ ...@@ -25,11 +25,14 @@
package com.sun.tools.javac.code; package com.sun.tools.javac.code;
import com.sun.tools.javac.util.*; import java.util.*;
import com.sun.tools.javac.jvm.Target;
import javax.lang.model.SourceVersion; import javax.lang.model.SourceVersion;
import static javax.lang.model.SourceVersion.*; import static javax.lang.model.SourceVersion.*;
import java.util.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.jvm.Target;
import static com.sun.tools.javac.main.OptionName.*;
/** The source language version accepted. /** The source language version accepted.
* *
...@@ -71,7 +74,7 @@ public enum Source { ...@@ -71,7 +74,7 @@ public enum Source {
Source instance = context.get(sourceKey); Source instance = context.get(sourceKey);
if (instance == null) { if (instance == null) {
Options options = Options.instance(context); Options options = Options.instance(context);
String sourceString = options.get("-source"); String sourceString = options.get(SOURCE);
if (sourceString != null) instance = lookup(sourceString); if (sourceString != null) instance = lookup(sourceString);
if (instance == null) instance = DEFAULT; if (instance == null) instance = DEFAULT;
context.put(sourceKey, instance); context.put(sourceKey, instance);
......
/* /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -960,6 +960,8 @@ public abstract class Symbol implements Element { ...@@ -960,6 +960,8 @@ public abstract class Symbol implements Element {
return ElementKind.ENUM_CONSTANT; return ElementKind.ENUM_CONSTANT;
} else if (owner.kind == TYP || owner.kind == ERR) { } else if (owner.kind == TYP || owner.kind == ERR) {
return ElementKind.FIELD; return ElementKind.FIELD;
} else if (isResourceVariable()) {
return ElementKind.RESOURCE_VARIABLE;
} else { } else {
return ElementKind.LOCAL_VARIABLE; return ElementKind.LOCAL_VARIABLE;
} }
......
...@@ -74,6 +74,7 @@ public class Symtab { ...@@ -74,6 +74,7 @@ public class Symtab {
public final JCNoType voidType = new JCNoType(TypeTags.VOID); public final JCNoType voidType = new JCNoType(TypeTags.VOID);
private final Names names; private final Names names;
private final Scope.ScopeCounter scopeCounter;
private final ClassReader reader; private final ClassReader reader;
private final Target target; private final Target target;
...@@ -340,6 +341,7 @@ public class Symtab { ...@@ -340,6 +341,7 @@ public class Symtab {
context.put(symtabKey, this); context.put(symtabKey, this);
names = Names.instance(context); names = Names.instance(context);
scopeCounter = Scope.ScopeCounter.instance(context);
target = Target.instance(context); target = Target.instance(context);
// Create the unknown type // Create the unknown type
...@@ -386,7 +388,7 @@ public class Symtab { ...@@ -386,7 +388,7 @@ public class Symtab {
// Create class to hold all predefined constants and operations. // Create class to hold all predefined constants and operations.
predefClass = new ClassSymbol(PUBLIC|ACYCLIC, names.empty, rootPackage); predefClass = new ClassSymbol(PUBLIC|ACYCLIC, names.empty, rootPackage);
Scope scope = new Scope(predefClass); Scope scope = new Scope.ClassScope(predefClass, scopeCounter);
predefClass.members_field = scope; predefClass.members_field = scope;
// Enter symbols for basic types. // Enter symbols for basic types.
...@@ -476,7 +478,7 @@ public class Symtab { ...@@ -476,7 +478,7 @@ public class Symtab {
proprietarySymbol.completer = null; proprietarySymbol.completer = null;
proprietarySymbol.flags_field = PUBLIC|ACYCLIC|ANNOTATION|INTERFACE; proprietarySymbol.flags_field = PUBLIC|ACYCLIC|ANNOTATION|INTERFACE;
proprietarySymbol.erasure_field = proprietaryType; proprietarySymbol.erasure_field = proprietaryType;
proprietarySymbol.members_field = new Scope(proprietarySymbol); proprietarySymbol.members_field = new Scope.ClassScope(proprietarySymbol, scopeCounter);
proprietaryType.typarams_field = List.nil(); proprietaryType.typarams_field = List.nil();
proprietaryType.allparams_field = List.nil(); proprietaryType.allparams_field = List.nil();
proprietaryType.supertype_field = annotationType; proprietaryType.supertype_field = annotationType;
...@@ -488,7 +490,7 @@ public class Symtab { ...@@ -488,7 +490,7 @@ public class Symtab {
ClassType arrayClassType = (ClassType)arrayClass.type; ClassType arrayClassType = (ClassType)arrayClass.type;
arrayClassType.supertype_field = objectType; arrayClassType.supertype_field = objectType;
arrayClassType.interfaces_field = List.of(cloneableType, serializableType); arrayClassType.interfaces_field = List.of(cloneableType, serializableType);
arrayClass.members_field = new Scope(arrayClass); arrayClass.members_field = new Scope.ClassScope(arrayClass, scopeCounter);
lengthVar = new VarSymbol( lengthVar = new VarSymbol(
PUBLIC | FINAL, PUBLIC | FINAL,
names.length, names.length,
......
...@@ -69,6 +69,7 @@ public class Types { ...@@ -69,6 +69,7 @@ public class Types {
new Context.Key<Types>(); new Context.Key<Types>();
final Symtab syms; final Symtab syms;
final Scope.ScopeCounter scopeCounter;
final JavacMessages messages; final JavacMessages messages;
final Names names; final Names names;
final boolean allowBoxing; final boolean allowBoxing;
...@@ -89,6 +90,7 @@ public class Types { ...@@ -89,6 +90,7 @@ public class Types {
protected Types(Context context) { protected Types(Context context) {
context.put(typesKey, this); context.put(typesKey, this);
syms = Symtab.instance(context); syms = Symtab.instance(context);
scopeCounter = Scope.ScopeCounter.instance(context);
names = Names.instance(context); names = Names.instance(context);
allowBoxing = Source.instance(context).allowBoxing(); allowBoxing = Source.instance(context).allowBoxing();
reader = ClassReader.instance(context); reader = ClassReader.instance(context);
...@@ -1984,22 +1986,26 @@ public class Types { ...@@ -1984,22 +1986,26 @@ public class Types {
final MethodSymbol cachedImpl; final MethodSymbol cachedImpl;
final Filter<Symbol> implFilter; final Filter<Symbol> implFilter;
final boolean checkResult; final boolean checkResult;
final Scope.ScopeCounter scopeCounter;
public Entry(MethodSymbol cachedImpl, public Entry(MethodSymbol cachedImpl,
Filter<Symbol> scopeFilter, Filter<Symbol> scopeFilter,
boolean checkResult) { boolean checkResult,
Scope.ScopeCounter scopeCounter) {
this.cachedImpl = cachedImpl; this.cachedImpl = cachedImpl;
this.implFilter = scopeFilter; this.implFilter = scopeFilter;
this.checkResult = checkResult; this.checkResult = checkResult;
this.scopeCounter = scopeCounter;
} }
boolean matches(Filter<Symbol> scopeFilter, boolean checkResult) { boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, Scope.ScopeCounter scopeCounter) {
return this.implFilter == scopeFilter && return this.implFilter == scopeFilter &&
this.checkResult == checkResult; this.checkResult == checkResult &&
this.scopeCounter.val() >= scopeCounter.val();
} }
} }
MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter, Scope.ScopeCounter scopeCounter) {
SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms); SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null; Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
if (cache == null) { if (cache == null) {
...@@ -2008,9 +2014,9 @@ public class Types { ...@@ -2008,9 +2014,9 @@ public class Types {
} }
Entry e = cache.get(origin); Entry e = cache.get(origin);
if (e == null || if (e == null ||
!e.matches(implFilter, checkResult)) { !e.matches(implFilter, checkResult, scopeCounter)) {
MethodSymbol impl = implementationInternal(ms, origin, Types.this, checkResult, implFilter); MethodSymbol impl = implementationInternal(ms, origin, Types.this, checkResult, implFilter);
cache.put(origin, new Entry(impl, implFilter, checkResult)); cache.put(origin, new Entry(impl, implFilter, checkResult, scopeCounter));
return impl; return impl;
} }
else { else {
...@@ -2038,7 +2044,7 @@ public class Types { ...@@ -2038,7 +2044,7 @@ public class Types {
private ImplementationCache implCache = new ImplementationCache(); private ImplementationCache implCache = new ImplementationCache();
public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) { public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
return implCache.get(ms, origin, checkResult, implFilter); return implCache.get(ms, origin, checkResult, implFilter, scopeCounter);
} }
// </editor-fold> // </editor-fold>
......
...@@ -119,10 +119,10 @@ public class Attr extends JCTree.Visitor { ...@@ -119,10 +119,10 @@ public class Attr extends JCTree.Visitor {
allowAnonOuterThis = source.allowAnonOuterThis(); allowAnonOuterThis = source.allowAnonOuterThis();
allowStringsInSwitch = source.allowStringsInSwitch(); allowStringsInSwitch = source.allowStringsInSwitch();
sourceName = source.name; sourceName = source.name;
relax = (options.get("-retrofit") != null || relax = (options.isSet("-retrofit") ||
options.get("-relax") != null); options.isSet("-relax"));
useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null; useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
enableSunApiLintControl = options.get("enableSunApiLintControl") != null; enableSunApiLintControl = options.isSet("enableSunApiLintControl");
} }
/** Switch: relax some constraints for retrofit mode. /** Switch: relax some constraints for retrofit mode.
...@@ -1422,7 +1422,8 @@ public class Attr extends JCTree.Visitor { ...@@ -1422,7 +1422,8 @@ public class Attr extends JCTree.Visitor {
// Compute the result type. // Compute the result type.
Type restype = mtype.getReturnType(); Type restype = mtype.getReturnType();
assert restype.tag != WILDCARD : mtype; if (restype.tag == WILDCARD)
throw new AssertionError(mtype);
// as a special case, array.clone() has a result that is // as a special case, array.clone() has a result that is
// the same as static type of the array being cloned // the same as static type of the array being cloned
......
...@@ -25,7 +25,6 @@ ...@@ -25,7 +25,6 @@
package com.sun.tools.javac.comp; package com.sun.tools.javac.comp;
import com.sun.source.tree.AssignmentTree;
import java.util.*; import java.util.*;
import java.util.Set; import java.util.Set;
...@@ -46,6 +45,8 @@ import static com.sun.tools.javac.code.Flags.*; ...@@ -46,6 +45,8 @@ import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*; import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*; import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.main.OptionName.*;
/** Type checking helper class for the attribution phase. /** Type checking helper class for the attribution phase.
* *
* <p><b>This is NOT part of any supported API. * <p><b>This is NOT part of any supported API.
...@@ -60,6 +61,7 @@ public class Check { ...@@ -60,6 +61,7 @@ public class Check {
private final Names names; private final Names names;
private final Log log; private final Log log;
private final Symtab syms; private final Symtab syms;
private final Enter enter;
private final Infer infer; private final Infer infer;
private final Types types; private final Types types;
private final JCDiagnostic.Factory diags; private final JCDiagnostic.Factory diags;
...@@ -86,6 +88,7 @@ public class Check { ...@@ -86,6 +88,7 @@ public class Check {
names = Names.instance(context); names = Names.instance(context);
log = Log.instance(context); log = Log.instance(context);
syms = Symtab.instance(context); syms = Symtab.instance(context);
enter = Enter.instance(context);
infer = Infer.instance(context); infer = Infer.instance(context);
this.types = Types.instance(context); this.types = Types.instance(context);
diags = JCDiagnostic.Factory.instance(context); diags = JCDiagnostic.Factory.instance(context);
...@@ -97,10 +100,10 @@ public class Check { ...@@ -97,10 +100,10 @@ public class Check {
allowGenerics = source.allowGenerics(); allowGenerics = source.allowGenerics();
allowAnnotations = source.allowAnnotations(); allowAnnotations = source.allowAnnotations();
allowCovariantReturns = source.allowCovariantReturns(); allowCovariantReturns = source.allowCovariantReturns();
complexInference = options.get("-complexinference") != null; complexInference = options.isSet(COMPLEXINFERENCE);
skipAnnotations = options.get("skipAnnotations") != null; skipAnnotations = options.isSet("skipAnnotations");
warnOnSyntheticConflicts = options.get("warnOnSyntheticConflicts") != null; warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
suppressAbortOnBadClassFile = options.get("suppressAbortOnBadClassFile") != null; suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
Target target = Target.instance(context); Target target = Target.instance(context);
syntheticNameChar = target.syntheticNameChar(); syntheticNameChar = target.syntheticNameChar();
...@@ -1727,6 +1730,113 @@ public class Check { ...@@ -1727,6 +1730,113 @@ public class Check {
return undef; return undef;
} }
void checkNonCyclicDecl(JCClassDecl tree) {
CycleChecker cc = new CycleChecker();
cc.scan(tree);
if (!cc.errorFound && !cc.partialCheck) {
tree.sym.flags_field |= ACYCLIC;
}
}
class CycleChecker extends TreeScanner {
List<Symbol> seenClasses = List.nil();
boolean errorFound = false;
boolean partialCheck = false;
private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
if (sym != null && sym.kind == TYP) {
Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
if (classEnv != null) {
DiagnosticSource prevSource = log.currentSource();
try {
log.useSource(classEnv.toplevel.sourcefile);
scan(classEnv.tree);
}
finally {
log.useSource(prevSource.getFile());
}
} else if (sym.kind == TYP) {
checkClass(pos, sym, List.<JCTree>nil());
}
} else {
//not completed yet
partialCheck = true;
}
}
@Override
public void visitSelect(JCFieldAccess tree) {
super.visitSelect(tree);
checkSymbol(tree.pos(), tree.sym);
}
@Override
public void visitIdent(JCIdent tree) {
checkSymbol(tree.pos(), tree.sym);
}
@Override
public void visitTypeApply(JCTypeApply tree) {
scan(tree.clazz);
}
@Override
public void visitTypeArray(JCArrayTypeTree tree) {
scan(tree.elemtype);
}
@Override
public void visitClassDef(JCClassDecl tree) {
List<JCTree> supertypes = List.nil();
if (tree.getExtendsClause() != null) {
supertypes = supertypes.prepend(tree.getExtendsClause());
}
if (tree.getImplementsClause() != null) {
for (JCTree intf : tree.getImplementsClause()) {
supertypes = supertypes.prepend(intf);
}
}
checkClass(tree.pos(), tree.sym, supertypes);
}
void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
if ((c.flags_field & ACYCLIC) != 0)
return;
if (seenClasses.contains(c)) {
errorFound = true;
noteCyclic(pos, (ClassSymbol)c);
} else if (!c.type.isErroneous()) {
try {
seenClasses = seenClasses.prepend(c);
if (c.type.tag == CLASS) {
if (supertypes.nonEmpty()) {
scan(supertypes);
}
else {
ClassType ct = (ClassType)c.type;
if (ct.supertype_field == null ||
ct.interfaces_field == null) {
//not completed yet
partialCheck = true;
return;
}
checkSymbol(pos, ct.supertype_field.tsym);
for (Type intf : ct.interfaces_field) {
checkSymbol(pos, intf.tsym);
}
}
if (c.owner.kind == TYP) {
checkSymbol(pos, c.owner);
}
}
} finally {
seenClasses = seenClasses.tail;
}
}
}
}
/** Check for cyclic references. Issue an error if the /** Check for cyclic references. Issue an error if the
* symbol of the type referred to has a LOCKED flag set. * symbol of the type referred to has a LOCKED flag set.
* *
......
...@@ -94,6 +94,7 @@ public class Enter extends JCTree.Visitor { ...@@ -94,6 +94,7 @@ public class Enter extends JCTree.Visitor {
Log log; Log log;
Symtab syms; Symtab syms;
Scope.ScopeCounter scopeCounter;
Check chk; Check chk;
TreeMaker make; TreeMaker make;
ClassReader reader; ClassReader reader;
...@@ -121,6 +122,7 @@ public class Enter extends JCTree.Visitor { ...@@ -121,6 +122,7 @@ public class Enter extends JCTree.Visitor {
reader = ClassReader.instance(context); reader = ClassReader.instance(context);
make = TreeMaker.instance(context); make = TreeMaker.instance(context);
syms = Symtab.instance(context); syms = Symtab.instance(context);
scopeCounter = Scope.ScopeCounter.instance(context);
chk = Check.instance(context); chk = Check.instance(context);
memberEnter = MemberEnter.instance(context); memberEnter = MemberEnter.instance(context);
types = Types.instance(context); types = Types.instance(context);
...@@ -189,7 +191,7 @@ public class Enter extends JCTree.Visitor { ...@@ -189,7 +191,7 @@ public class Enter extends JCTree.Visitor {
*/ */
public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) { public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) {
Env<AttrContext> localEnv = Env<AttrContext> localEnv =
env.dup(tree, env.info.dup(new Scope(tree.sym))); env.dup(tree, env.info.dup(new Scope.ClassScope(tree.sym, scopeCounter)));
localEnv.enclClass = tree; localEnv.enclClass = tree;
localEnv.outer = env; localEnv.outer = env;
localEnv.info.isSelfCall = false; localEnv.info.isSelfCall = false;
...@@ -325,7 +327,7 @@ public class Enter extends JCTree.Visitor { ...@@ -325,7 +327,7 @@ public class Enter extends JCTree.Visitor {
c.flatname = names.fromString(tree.packge + "." + name); c.flatname = names.fromString(tree.packge + "." + name);
c.sourcefile = tree.sourcefile; c.sourcefile = tree.sourcefile;
c.completer = null; c.completer = null;
c.members_field = new Scope(c); c.members_field = new Scope.ClassScope(c, scopeCounter);
tree.packge.package_info = c; tree.packge.package_info = c;
} }
classEnter(tree.defs, topEnv); classEnter(tree.defs, topEnv);
...@@ -393,7 +395,7 @@ public class Enter extends JCTree.Visitor { ...@@ -393,7 +395,7 @@ public class Enter extends JCTree.Visitor {
c.completer = memberEnter; c.completer = memberEnter;
c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree); c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree);
c.sourcefile = env.toplevel.sourcefile; c.sourcefile = env.toplevel.sourcefile;
c.members_field = new Scope(c); c.members_field = new Scope.ClassScope(c, scopeCounter);
ClassType ct = (ClassType)c.type; ClassType ct = (ClassType)c.type;
if (owner.kind != PCK && (c.flags_field & STATIC) == 0) { if (owner.kind != PCK && (c.flags_field & STATIC) == 0) {
......
...@@ -80,25 +80,12 @@ public class Infer { ...@@ -80,25 +80,12 @@ public class Infer {
} }
public static class InferenceException extends RuntimeException { public static class InferenceException extends Resolve.InapplicableMethodException {
private static final long serialVersionUID = 0; private static final long serialVersionUID = 0;
JCDiagnostic diagnostic;
JCDiagnostic.Factory diags;
InferenceException(JCDiagnostic.Factory diags) { InferenceException(JCDiagnostic.Factory diags) {
this.diagnostic = null; super(diags);
this.diags = diags;
}
InferenceException setMessage(String key, Object... args) {
this.diagnostic = diags.fragment(key, args);
return this;
} }
public JCDiagnostic getDiagnostic() {
return diagnostic;
}
} }
public static class NoInstanceException extends InferenceException { public static class NoInstanceException extends InferenceException {
...@@ -320,7 +307,7 @@ public class Infer { ...@@ -320,7 +307,7 @@ public class Infer {
Type qtype1 = types.subst(that.qtype, that.tvars, undetvars); Type qtype1 = types.subst(that.qtype, that.tvars, undetvars);
if (!types.isSubtype(qtype1, to)) { if (!types.isSubtype(qtype1, to)) {
throw unambiguousNoInstanceException throw unambiguousNoInstanceException
.setMessage("no.conforming.instance.exists", .setMessage("infer.no.conforming.instance.exists",
that.tvars, that.qtype, to); that.tvars, that.qtype, to);
} }
for (List<Type> l = undetvars; l.nonEmpty(); l = l.tail) for (List<Type> l = undetvars; l.nonEmpty(); l = l.tail)
...@@ -378,6 +365,11 @@ public class Infer { ...@@ -378,6 +365,11 @@ public class Infer {
// instantiate all polymorphic argument types and // instantiate all polymorphic argument types and
// set up lower bounds constraints for undetvars // set up lower bounds constraints for undetvars
Type varargsFormal = useVarargs ? formals.last() : null; Type varargsFormal = useVarargs ? formals.last() : null;
if (varargsFormal == null &&
actuals.size() != formals.size()) {
throw unambiguousNoInstanceException
.setMessage("infer.arg.length.mismatch");
}
while (actuals.nonEmpty() && formals.head != varargsFormal) { while (actuals.nonEmpty() && formals.head != varargsFormal) {
Type formal = formals.head; Type formal = formals.head;
Type actual = actuals.head.baseType(); Type actual = actuals.head.baseType();
...@@ -390,19 +382,16 @@ public class Infer { ...@@ -390,19 +382,16 @@ public class Infer {
: types.isSubtypeUnchecked(actual, undetFormal, warn); : types.isSubtypeUnchecked(actual, undetFormal, warn);
if (!works) { if (!works) {
throw unambiguousNoInstanceException throw unambiguousNoInstanceException
.setMessage("no.conforming.assignment.exists", .setMessage("infer.no.conforming.assignment.exists",
tvars, actualNoCapture, formal); tvars, actualNoCapture, formal);
} }
formals = formals.tail; formals = formals.tail;
actuals = actuals.tail; actuals = actuals.tail;
actualsNoCapture = actualsNoCapture.tail; actualsNoCapture = actualsNoCapture.tail;
} }
if (formals.head != varargsFormal || // not enough args
!useVarargs && actuals.nonEmpty()) { // too many args if (formals.head != varargsFormal) // not enough args
// argument lists differ in length throw unambiguousNoInstanceException.setMessage("infer.arg.length.mismatch");
throw unambiguousNoInstanceException
.setMessage("arg.length.mismatch");
}
// for varargs arguments as well // for varargs arguments as well
if (useVarargs) { if (useVarargs) {
...@@ -416,7 +405,7 @@ public class Infer { ...@@ -416,7 +405,7 @@ public class Infer {
boolean works = types.isConvertible(actual, elemUndet, warn); boolean works = types.isConvertible(actual, elemUndet, warn);
if (!works) { if (!works) {
throw unambiguousNoInstanceException throw unambiguousNoInstanceException
.setMessage("no.conforming.assignment.exists", .setMessage("infer.no.conforming.assignment.exists",
tvars, actualNoCapture, elemType); tvars, actualNoCapture, elemType);
} }
actuals = actuals.tail; actuals = actuals.tail;
......
...@@ -68,6 +68,7 @@ public class Lower extends TreeTranslator { ...@@ -68,6 +68,7 @@ public class Lower extends TreeTranslator {
private Names names; private Names names;
private Log log; private Log log;
private Symtab syms; private Symtab syms;
private Scope.ScopeCounter scopeCounter;
private Resolve rs; private Resolve rs;
private Check chk; private Check chk;
private Attr attr; private Attr attr;
...@@ -90,6 +91,7 @@ public class Lower extends TreeTranslator { ...@@ -90,6 +91,7 @@ public class Lower extends TreeTranslator {
names = Names.instance(context); names = Names.instance(context);
log = Log.instance(context); log = Log.instance(context);
syms = Symtab.instance(context); syms = Symtab.instance(context);
scopeCounter = Scope.ScopeCounter.instance(context);
rs = Resolve.instance(context); rs = Resolve.instance(context);
chk = Check.instance(context); chk = Check.instance(context);
attr = Attr.instance(context); attr = Attr.instance(context);
...@@ -107,7 +109,7 @@ public class Lower extends TreeTranslator { ...@@ -107,7 +109,7 @@ public class Lower extends TreeTranslator {
types = Types.instance(context); types = Types.instance(context);
Options options = Options.instance(context); Options options = Options.instance(context);
debugLower = options.get("debuglower") != null; debugLower = options.isSet("debuglower");
pkginfoOpt = PkgInfo.get(options); pkginfoOpt = PkgInfo.get(options);
} }
...@@ -569,7 +571,7 @@ public class Lower extends TreeTranslator { ...@@ -569,7 +571,7 @@ public class Lower extends TreeTranslator {
c.flatname = chk.localClassName(c); c.flatname = chk.localClassName(c);
c.sourcefile = owner.sourcefile; c.sourcefile = owner.sourcefile;
c.completer = null; c.completer = null;
c.members_field = new Scope(c); c.members_field = new Scope.ClassScope(c, scopeCounter);
c.flags_field = flags; c.flags_field = flags;
ClassType ctype = (ClassType) c.type; ClassType ctype = (ClassType) c.type;
ctype.supertype_field = syms.objectType; ctype.supertype_field = syms.objectType;
...@@ -2677,7 +2679,8 @@ public class Lower extends TreeTranslator { ...@@ -2677,7 +2679,8 @@ public class Lower extends TreeTranslator {
} }
//where //where
private JCTree convert(JCTree tree, Type pt) { private JCTree convert(JCTree tree, Type pt) {
if (tree.type == pt) return tree; if (tree.type == pt || tree.type.tag == TypeTags.BOT)
return tree;
JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree); JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt) result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
: pt; : pt;
......
...@@ -67,6 +67,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer { ...@@ -67,6 +67,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer {
private final Check chk; private final Check chk;
private final Attr attr; private final Attr attr;
private final Symtab syms; private final Symtab syms;
private final Scope.ScopeCounter scopeCounter;
private final TreeMaker make; private final TreeMaker make;
private final ClassReader reader; private final ClassReader reader;
private final Todo todo; private final Todo todo;
...@@ -92,6 +93,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer { ...@@ -92,6 +93,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer {
chk = Check.instance(context); chk = Check.instance(context);
attr = Attr.instance(context); attr = Attr.instance(context);
syms = Symtab.instance(context); syms = Symtab.instance(context);
scopeCounter = Scope.ScopeCounter.instance(context);
make = TreeMaker.instance(context); make = TreeMaker.instance(context);
reader = ClassReader.instance(context); reader = ClassReader.instance(context);
todo = Todo.instance(context); todo = Todo.instance(context);
...@@ -100,7 +102,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer { ...@@ -100,7 +102,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer {
diags = JCDiagnostic.Factory.instance(context); diags = JCDiagnostic.Factory.instance(context);
target = Target.instance(context); target = Target.instance(context);
Options options = Options.instance(context); Options options = Options.instance(context);
skipAnnotations = options.get("skipAnnotations") != null; skipAnnotations = options.isSet("skipAnnotations");
} }
/** A queue for classes whose members still need to be entered into the /** A queue for classes whose members still need to be entered into the
...@@ -925,7 +927,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer { ...@@ -925,7 +927,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer {
tp.accept(new TypeAnnotate(baseEnv)); tp.accept(new TypeAnnotate(baseEnv));
tree.accept(new TypeAnnotate(env)); tree.accept(new TypeAnnotate(env));
chk.checkNonCyclic(tree.pos(), c.type); chk.checkNonCyclicDecl(tree);
attr.attribTypeVariables(tree.typarams, baseEnv); attr.attribTypeVariables(tree.typarams, baseEnv);
...@@ -1087,7 +1089,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer { ...@@ -1087,7 +1089,7 @@ public class MemberEnter extends JCTree.Visitor implements Completer {
private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) { private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
Scope baseScope = new Scope(tree.sym); Scope baseScope = new Scope.ClassScope(tree.sym, scopeCounter);
//import already entered local classes into base scope //import already entered local classes into base scope
for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) { for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
if (e.sym.isLocal()) { if (e.sym.isLocal()) {
......
...@@ -110,15 +110,17 @@ public class Resolve { ...@@ -110,15 +110,17 @@ public class Resolve {
boxingEnabled = source.allowBoxing(); boxingEnabled = source.allowBoxing();
varargsEnabled = source.allowVarargs(); varargsEnabled = source.allowVarargs();
Options options = Options.instance(context); Options options = Options.instance(context);
debugResolve = options.get("debugresolve") != null; debugResolve = options.isSet("debugresolve");
allowTransitionalJSR292 = options.get("allowTransitionalJSR292") != null; allowTransitionalJSR292 = options.isSet("allowTransitionalJSR292");
Target target = Target.instance(context); Target target = Target.instance(context);
allowMethodHandles = allowTransitionalJSR292 || allowMethodHandles = allowTransitionalJSR292 ||
target.hasMethodHandles(); target.hasMethodHandles();
allowInvokeDynamic = (allowTransitionalJSR292 || allowInvokeDynamic = (allowTransitionalJSR292 ||
target.hasInvokedynamic()) && target.hasInvokedynamic()) &&
options.get("invokedynamic") != null; options.isSet("invokedynamic");
polymorphicSignatureScope = new Scope(syms.noSymbol); polymorphicSignatureScope = new Scope(syms.noSymbol);
inapplicableMethodException = new InapplicableMethodException(diags);
} }
/** error symbols, which are returned when resolution fails /** error symbols, which are returned when resolution fails
...@@ -318,7 +320,8 @@ public class Resolve { ...@@ -318,7 +320,8 @@ public class Resolve {
throws Infer.InferenceException { throws Infer.InferenceException {
boolean polymorphicSignature = (m.isPolymorphicSignatureGeneric() && allowMethodHandles) || boolean polymorphicSignature = (m.isPolymorphicSignatureGeneric() && allowMethodHandles) ||
isTransitionalDynamicCallSite(site, m); isTransitionalDynamicCallSite(site, m);
if (useVarargs && (m.flags() & VARARGS) == 0) return null; if (useVarargs && (m.flags() & VARARGS) == 0)
throw inapplicableMethodException.setMessage(null);
Type mt = types.memberType(site, m); Type mt = types.memberType(site, m);
// tvars is the list of formal type variables for which type arguments // tvars is the list of formal type variables for which type arguments
...@@ -334,7 +337,7 @@ public class Resolve { ...@@ -334,7 +337,7 @@ public class Resolve {
} else if (mt.tag == FORALL && typeargtypes.nonEmpty()) { } else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
ForAll pmt = (ForAll) mt; ForAll pmt = (ForAll) mt;
if (typeargtypes.length() != pmt.tvars.length()) if (typeargtypes.length() != pmt.tvars.length())
return null; throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
// Check type arguments are within bounds // Check type arguments are within bounds
List<Type> formals = pmt.tvars; List<Type> formals = pmt.tvars;
List<Type> actuals = typeargtypes; List<Type> actuals = typeargtypes;
...@@ -343,7 +346,7 @@ public class Resolve { ...@@ -343,7 +346,7 @@ public class Resolve {
pmt.tvars, typeargtypes); pmt.tvars, typeargtypes);
for (; bounds.nonEmpty(); bounds = bounds.tail) for (; bounds.nonEmpty(); bounds = bounds.tail)
if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn)) if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
return null; throw inapplicableMethodException.setMessage("explicit.param.do.not.conform.to.bounds",actuals.head, bounds);
formals = formals.tail; formals = formals.tail;
actuals = actuals.tail; actuals = actuals.tail;
} }
...@@ -375,11 +378,10 @@ public class Resolve { ...@@ -375,11 +378,10 @@ public class Resolve {
allowBoxing, allowBoxing,
useVarargs, useVarargs,
warn); warn);
return
argumentsAcceptable(argtypes, mt.getParameterTypes(), checkRawArgumentsAcceptable(argtypes, mt.getParameterTypes(),
allowBoxing, useVarargs, warn) allowBoxing, useVarargs, warn);
? mt return mt;
: null;
} }
boolean isTransitionalDynamicCallSite(Type site, Symbol sym) { boolean isTransitionalDynamicCallSite(Type site, Symbol sym) {
...@@ -403,7 +405,7 @@ public class Resolve { ...@@ -403,7 +405,7 @@ public class Resolve {
try { try {
return rawInstantiate(env, site, m, argtypes, typeargtypes, return rawInstantiate(env, site, m, argtypes, typeargtypes,
allowBoxing, useVarargs, warn); allowBoxing, useVarargs, warn);
} catch (Infer.InferenceException ex) { } catch (InapplicableMethodException ex) {
return null; return null;
} }
} }
...@@ -415,26 +417,76 @@ public class Resolve { ...@@ -415,26 +417,76 @@ public class Resolve {
boolean allowBoxing, boolean allowBoxing,
boolean useVarargs, boolean useVarargs,
Warner warn) { Warner warn) {
try {
checkRawArgumentsAcceptable(argtypes, formals, allowBoxing, useVarargs, warn);
return true;
} catch (InapplicableMethodException ex) {
return false;
}
}
void checkRawArgumentsAcceptable(List<Type> argtypes,
List<Type> formals,
boolean allowBoxing,
boolean useVarargs,
Warner warn) {
Type varargsFormal = useVarargs ? formals.last() : null; Type varargsFormal = useVarargs ? formals.last() : null;
if (varargsFormal == null &&
argtypes.size() != formals.size()) {
throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
}
while (argtypes.nonEmpty() && formals.head != varargsFormal) { while (argtypes.nonEmpty() && formals.head != varargsFormal) {
boolean works = allowBoxing boolean works = allowBoxing
? types.isConvertible(argtypes.head, formals.head, warn) ? types.isConvertible(argtypes.head, formals.head, warn)
: types.isSubtypeUnchecked(argtypes.head, formals.head, warn); : types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
if (!works) return false; if (!works)
throw inapplicableMethodException.setMessage("no.conforming.assignment.exists",
argtypes.head,
formals.head);
argtypes = argtypes.tail; argtypes = argtypes.tail;
formals = formals.tail; formals = formals.tail;
} }
if (formals.head != varargsFormal) return false; // not enough args
if (!useVarargs) if (formals.head != varargsFormal)
return argtypes.isEmpty(); throw inapplicableMethodException.setMessage("arg.length.mismatch"); // not enough args
Type elt = types.elemtype(varargsFormal);
while (argtypes.nonEmpty()) { if (useVarargs) {
if (!types.isConvertible(argtypes.head, elt, warn)) Type elt = types.elemtype(varargsFormal);
return false; while (argtypes.nonEmpty()) {
argtypes = argtypes.tail; if (!types.isConvertible(argtypes.head, elt, warn))
throw inapplicableMethodException.setMessage("varargs.argument.mismatch",
argtypes.head,
elt);
argtypes = argtypes.tail;
}
} }
return true; return;
} }
// where
public static class InapplicableMethodException extends RuntimeException {
private static final long serialVersionUID = 0;
JCDiagnostic diagnostic;
JCDiagnostic.Factory diags;
InapplicableMethodException(JCDiagnostic.Factory diags) {
this.diagnostic = null;
this.diags = diags;
}
InapplicableMethodException setMessage(String key) {
this.diagnostic = key != null ? diags.fragment(key) : null;
return this;
}
InapplicableMethodException setMessage(String key, Object... args) {
this.diagnostic = key != null ? diags.fragment(key, args) : null;
return this;
}
public JCDiagnostic getDiagnostic() {
return diagnostic;
}
}
private final InapplicableMethodException inapplicableMethodException;
/* *************************************************************************** /* ***************************************************************************
* Symbol lookup * Symbol lookup
...@@ -595,6 +647,7 @@ public class Resolve { ...@@ -595,6 +647,7 @@ public class Resolve {
* @param allowBoxing Allow boxing conversions of arguments. * @param allowBoxing Allow boxing conversions of arguments.
* @param useVarargs Box trailing arguments into an array for varargs. * @param useVarargs Box trailing arguments into an array for varargs.
*/ */
@SuppressWarnings("fallthrough")
Symbol selectBest(Env<AttrContext> env, Symbol selectBest(Env<AttrContext> env,
Type site, Type site,
List<Type> argtypes, List<Type> argtypes,
...@@ -608,21 +661,16 @@ public class Resolve { ...@@ -608,21 +661,16 @@ public class Resolve {
if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar; if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
assert sym.kind < AMBIGUOUS; assert sym.kind < AMBIGUOUS;
try { try {
if (rawInstantiate(env, site, sym, argtypes, typeargtypes, rawInstantiate(env, site, sym, argtypes, typeargtypes,
allowBoxing, useVarargs, Warner.noWarnings) == null) { allowBoxing, useVarargs, Warner.noWarnings);
// inapplicable } catch (InapplicableMethodException ex) {
switch (bestSoFar.kind) {
case ABSENT_MTH: return wrongMethod.setWrongSym(sym);
case WRONG_MTH: return wrongMethods;
default: return bestSoFar;
}
}
} catch (Infer.InferenceException ex) {
switch (bestSoFar.kind) { switch (bestSoFar.kind) {
case ABSENT_MTH: case ABSENT_MTH:
return wrongMethod.setWrongSym(sym, ex.getDiagnostic()); return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
case WRONG_MTH: case WRONG_MTH:
return wrongMethods; wrongMethods.addCandidate(currentStep, wrongMethod.sym, wrongMethod.explanation);
case WRONG_MTHS:
return wrongMethods.addCandidate(currentStep, sym, ex.getDiagnostic());
default: default:
return bestSoFar; return bestSoFar;
} }
...@@ -631,7 +679,7 @@ public class Resolve { ...@@ -631,7 +679,7 @@ public class Resolve {
return (bestSoFar.kind == ABSENT_MTH) return (bestSoFar.kind == ABSENT_MTH)
? new AccessError(env, site, sym) ? new AccessError(env, site, sym)
: bestSoFar; : bestSoFar;
} }
return (bestSoFar.kind > AMBIGUOUS) return (bestSoFar.kind > AMBIGUOUS)
? sym ? sym
: mostSpecific(sym, bestSoFar, env, site, : mostSpecific(sym, bestSoFar, env, site,
...@@ -1253,11 +1301,12 @@ public class Resolve { ...@@ -1253,11 +1301,12 @@ public class Resolve {
Name name, Name name,
List<Type> argtypes, List<Type> argtypes,
List<Type> typeargtypes) { List<Type> typeargtypes) {
Symbol sym = methodNotFound; Symbol sym = startResolution();
List<MethodResolutionPhase> steps = methodResolutionSteps; List<MethodResolutionPhase> steps = methodResolutionSteps;
while (steps.nonEmpty() && while (steps.nonEmpty() &&
steps.head.isApplicable(boxingEnabled, varargsEnabled) && steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
sym.kind >= ERRONEOUS) { sym.kind >= ERRONEOUS) {
currentStep = steps.head;
sym = findFun(env, name, argtypes, typeargtypes, sym = findFun(env, name, argtypes, typeargtypes,
steps.head.isBoxingRequired, steps.head.isBoxingRequired,
env.info.varArgs = steps.head.isVarargsRequired); env.info.varArgs = steps.head.isVarargsRequired);
...@@ -1274,6 +1323,12 @@ public class Resolve { ...@@ -1274,6 +1323,12 @@ public class Resolve {
return sym; return sym;
} }
private Symbol startResolution() {
wrongMethod.clear();
wrongMethods.clear();
return methodNotFound;
}
/** Resolve a qualified method identifier /** Resolve a qualified method identifier
* @param pos The position to use for error reporting. * @param pos The position to use for error reporting.
* @param env The environment current at the method invocation. * @param env The environment current at the method invocation.
...@@ -1286,11 +1341,12 @@ public class Resolve { ...@@ -1286,11 +1341,12 @@ public class Resolve {
Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env, Symbol resolveQualifiedMethod(DiagnosticPosition pos, Env<AttrContext> env,
Type site, Name name, List<Type> argtypes, Type site, Name name, List<Type> argtypes,
List<Type> typeargtypes) { List<Type> typeargtypes) {
Symbol sym = methodNotFound; Symbol sym = startResolution();
List<MethodResolutionPhase> steps = methodResolutionSteps; List<MethodResolutionPhase> steps = methodResolutionSteps;
while (steps.nonEmpty() && while (steps.nonEmpty() &&
steps.head.isApplicable(boxingEnabled, varargsEnabled) && steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
sym.kind >= ERRONEOUS) { sym.kind >= ERRONEOUS) {
currentStep = steps.head;
sym = findMethod(env, site, name, argtypes, typeargtypes, sym = findMethod(env, site, name, argtypes, typeargtypes,
steps.head.isBoxingRequired(), steps.head.isBoxingRequired(),
env.info.varArgs = steps.head.isVarargsRequired(), false); env.info.varArgs = steps.head.isVarargsRequired(), false);
...@@ -1404,11 +1460,12 @@ public class Resolve { ...@@ -1404,11 +1460,12 @@ public class Resolve {
Type site, Type site,
List<Type> argtypes, List<Type> argtypes,
List<Type> typeargtypes) { List<Type> typeargtypes) {
Symbol sym = methodNotFound; Symbol sym = startResolution();
List<MethodResolutionPhase> steps = methodResolutionSteps; List<MethodResolutionPhase> steps = methodResolutionSteps;
while (steps.nonEmpty() && while (steps.nonEmpty() &&
steps.head.isApplicable(boxingEnabled, varargsEnabled) && steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
sym.kind >= ERRONEOUS) { sym.kind >= ERRONEOUS) {
currentStep = steps.head;
sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
steps.head.isBoxingRequired(), steps.head.isBoxingRequired(),
env.info.varArgs = steps.head.isVarargsRequired()); env.info.varArgs = steps.head.isVarargsRequired());
...@@ -1439,26 +1496,22 @@ public class Resolve { ...@@ -1439,26 +1496,22 @@ public class Resolve {
Type site, Type site,
List<Type> argtypes, List<Type> argtypes,
List<Type> typeargtypes) { List<Type> typeargtypes) {
Symbol sym = methodNotFound; Symbol sym = startResolution();
JCDiagnostic explanation = null;
List<MethodResolutionPhase> steps = methodResolutionSteps; List<MethodResolutionPhase> steps = methodResolutionSteps;
while (steps.nonEmpty() && while (steps.nonEmpty() &&
steps.head.isApplicable(boxingEnabled, varargsEnabled) && steps.head.isApplicable(boxingEnabled, varargsEnabled) &&
sym.kind >= ERRONEOUS) { sym.kind >= ERRONEOUS) {
currentStep = steps.head;
sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, sym = resolveConstructor(pos, env, site, argtypes, typeargtypes,
steps.head.isBoxingRequired(), steps.head.isBoxingRequired(),
env.info.varArgs = steps.head.isVarargsRequired()); env.info.varArgs = steps.head.isVarargsRequired());
methodResolutionCache.put(steps.head, sym); methodResolutionCache.put(steps.head, sym);
if (sym.kind == WRONG_MTH &&
((InapplicableSymbolError)sym).explanation != null) {
//if the symbol is an inapplicable method symbol, then the
//explanation contains the reason for which inference failed
explanation = ((InapplicableSymbolError)sym).explanation;
}
steps = steps.tail; steps = steps.tail;
} }
if (sym.kind >= AMBIGUOUS) { if (sym.kind >= AMBIGUOUS) {
final JCDiagnostic details = explanation; final JCDiagnostic details = sym.kind == WRONG_MTH ?
((InapplicableSymbolError)sym).explanation :
null;
Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") { Symbol errSym = new ResolveError(WRONG_MTH, "diamond error") {
@Override @Override
JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) { JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
...@@ -1860,7 +1913,8 @@ public class Resolve { ...@@ -1860,7 +1913,8 @@ public class Resolve {
*/ */
InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) { InapplicableSymbolError setWrongSym(Symbol sym, JCDiagnostic explanation) {
this.sym = sym; this.sym = sym;
this.explanation = explanation; if (this.sym == sym && explanation != null)
this.explanation = explanation; //update the details
return this; return this;
} }
...@@ -1868,7 +1922,6 @@ public class Resolve { ...@@ -1868,7 +1922,6 @@ public class Resolve {
*/ */
InapplicableSymbolError setWrongSym(Symbol sym) { InapplicableSymbolError setWrongSym(Symbol sym) {
this.sym = sym; this.sym = sym;
this.explanation = null;
return this; return this;
} }
...@@ -1905,6 +1958,10 @@ public class Resolve { ...@@ -1905,6 +1958,10 @@ public class Resolve {
} }
} }
void clear() {
explanation = null;
}
@Override @Override
public Symbol access(Name name, TypeSymbol location) { public Symbol access(Name name, TypeSymbol location) {
return types.createErrorType(name, location, syms.errSymbol.type).tsym; return types.createErrorType(name, location, syms.errSymbol.type).tsym;
...@@ -1917,6 +1974,9 @@ public class Resolve { ...@@ -1917,6 +1974,9 @@ public class Resolve {
* given an actual arguments/type argument list. * given an actual arguments/type argument list.
*/ */
class InapplicableSymbolsError extends ResolveError { class InapplicableSymbolsError extends ResolveError {
private List<Candidate> candidates = List.nil();
InapplicableSymbolsError(Symbol sym) { InapplicableSymbolsError(Symbol sym) {
super(WRONG_MTHS, "inapplicable symbols"); super(WRONG_MTHS, "inapplicable symbols");
} }
...@@ -1928,8 +1988,85 @@ public class Resolve { ...@@ -1928,8 +1988,85 @@ public class Resolve {
Name name, Name name,
List<Type> argtypes, List<Type> argtypes,
List<Type> typeargtypes) { List<Type> typeargtypes) {
return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos, if (candidates.nonEmpty()) {
JCDiagnostic err = diags.create(dkind,
log.currentSource(),
pos,
"cant.apply.symbols",
name == names.init ? KindName.CONSTRUCTOR : absentKind(kind),
getName(),
argtypes);
return new JCDiagnostic.MultilineDiagnostic(err, candidateDetails(site));
} else {
return new SymbolNotFoundError(ABSENT_MTH).getDiagnostic(dkind, pos,
site, name, argtypes, typeargtypes); site, name, argtypes, typeargtypes);
}
}
//where
List<JCDiagnostic> candidateDetails(Type site) {
List<JCDiagnostic> details = List.nil();
for (Candidate c : candidates)
details = details.prepend(c.getDiagnostic(site));
return details.reverse();
}
Symbol addCandidate(MethodResolutionPhase currentStep, Symbol sym, JCDiagnostic details) {
Candidate c = new Candidate(currentStep, sym, details);
if (c.isValid() && !candidates.contains(c))
candidates = candidates.append(c);
return this;
}
void clear() {
candidates = List.nil();
}
private Name getName() {
Symbol sym = candidates.head.sym;
return sym.name == names.init ?
sym.owner.name :
sym.name;
}
private class Candidate {
final MethodResolutionPhase step;
final Symbol sym;
final JCDiagnostic details;
private Candidate(MethodResolutionPhase step, Symbol sym, JCDiagnostic details) {
this.step = step;
this.sym = sym;
this.details = details;
}
JCDiagnostic getDiagnostic(Type site) {
return diags.fragment("inapplicable.method",
Kinds.kindName(sym),
sym.location(site, types),
sym.asMemberOf(site, types),
details);
}
@Override
public boolean equals(Object o) {
if (o instanceof Candidate) {
Symbol s1 = this.sym;
Symbol s2 = ((Candidate)o).sym;
if ((s1 != s2 &&
(s1.overrides(s2, s1.owner.type.tsym, types, false) ||
(s2.overrides(s1, s2.owner.type.tsym, types, false)))) ||
((s1.isConstructor() || s2.isConstructor()) && s1.owner != s2.owner))
return true;
}
return false;
}
boolean isValid() {
return (((sym.flags() & VARARGS) != 0 && step == VARARITY) ||
(sym.flags() & VARARGS) == 0 && step == (boxingEnabled ? BOX : BASIC));
}
} }
} }
...@@ -2093,6 +2230,8 @@ public class Resolve { ...@@ -2093,6 +2230,8 @@ public class Resolve {
final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY); final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
private MethodResolutionPhase currentStep = null;
private MethodResolutionPhase firstErroneousResolutionPhase() { private MethodResolutionPhase firstErroneousResolutionPhase() {
MethodResolutionPhase bestSoFar = BASIC; MethodResolutionPhase bestSoFar = BASIC;
Symbol sym = methodNotFound; Symbol sym = methodNotFound;
......
/* /*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -150,8 +150,8 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -150,8 +150,8 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
useZipFileIndex = System.getProperty("useJavaUtilZip") == null;// TODO: options.get("useJavaUtilZip") == null; useZipFileIndex = System.getProperty("useJavaUtilZip") == null;// TODO: options.get("useJavaUtilZip") == null;
mmappedIO = options.get("mmappedIO") != null; mmappedIO = options.isSet("mmappedIO");
ignoreSymbolFile = options.get("ignore.symbol.file") != null; ignoreSymbolFile = options.isSet("ignore.symbol.file");
} }
public JavaFileObject getFileForInput(String name) { public JavaFileObject getFileForInput(String name) {
...@@ -435,7 +435,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -435,7 +435,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
zdir = new ZipFile(zipFileName); zdir = new ZipFile(zipFileName);
} }
else { else {
usePreindexedCache = options.get("usezipindex") != null; usePreindexedCache = options.isSet("usezipindex");
preindexCacheLocation = options.get("java.io.tmpdir"); preindexCacheLocation = options.get("java.io.tmpdir");
String optCacheLoc = options.get("cachezipindexdir"); String optCacheLoc = options.get("cachezipindexdir");
...@@ -469,7 +469,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -469,7 +469,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
null, null,
usePreindexedCache, usePreindexedCache,
preindexCacheLocation, preindexCacheLocation,
options.get("writezipindexfiles") != null)); options.isSet("writezipindexfiles")));
} }
} }
else { else {
...@@ -482,7 +482,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -482,7 +482,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
symbolFilePrefix, symbolFilePrefix,
usePreindexedCache, usePreindexedCache,
preindexCacheLocation, preindexCacheLocation,
options.get("writezipindexfiles") != null)); options.isSet("writezipindexfiles")));
} }
} }
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
...@@ -605,7 +605,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -605,7 +605,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
nullCheck(className); nullCheck(className);
nullCheck(kind); nullCheck(kind);
if (!sourceOrClass.contains(kind)) if (!sourceOrClass.contains(kind))
throw new IllegalArgumentException("Invalid kind " + kind); throw new IllegalArgumentException("Invalid kind: " + kind);
return getFileForInput(location, RelativeFile.forClass(className, kind)); return getFileForInput(location, RelativeFile.forClass(className, kind));
} }
...@@ -658,7 +658,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -658,7 +658,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
nullCheck(className); nullCheck(className);
nullCheck(kind); nullCheck(kind);
if (!sourceOrClass.contains(kind)) if (!sourceOrClass.contains(kind))
throw new IllegalArgumentException("Invalid kind " + kind); throw new IllegalArgumentException("Invalid kind: " + kind);
return getFileForOutput(location, RelativeFile.forClass(className, kind), sibling); return getFileForOutput(location, RelativeFile.forClass(className, kind), sibling);
} }
...@@ -672,7 +672,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -672,7 +672,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
// validatePackageName(packageName); // validatePackageName(packageName);
nullCheck(packageName); nullCheck(packageName);
if (!isRelativeUri(relativeName)) if (!isRelativeUri(relativeName))
throw new IllegalArgumentException("relativeName is invalid"); throw new IllegalArgumentException("Invalid relative name: " + relativeName);
RelativeFile name = packageName.length() == 0 RelativeFile name = packageName.length() == 0
? new RelativeFile(relativeName) ? new RelativeFile(relativeName)
: new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName); : new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
...@@ -806,6 +806,8 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil ...@@ -806,6 +806,8 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
String path = uri.normalize().getPath(); String path = uri.normalize().getPath();
if (path.length() == 0 /* isEmpty() is mustang API */) if (path.length() == 0 /* isEmpty() is mustang API */)
return false; return false;
if (!path.equals(uri.getPath())) // implicitly checks for embedded . and ..
return false;
char first = path.charAt(0); char first = path.charAt(0);
return first != '.' && first != '/'; return first != '.' && first != '/';
} }
......
...@@ -56,6 +56,8 @@ import static com.sun.tools.javac.code.TypeTags.*; ...@@ -56,6 +56,8 @@ import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.jvm.ClassFile.*; import static com.sun.tools.javac.jvm.ClassFile.*;
import static com.sun.tools.javac.jvm.ClassFile.Version.*; import static com.sun.tools.javac.jvm.ClassFile.Version.*;
import static com.sun.tools.javac.main.OptionName.*;
/** This class provides operations to read a classfile into an internal /** This class provides operations to read a classfile into an internal
* representation. The internal representation is anchored in a * representation. The internal representation is anchored in a
* ClassSymbol which contains in its scope symbol representations * ClassSymbol which contains in its scope symbol representations
...@@ -122,6 +124,9 @@ public class ClassReader implements Completer { ...@@ -122,6 +124,9 @@ public class ClassReader implements Completer {
/** The symbol table. */ /** The symbol table. */
Symtab syms; Symtab syms;
/** The scope counter */
Scope.ScopeCounter scopeCounter;
Types types; Types types;
/** The name table. */ /** The name table. */
...@@ -244,6 +249,7 @@ public class ClassReader implements Completer { ...@@ -244,6 +249,7 @@ public class ClassReader implements Completer {
names = Names.instance(context); names = Names.instance(context);
syms = Symtab.instance(context); syms = Symtab.instance(context);
scopeCounter = Scope.ScopeCounter.instance(context);
types = Types.instance(context); types = Types.instance(context);
fileManager = context.get(JavaFileManager.class); fileManager = context.get(JavaFileManager.class);
if (fileManager == null) if (fileManager == null)
...@@ -255,23 +261,23 @@ public class ClassReader implements Completer { ...@@ -255,23 +261,23 @@ public class ClassReader implements Completer {
Options options = Options.instance(context); Options options = Options.instance(context);
annotate = Annotate.instance(context); annotate = Annotate.instance(context);
verbose = options.get("-verbose") != null; verbose = options.isSet(VERBOSE);
checkClassFile = options.get("-checkclassfile") != null; checkClassFile = options.isSet("-checkclassfile");
Source source = Source.instance(context); Source source = Source.instance(context);
allowGenerics = source.allowGenerics(); allowGenerics = source.allowGenerics();
allowVarargs = source.allowVarargs(); allowVarargs = source.allowVarargs();
allowAnnotations = source.allowAnnotations(); allowAnnotations = source.allowAnnotations();
saveParameterNames = options.get("save-parameter-names") != null; saveParameterNames = options.isSet("save-parameter-names");
cacheCompletionFailure = options.get("dev") == null; cacheCompletionFailure = options.isUnset("dev");
preferSource = "source".equals(options.get("-Xprefer")); preferSource = "source".equals(options.get("-Xprefer"));
completionFailureName = completionFailureName =
(options.get("failcomplete") != null) options.isSet("failcomplete")
? names.fromString(options.get("failcomplete")) ? names.fromString(options.get("failcomplete"))
: null; : null;
typevars = new Scope(syms.noSymbol); typevars = new Scope(syms.noSymbol);
debugJSR308 = options.get("TA:reader") != null; debugJSR308 = options.isSet("TA:reader");
initAttributeReaders(); initAttributeReaders();
} }
...@@ -1984,7 +1990,7 @@ public class ClassReader implements Completer { ...@@ -1984,7 +1990,7 @@ public class ClassReader implements Completer {
ClassType ct = (ClassType)c.type; ClassType ct = (ClassType)c.type;
// allocate scope for members // allocate scope for members
c.members_field = new Scope(c); c.members_field = new Scope.ClassScope(c, scopeCounter);
// prepare type variable table // prepare type variable table
typevars = typevars.dup(currentOwner); typevars = typevars.dup(currentOwner);
......
...@@ -45,8 +45,10 @@ import static com.sun.tools.javac.code.Flags.*; ...@@ -45,8 +45,10 @@ import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*; import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*; import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.jvm.UninitializedType.*; import static com.sun.tools.javac.jvm.UninitializedType.*;
import static com.sun.tools.javac.main.OptionName.*;
import static javax.tools.StandardLocation.CLASS_OUTPUT; import static javax.tools.StandardLocation.CLASS_OUTPUT;
/** This class provides operations to map an internal symbol table graph /** This class provides operations to map an internal symbol table graph
* rooted in a ClassSymbol into a classfile. * rooted in a ClassSymbol into a classfile.
* *
...@@ -178,15 +180,16 @@ public class ClassWriter extends ClassFile { ...@@ -178,15 +180,16 @@ public class ClassWriter extends ClassFile {
types = Types.instance(context); types = Types.instance(context);
fileManager = context.get(JavaFileManager.class); fileManager = context.get(JavaFileManager.class);
debugJSR308 = options.get("TA:writer") != null; debugJSR308 = options.isSet("TA:writer");
verbose = options.get("-verbose") != null; verbose = options.isSet(VERBOSE);
scramble = options.get("-scramble") != null; scramble = options.isSet("-scramble");
scrambleAll = options.get("-scrambleAll") != null; scrambleAll = options.isSet("-scrambleAll");
retrofit = options.get("-retrofit") != null; retrofit = options.isSet("-retrofit");
genCrt = options.get("-Xjcov") != null; genCrt = options.isSet(XJCOV);
debugstackmap = options.get("debugstackmap") != null; debugstackmap = options.isSet("debugstackmap");
emitSourceFile = options.get("-g:")==null || options.get("-g:source")!=null; emitSourceFile = options.isUnset(G_CUSTOM) ||
options.isSet(G_CUSTOM, "source");
String dumpModFlags = options.get("dumpmodifiers"); String dumpModFlags = options.get("dumpmodifiers");
dumpClassModifiers = dumpClassModifiers =
......
...@@ -46,6 +46,7 @@ import static com.sun.tools.javac.code.Kinds.*; ...@@ -46,6 +46,7 @@ import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*; import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.jvm.ByteCodes.*; import static com.sun.tools.javac.jvm.ByteCodes.*;
import static com.sun.tools.javac.jvm.CRTFlags.*; import static com.sun.tools.javac.jvm.CRTFlags.*;
import static com.sun.tools.javac.main.OptionName.*;
/** This pass maps flat Java (i.e. without inner classes) to bytecodes. /** This pass maps flat Java (i.e. without inner classes) to bytecodes.
* *
...@@ -113,19 +114,19 @@ public class Gen extends JCTree.Visitor { ...@@ -113,19 +114,19 @@ public class Gen extends JCTree.Visitor {
Options options = Options.instance(context); Options options = Options.instance(context);
lineDebugInfo = lineDebugInfo =
options.get("-g:") == null || options.isUnset(G_CUSTOM) ||
options.get("-g:lines") != null; options.isSet(G_CUSTOM, "lines");
varDebugInfo = varDebugInfo =
options.get("-g:") == null options.isUnset(G_CUSTOM)
? options.get("-g") != null ? options.isSet(G)
: options.get("-g:vars") != null; : options.isSet(G_CUSTOM, "vars");
genCrt = options.get("-Xjcov") != null; genCrt = options.isSet(XJCOV);
debugCode = options.get("debugcode") != null; debugCode = options.isSet("debugcode");
allowInvokedynamic = target.hasInvokedynamic() || options.get("invokedynamic") != null; allowInvokedynamic = target.hasInvokedynamic() || options.isSet("invokedynamic");
generateIproxies = generateIproxies =
target.requiresIproxy() || target.requiresIproxy() ||
options.get("miranda") != null; options.isSet("miranda");
if (target.generateStackMapTable()) { if (target.generateStackMapTable()) {
// ignore cldc because we cannot have both stackmap formats // ignore cldc because we cannot have both stackmap formats
......
...@@ -31,6 +31,8 @@ import com.sun.tools.javac.code.Flags; ...@@ -31,6 +31,8 @@ import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.*;
import static com.sun.tools.javac.main.OptionName.*;
/** The classfile version target. /** The classfile version target.
* *
* <p><b>This is NOT part of any supported API. * <p><b>This is NOT part of any supported API.
...@@ -73,7 +75,7 @@ public enum Target { ...@@ -73,7 +75,7 @@ public enum Target {
Target instance = context.get(targetKey); Target instance = context.get(targetKey);
if (instance == null) { if (instance == null) {
Options options = Options.instance(context); Options options = Options.instance(context);
String targetString = options.get("-target"); String targetString = options.get(TARGET);
if (targetString != null) instance = lookup(targetString); if (targetString != null) instance = lookup(targetString);
if (instance == null) instance = DEFAULT; if (instance == null) instance = DEFAULT;
context.put(targetKey, instance); context.put(targetKey, instance);
......
/* /*
* Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -26,48 +26,44 @@ ...@@ -26,48 +26,44 @@
package com.sun.tools.javac.main; package com.sun.tools.javac.main;
import java.io.*; import java.io.*;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.Queue;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.Set; import java.util.Set;
import java.util.logging.Handler; import java.util.logging.Handler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.annotation.processing.Processor;
import javax.lang.model.SourceVersion;
import javax.tools.JavaFileManager; import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject; import javax.tools.JavaFileObject;
import javax.tools.DiagnosticListener; import javax.tools.DiagnosticListener;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener; import com.sun.source.util.TaskListener;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.*;
import com.sun.tools.javac.code.*; import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.*; import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.parser.*; import com.sun.tools.javac.parser.*;
import com.sun.tools.javac.comp.*; import com.sun.tools.javac.comp.*;
import com.sun.tools.javac.jvm.*; import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.processing.*; import com.sun.tools.javac.processing.*;
import javax.annotation.processing.Processor;
import static javax.tools.StandardLocation.CLASS_OUTPUT; import static javax.tools.StandardLocation.CLASS_OUTPUT;
import static com.sun.tools.javac.main.OptionName.*;
import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*; import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
import static com.sun.tools.javac.util.ListBuffer.lb; import static com.sun.tools.javac.util.ListBuffer.lb;
// TEMP, until we have a more efficient way to save doc comment info
import com.sun.tools.javac.parser.DocCommentScanner;
import java.util.HashMap;
import java.util.Queue;
import javax.lang.model.SourceVersion;
/** This class could be the main entry point for GJC when GJC is used as a /** This class could be the main entry point for GJC when GJC is used as a
* component in a larger software system. It provides operations to * component in a larger software system. It provides operations to
...@@ -359,22 +355,22 @@ public class JavaCompiler implements ClassReader.SourceCompleter { ...@@ -359,22 +355,22 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
Options options = Options.instance(context); Options options = Options.instance(context);
verbose = options.get("-verbose") != null; verbose = options.isSet(VERBOSE);
sourceOutput = options.get("-printsource") != null; // used to be -s sourceOutput = options.isSet(PRINTSOURCE); // used to be -s
stubOutput = options.get("-stubs") != null; stubOutput = options.isSet("-stubs");
relax = options.get("-relax") != null; relax = options.isSet("-relax");
printFlat = options.get("-printflat") != null; printFlat = options.isSet("-printflat");
attrParseOnly = options.get("-attrparseonly") != null; attrParseOnly = options.isSet("-attrparseonly");
encoding = options.get("-encoding"); encoding = options.get(ENCODING);
lineDebugInfo = options.get("-g:") == null || lineDebugInfo = options.isUnset(G_CUSTOM) ||
options.get("-g:lines") != null; options.isSet(G_CUSTOM, "lines");
genEndPos = options.get("-Xjcov") != null || genEndPos = options.isSet(XJCOV) ||
context.get(DiagnosticListener.class) != null; context.get(DiagnosticListener.class) != null;
devVerbose = options.get("dev") != null; devVerbose = options.isSet("dev");
processPcks = options.get("process.packages") != null; processPcks = options.isSet("process.packages");
werror = options.get("-Werror") != null; werror = options.isSet(WERROR);
verboseCompilePolicy = options.get("verboseCompilePolicy") != null; verboseCompilePolicy = options.isSet("verboseCompilePolicy");
if (attrParseOnly) if (attrParseOnly)
compilePolicy = CompilePolicy.ATTR_ONLY; compilePolicy = CompilePolicy.ATTR_ONLY;
...@@ -384,15 +380,15 @@ public class JavaCompiler implements ClassReader.SourceCompleter { ...@@ -384,15 +380,15 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit")); implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
completionFailureName = completionFailureName =
(options.get("failcomplete") != null) options.isSet("failcomplete")
? names.fromString(options.get("failcomplete")) ? names.fromString(options.get("failcomplete"))
: null; : null;
shouldStopPolicy = shouldStopPolicy =
(options.get("shouldStopPolicy") != null) options.isSet("shouldStopPolicy")
? CompileState.valueOf(options.get("shouldStopPolicy")) ? CompileState.valueOf(options.get("shouldStopPolicy"))
: null; : null;
if (options.get("oldDiags") == null) if (options.isUnset("oldDiags"))
log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context)); log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
} }
...@@ -957,18 +953,17 @@ public class JavaCompiler implements ClassReader.SourceCompleter { ...@@ -957,18 +953,17 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
// Process annotations if processing is not disabled and there // Process annotations if processing is not disabled and there
// is at least one Processor available. // is at least one Processor available.
Options options = Options.instance(context); Options options = Options.instance(context);
if (options.get("-proc:none") != null) { if (options.isSet(PROC, "none")) {
processAnnotations = false; processAnnotations = false;
} else if (procEnvImpl == null) { } else if (procEnvImpl == null) {
procEnvImpl = new JavacProcessingEnvironment(context, processors); procEnvImpl = new JavacProcessingEnvironment(context, processors);
processAnnotations = procEnvImpl.atLeastOneProcessor(); processAnnotations = procEnvImpl.atLeastOneProcessor();
if (processAnnotations) { if (processAnnotations) {
if (context.get(Scanner.Factory.scannerFactoryKey) == null)
DocCommentScanner.Factory.preRegister(context);
options.put("save-parameter-names", "save-parameter-names"); options.put("save-parameter-names", "save-parameter-names");
reader.saveParameterNames = true; reader.saveParameterNames = true;
keepComments = true; keepComments = true;
genEndPos = true;
if (taskListener != null) if (taskListener != null)
taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING)); taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
log.deferDiagnostics = true; log.deferDiagnostics = true;
...@@ -1017,7 +1012,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter { ...@@ -1017,7 +1012,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
// annotation processing is to occur with compilation, // annotation processing is to occur with compilation,
// emit a warning. // emit a warning.
Options options = Options.instance(context); Options options = Options.instance(context);
if (options.get("-proc:only") != null) { if (options.isSet(PROC, "only")) {
log.warning("proc.proc-only.requested.no.procs"); log.warning("proc.proc-only.requested.no.procs");
todo.clear(); todo.clear();
} }
...@@ -1105,10 +1100,10 @@ public class JavaCompiler implements ClassReader.SourceCompleter { ...@@ -1105,10 +1100,10 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
Options options = Options.instance(context); Options options = Options.instance(context);
return return
explicitAnnotationProcessingRequested || explicitAnnotationProcessingRequested ||
options.get("-processor") != null || options.isSet(PROCESSOR) ||
options.get("-processorpath") != null || options.isSet(PROCESSORPATH) ||
options.get("-proc:only") != null || options.isSet(PROC, "only") ||
options.get("-Xprint") != null; options.isSet(XPRINT);
} }
/** /**
...@@ -1587,6 +1582,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter { ...@@ -1587,6 +1582,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter {
} }
public void initRound(JavaCompiler prev) { public void initRound(JavaCompiler prev) {
genEndPos = prev.genEndPos;
keepComments = prev.keepComments; keepComments = prev.keepComments;
start_msec = prev.start_msec; start_msec = prev.start_msec;
hasBeenUsed = true; hasBeenUsed = true;
......
...@@ -32,6 +32,9 @@ import java.net.URL; ...@@ -32,6 +32,9 @@ import java.net.URL;
import java.security.DigestInputStream; import java.security.DigestInputStream;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.annotation.processing.Processor;
import com.sun.tools.javac.code.Source; import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.file.CacheFSInfo; import com.sun.tools.javac.file.CacheFSInfo;
...@@ -41,9 +44,8 @@ import com.sun.tools.javac.main.JavacOption.Option; ...@@ -41,9 +44,8 @@ import com.sun.tools.javac.main.JavacOption.Option;
import com.sun.tools.javac.main.RecognizedOptions.OptionHelper; import com.sun.tools.javac.main.RecognizedOptions.OptionHelper;
import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.*;
import com.sun.tools.javac.processing.AnnotationProcessingError; import com.sun.tools.javac.processing.AnnotationProcessingError;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject; import static com.sun.tools.javac.main.OptionName.*;
import javax.annotation.processing.Processor;
/** This class provides a commandline interface to the GJC compiler. /** This class provides a commandline interface to the GJC compiler.
* *
...@@ -239,16 +241,16 @@ public class Main { ...@@ -239,16 +241,16 @@ public class Main {
} }
} }
if (!checkDirectory("-d")) if (!checkDirectory(D))
return null; return null;
if (!checkDirectory("-s")) if (!checkDirectory(S))
return null; return null;
String sourceString = options.get("-source"); String sourceString = options.get(SOURCE);
Source source = (sourceString != null) Source source = (sourceString != null)
? Source.lookup(sourceString) ? Source.lookup(sourceString)
: Source.DEFAULT; : Source.DEFAULT;
String targetString = options.get("-target"); String targetString = options.get(TARGET);
Target target = (targetString != null) Target target = (targetString != null)
? Target.lookup(targetString) ? Target.lookup(targetString)
: Target.DEFAULT; : Target.DEFAULT;
...@@ -285,7 +287,7 @@ public class Main { ...@@ -285,7 +287,7 @@ public class Main {
// phase this out with JSR 292 PFD // phase this out with JSR 292 PFD
if ("no".equals(options.get("allowTransitionalJSR292"))) { if ("no".equals(options.get("allowTransitionalJSR292"))) {
options.put("allowTransitionalJSR292", null); options.put("allowTransitionalJSR292", null);
} else if (target.hasInvokedynamic() && options.get("allowTransitionalJSR292") == null) { } else if (target.hasInvokedynamic() && options.isUnset("allowTransitionalJSR292")) {
options.put("allowTransitionalJSR292", "allowTransitionalJSR292"); options.put("allowTransitionalJSR292", "allowTransitionalJSR292");
} }
...@@ -300,7 +302,7 @@ public class Main { ...@@ -300,7 +302,7 @@ public class Main {
return filenames.toList(); return filenames.toList();
} }
// where // where
private boolean checkDirectory(String optName) { private boolean checkDirectory(OptionName optName) {
String value = options.get(optName); String value = options.get(optName);
if (value == null) if (value == null)
return true; return true;
...@@ -367,10 +369,10 @@ public class Main { ...@@ -367,10 +369,10 @@ public class Main {
return EXIT_CMDERR; return EXIT_CMDERR;
} else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) { } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
// it is allowed to compile nothing if just asking for help or version info // it is allowed to compile nothing if just asking for help or version info
if (options.get("-help") != null if (options.isSet(HELP)
|| options.get("-X") != null || options.isSet(X)
|| options.get("-version") != null || options.isSet(VERSION)
|| options.get("-fullversion") != null) || options.isSet(FULLVERSION))
return EXIT_OK; return EXIT_OK;
error("err.no.source.files"); error("err.no.source.files");
return EXIT_CMDERR; return EXIT_CMDERR;
...@@ -382,7 +384,7 @@ public class Main { ...@@ -382,7 +384,7 @@ public class Main {
return EXIT_SYSERR; return EXIT_SYSERR;
} }
boolean forceStdOut = options.get("stdout") != null; boolean forceStdOut = options.isSet("stdout");
if (forceStdOut) { if (forceStdOut) {
out.flush(); out.flush();
out = new PrintWriter(System.out, true); out = new PrintWriter(System.out, true);
...@@ -391,7 +393,7 @@ public class Main { ...@@ -391,7 +393,7 @@ public class Main {
context.put(Log.outKey, out); context.put(Log.outKey, out);
// allow System property in following line as a Mustang legacy // allow System property in following line as a Mustang legacy
boolean batchMode = (options.get("nonBatchMode") == null boolean batchMode = (options.isUnset("nonBatchMode")
&& System.getProperty("nonBatchMode") == null); && System.getProperty("nonBatchMode") == null);
if (batchMode) if (batchMode)
CacheFSInfo.preRegister(context); CacheFSInfo.preRegister(context);
...@@ -455,7 +457,7 @@ public class Main { ...@@ -455,7 +457,7 @@ public class Main {
// for buggy compiler error recovery by swallowing thrown // for buggy compiler error recovery by swallowing thrown
// exceptions. // exceptions.
if (comp == null || comp.errorCount() == 0 || if (comp == null || comp.errorCount() == 0 ||
options == null || options.get("dev") != null) options == null || options.isSet("dev"))
bugMessage(ex); bugMessage(ex);
return EXIT_ABNORMAL; return EXIT_ABNORMAL;
} finally { } finally {
...@@ -478,7 +480,7 @@ public class Main { ...@@ -478,7 +480,7 @@ public class Main {
*/ */
void feMessage(Throwable ex) { void feMessage(Throwable ex) {
Log.printLines(out, ex.getMessage()); Log.printLines(out, ex.getMessage());
if (ex.getCause() != null && options.get("dev") != null) { if (ex.getCause() != null && options.isSet("dev")) {
ex.getCause().printStackTrace(out); ex.getCause().printStackTrace(out);
} }
} }
......
...@@ -366,11 +366,11 @@ public class JavacPathFileManager extends BaseFileManager implements PathFileMan ...@@ -366,11 +366,11 @@ public class JavacPathFileManager extends BaseFileManager implements PathFileMan
// } // }
// } // }
int maxDepth = (recurse ? Integer.MAX_VALUE : 1); int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
Set<FileVisitOption> opts = EnumSet.of(DETECT_CYCLES, FOLLOW_LINKS); Set<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
Files.walkFileTree(packageDir, opts, maxDepth, Files.walkFileTree(packageDir, opts, maxDepth,
new SimpleFileVisitor<Path>() { new SimpleFileVisitor<Path>() {
@Override @Override
public FileVisitResult preVisitDirectory(Path dir) { public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (SourceVersion.isIdentifier(dir.getName().toString())) // JSR 292? if (SourceVersion.isIdentifier(dir.getName().toString())) // JSR 292?
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
else else
......
/* /*
* Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -42,50 +42,17 @@ import static com.sun.tools.javac.util.LayoutCharacters.*; ...@@ -42,50 +42,17 @@ import static com.sun.tools.javac.util.LayoutCharacters.*;
*/ */
public class DocCommentScanner extends Scanner { public class DocCommentScanner extends Scanner {
/** A factory for creating scanners. */
public static class Factory extends Scanner.Factory {
public static void preRegister(final Context context) {
context.put(scannerFactoryKey, new Context.Factory<Scanner.Factory>() {
public Factory make() {
return new Factory(context);
}
});
}
/** Create a new scanner factory. */
protected Factory(Context context) {
super(context);
}
@Override
public Scanner newScanner(CharSequence input) {
if (input instanceof CharBuffer) {
return new DocCommentScanner(this, (CharBuffer)input);
} else {
char[] array = input.toString().toCharArray();
return newScanner(array, array.length);
}
}
@Override
public Scanner newScanner(char[] input, int inputLength) {
return new DocCommentScanner(this, input, inputLength);
}
}
/** Create a scanner from the input buffer. buffer must implement /** Create a scanner from the input buffer. buffer must implement
* array() and compact(), and remaining() must be less than limit(). * array() and compact(), and remaining() must be less than limit().
*/ */
protected DocCommentScanner(Factory fac, CharBuffer buffer) { protected DocCommentScanner(ScannerFactory fac, CharBuffer buffer) {
super(fac, buffer); super(fac, buffer);
} }
/** Create a scanner from the input array. The array must have at /** Create a scanner from the input array. The array must have at
* least a single character of extra space. * least a single character of extra space.
*/ */
protected DocCommentScanner(Factory fac, char[] input, int inputLength) { protected DocCommentScanner(ScannerFactory fac, char[] input, int inputLength) {
super(fac, input, inputLength); super(fac, input, inputLength);
} }
......
/* /*
* Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -2473,6 +2473,11 @@ public class JavacParser implements Parser { ...@@ -2473,6 +2473,11 @@ public class JavacParser implements Parser {
defs.append(importDeclaration()); defs.append(importDeclaration());
} else { } else {
JCTree def = typeDeclaration(mods); JCTree def = typeDeclaration(mods);
if (keepDocComments && dc != null && docComments.get(def) == dc) {
// If the first type declaration has consumed the first doc
// comment, then don't use it for the top level comment as well.
dc = null;
}
if (def instanceof JCExpressionStatement) if (def instanceof JCExpressionStatement)
def = ((JCExpressionStatement)def).expr; def = ((JCExpressionStatement)def).expr;
defs.append(def); defs.append(def);
......
/* /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -59,7 +59,7 @@ public class ParserFactory { ...@@ -59,7 +59,7 @@ public class ParserFactory {
final Source source; final Source source;
final Names names; final Names names;
final Options options; final Options options;
final Scanner.Factory scannerFactory; final ScannerFactory scannerFactory;
protected ParserFactory(Context context) { protected ParserFactory(Context context) {
super(); super();
...@@ -70,11 +70,11 @@ public class ParserFactory { ...@@ -70,11 +70,11 @@ public class ParserFactory {
this.keywords = Keywords.instance(context); this.keywords = Keywords.instance(context);
this.source = Source.instance(context); this.source = Source.instance(context);
this.options = Options.instance(context); this.options = Options.instance(context);
this.scannerFactory = Scanner.Factory.instance(context); this.scannerFactory = ScannerFactory.instance(context);
} }
public Parser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) { public Parser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) {
Lexer lexer = scannerFactory.newScanner(input); Lexer lexer = scannerFactory.newScanner(input, keepDocComments);
if (keepEndPos) { if (keepEndPos) {
return new EndPosParser(this, lexer, keepDocComments, keepLineMap); return new EndPosParser(this, lexer, keepDocComments, keepLineMap);
} else { } else {
......
/* /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -47,48 +47,6 @@ public class Scanner implements Lexer { ...@@ -47,48 +47,6 @@ public class Scanner implements Lexer {
private static boolean scannerDebug = false; private static boolean scannerDebug = false;
/** A factory for creating scanners. */
public static class Factory {
/** The context key for the scanner factory. */
public static final Context.Key<Scanner.Factory> scannerFactoryKey =
new Context.Key<Scanner.Factory>();
/** Get the Factory instance for this context. */
public static Factory instance(Context context) {
Factory instance = context.get(scannerFactoryKey);
if (instance == null)
instance = new Factory(context);
return instance;
}
final Log log;
final Names names;
final Source source;
final Keywords keywords;
/** Create a new scanner factory. */
protected Factory(Context context) {
context.put(scannerFactoryKey, this);
this.log = Log.instance(context);
this.names = Names.instance(context);
this.source = Source.instance(context);
this.keywords = Keywords.instance(context);
}
public Scanner newScanner(CharSequence input) {
if (input instanceof CharBuffer) {
return new Scanner(this, (CharBuffer)input);
} else {
char[] array = input.toString().toCharArray();
return newScanner(array, array.length);
}
}
public Scanner newScanner(char[] input, int inputLength) {
return new Scanner(this, input, inputLength);
}
}
/* Output variables; set by nextToken(): /* Output variables; set by nextToken():
*/ */
...@@ -177,7 +135,7 @@ public class Scanner implements Lexer { ...@@ -177,7 +135,7 @@ public class Scanner implements Lexer {
private final Keywords keywords; private final Keywords keywords;
/** Common code for constructors. */ /** Common code for constructors. */
private Scanner(Factory fac) { private Scanner(ScannerFactory fac) {
log = fac.log; log = fac.log;
names = fac.names; names = fac.names;
keywords = fac.keywords; keywords = fac.keywords;
...@@ -201,7 +159,7 @@ public class Scanner implements Lexer { ...@@ -201,7 +159,7 @@ public class Scanner implements Lexer {
/** Create a scanner from the input buffer. buffer must implement /** Create a scanner from the input buffer. buffer must implement
* array() and compact(), and remaining() must be less than limit(). * array() and compact(), and remaining() must be less than limit().
*/ */
protected Scanner(Factory fac, CharBuffer buffer) { protected Scanner(ScannerFactory fac, CharBuffer buffer) {
this(fac, JavacFileManager.toArray(buffer), buffer.limit()); this(fac, JavacFileManager.toArray(buffer), buffer.limit());
} }
...@@ -216,7 +174,7 @@ public class Scanner implements Lexer { ...@@ -216,7 +174,7 @@ public class Scanner implements Lexer {
* @param inputLength the size of the input. * @param inputLength the size of the input.
* Must be positive and less than or equal to input.length. * Must be positive and less than or equal to input.length.
*/ */
protected Scanner(Factory fac, char[] input, int inputLength) { protected Scanner(ScannerFactory fac, char[] input, int inputLength) {
this(fac); this(fac);
eofPos = inputLength; eofPos = inputLength;
if (inputLength == input.length) { if (inputLength == input.length) {
......
/*
* Copyright (c) 1999, 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. 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.tools.javac.parser;
import java.nio.CharBuffer;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Names;
/**
* A factory for creating scanners.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b>
*/
public class ScannerFactory {
/** The context key for the scanner factory. */
public static final Context.Key<ScannerFactory> scannerFactoryKey =
new Context.Key<ScannerFactory>();
/** Get the Factory instance for this context. */
public static ScannerFactory instance(Context context) {
ScannerFactory instance = context.get(scannerFactoryKey);
if (instance == null)
instance = new ScannerFactory(context);
return instance;
}
final Log log;
final Names names;
final Source source;
final Keywords keywords;
/** Create a new scanner factory. */
protected ScannerFactory(Context context) {
context.put(scannerFactoryKey, this);
this.log = Log.instance(context);
this.names = Names.instance(context);
this.source = Source.instance(context);
this.keywords = Keywords.instance(context);
}
public Scanner newScanner(CharSequence input, boolean keepDocComments) {
if (input instanceof CharBuffer) {
CharBuffer buf = (CharBuffer) input;
if (keepDocComments)
return new DocCommentScanner(this, buf);
else
return new Scanner(this, buf);
} else {
char[] array = input.toString().toCharArray();
return newScanner(array, array.length, keepDocComments);
}
}
public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) {
if (keepDocComments)
return new DocCommentScanner(this, input, inputLength);
else
return new Scanner(this, input, inputLength);
}
}
...@@ -25,14 +25,6 @@ ...@@ -25,14 +25,6 @@
package com.sun.tools.javac.processing; package com.sun.tools.javac.processing;
import com.sun.tools.javac.util.*;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Element;
import java.util.*;
import java.io.Closeable; import java.io.Closeable;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream; import java.io.InputStream;
...@@ -43,14 +35,26 @@ import java.io.Writer; ...@@ -43,14 +35,26 @@ import java.io.Writer;
import java.io.FilterWriter; import java.io.FilterWriter;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.IOException; import java.io.IOException;
import java.util.*;
import javax.tools.*;
import static java.util.Collections.*; import static java.util.Collections.*;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Element;
import javax.tools.*;
import javax.tools.JavaFileManager.Location; import javax.tools.JavaFileManager.Location;
import static javax.tools.StandardLocation.SOURCE_OUTPUT; import static javax.tools.StandardLocation.SOURCE_OUTPUT;
import static javax.tools.StandardLocation.CLASS_OUTPUT; import static javax.tools.StandardLocation.CLASS_OUTPUT;
import com.sun.tools.javac.code.Lint;
import com.sun.tools.javac.util.*;
import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
/** /**
* The FilerImplementation class must maintain a number of * The FilerImplementation class must maintain a number of
* constraints. First, multiple attempts to open the same path within * constraints. First, multiple attempts to open the same path within
...@@ -366,7 +370,7 @@ public class JavacFiler implements Filer, Closeable { ...@@ -366,7 +370,7 @@ public class JavacFiler implements Filer, Closeable {
aggregateGeneratedSourceNames = new LinkedHashSet<String>(); aggregateGeneratedSourceNames = new LinkedHashSet<String>();
aggregateGeneratedClassNames = new LinkedHashSet<String>(); aggregateGeneratedClassNames = new LinkedHashSet<String>();
lint = (Options.instance(context)).lint("processing"); lint = (Lint.instance(context)).isEnabled(PROCESSING);
} }
public JavaFileObject createSourceFile(CharSequence name, public JavaFileObject createSourceFile(CharSequence name,
......
/* /*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -49,6 +49,7 @@ import javax.tools.StandardJavaFileManager; ...@@ -49,6 +49,7 @@ import javax.tools.StandardJavaFileManager;
import javax.tools.JavaFileObject; import javax.tools.JavaFileObject;
import javax.tools.DiagnosticListener; import javax.tools.DiagnosticListener;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.source.util.AbstractTypeProcessor; import com.sun.source.util.AbstractTypeProcessor;
import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener; import com.sun.source.util.TaskListener;
...@@ -78,6 +79,8 @@ import com.sun.tools.javac.util.Options; ...@@ -78,6 +79,8 @@ import com.sun.tools.javac.util.Options;
import static javax.tools.StandardLocation.*; import static javax.tools.StandardLocation.*;
import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*; import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
import static com.sun.tools.javac.main.OptionName.*;
import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
/** /**
* Objects of this class hold and manage the state needed to support * Objects of this class hold and manage the state needed to support
...@@ -159,15 +162,14 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -159,15 +162,14 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
source = Source.instance(context); source = Source.instance(context);
diags = JCDiagnostic.Factory.instance(context); diags = JCDiagnostic.Factory.instance(context);
options = Options.instance(context); options = Options.instance(context);
printProcessorInfo = options.get("-XprintProcessorInfo") != null; printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
printRounds = options.get("-XprintRounds") != null; printRounds = options.isSet(XPRINTROUNDS);
verbose = options.get("-verbose") != null; verbose = options.isSet(VERBOSE);
lint = options.lint("processing"); lint = Lint.instance(context).isEnabled(PROCESSING);
procOnly = options.get("-proc:only") != null || procOnly = options.isSet(PROC, "only") || options.isSet(XPRINT);
options.get("-Xprint") != null; fatalErrors = options.isSet("fatalEnterError");
fatalErrors = options.get("fatalEnterError") != null; showResolveErrors = options.isSet("showResolveErrors");
showResolveErrors = options.get("showResolveErrors") != null; werror = options.isSet(WERROR);
werror = options.get("-Werror") != null;
platformAnnotations = initPlatformAnnotations(); platformAnnotations = initPlatformAnnotations();
foundTypeProcessors = false; foundTypeProcessors = false;
...@@ -199,7 +201,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -199,7 +201,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
Log log = Log.instance(context); Log log = Log.instance(context);
Iterator<? extends Processor> processorIterator; Iterator<? extends Processor> processorIterator;
if (options.get("-Xprint") != null) { if (options.isSet(XPRINT)) {
try { try {
Processor processor = PrintingProcessor.class.newInstance(); Processor processor = PrintingProcessor.class.newInstance();
processorIterator = List.of(processor).iterator(); processorIterator = List.of(processor).iterator();
...@@ -212,7 +214,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -212,7 +214,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
} else if (processors != null) { } else if (processors != null) {
processorIterator = processors.iterator(); processorIterator = processors.iterator();
} else { } else {
String processorNames = options.get("-processor"); String processorNames = options.get(PROCESSOR);
JavaFileManager fileManager = context.get(JavaFileManager.class); JavaFileManager fileManager = context.get(JavaFileManager.class);
try { try {
// If processorpath is not explicitly set, use the classpath. // If processorpath is not explicitly set, use the classpath.
...@@ -263,7 +265,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -263,7 +265,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH) ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
: standardFileManager.getLocation(CLASS_PATH); : standardFileManager.getLocation(CLASS_PATH);
if (needClassLoader(options.get("-processor"), workingPath) ) if (needClassLoader(options.get(PROCESSOR), workingPath) )
handleException(key, e); handleException(key, e);
} else { } else {
...@@ -744,7 +746,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -744,7 +746,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
psi.runContributingProcs(renv); psi.runContributingProcs(renv);
// Debugging // Debugging
if (options.get("displayFilerState") != null) if (options.isSet("displayFilerState"))
filer.displayState(); filer.displayState();
} }
...@@ -1104,6 +1106,12 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea ...@@ -1104,6 +1106,12 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
task.updateContext(next); task.updateContext(next);
} }
JavacTrees trees = context.get(JavacTrees.class);
if (trees != null) {
next.put(JavacTrees.class, trees);
trees.updateContext(next);
}
context.clear(); context.clear();
return next; return next;
} }
......
...@@ -93,6 +93,8 @@ compiler.err.cant.apply.symbol.1=\ ...@@ -93,6 +93,8 @@ compiler.err.cant.apply.symbol.1=\
required: {2}\n\ required: {2}\n\
found: {3}\n\ found: {3}\n\
reason: {6} reason: {6}
compiler.err.cant.apply.symbols=\
no suitable {0} found for {1}({2})
compiler.err.cant.assign.val.to.final.var=\ compiler.err.cant.assign.val.to.final.var=\
cannot assign a value to final variable {0} cannot assign a value to final variable {0}
compiler.err.cant.deref=\ compiler.err.cant.deref=\
...@@ -1075,11 +1077,11 @@ compiler.misc.no.unique.maximal.instance.exists=\ ...@@ -1075,11 +1077,11 @@ compiler.misc.no.unique.maximal.instance.exists=\
no unique maximal instance exists for type variable {0} with upper bounds {1} no unique maximal instance exists for type variable {0} with upper bounds {1}
compiler.misc.no.unique.minimal.instance.exists=\ compiler.misc.no.unique.minimal.instance.exists=\
no unique minimal instance exists for type variable {0} with lower bounds {1} no unique minimal instance exists for type variable {0} with lower bounds {1}
compiler.misc.no.conforming.instance.exists=\ compiler.misc.infer.no.conforming.instance.exists=\
no instance(s) of type variable(s) {0} exist so that {1} conforms to {2} no instance(s) of type variable(s) {0} exist so that {1} conforms to {2}
compiler.misc.no.conforming.assignment.exists=\ compiler.misc.infer.no.conforming.assignment.exists=\
no instance(s) of type variable(s) {0} exist so that argument type {1} conforms to formal parameter type {2} no instance(s) of type variable(s) {0} exist so that argument type {1} conforms to formal parameter type {2}
compiler.misc.arg.length.mismatch=\ compiler.misc.infer.arg.length.mismatch=\
cannot instantiate from arguments because actual and formal argument lists differ in length cannot instantiate from arguments because actual and formal argument lists differ in length
compiler.misc.inferred.do.not.conform.to.bounds=\ compiler.misc.inferred.do.not.conform.to.bounds=\
inferred type does not conform to declared bound(s)\n\ inferred type does not conform to declared bound(s)\n\
...@@ -1095,6 +1097,16 @@ compiler.misc.diamond.invalid.arg=\ ...@@ -1095,6 +1097,16 @@ compiler.misc.diamond.invalid.arg=\
type argument {0} inferred for {1} is not allowed in this context type argument {0} inferred for {1} is not allowed in this context
compiler.misc.diamond.invalid.args=\ compiler.misc.diamond.invalid.args=\
type arguments {0} inferred for {1} are not allowed in this context type arguments {0} inferred for {1} are not allowed in this context
compiler.misc.explicit.param.do.not.conform.to.bounds=\
explicit type argument {0} does not conform to declared bound(s) {1}
compiler.misc.arg.length.mismatch=\
actual and formal argument lists differ in length
compiler.misc.no.conforming.assignment.exists=\
actual argument {0} cannot be converted to {1} by method invocation conversion
compiler.misc.varargs.argument.mismatch=\
argument type {0} does not conform to vararg element type {1}
##### #####
## The first argument ({0}) is a "kindname". ## The first argument ({0}) is a "kindname".
...@@ -1232,6 +1244,10 @@ compiler.misc.varargs.clash.with=\ ...@@ -1232,6 +1244,10 @@ compiler.misc.varargs.clash.with=\
compiler.misc.non.denotable.type=\ compiler.misc.non.denotable.type=\
Non-denotable type {0} not allowed here Non-denotable type {0} not allowed here
compiler.misc.inapplicable.method=\
{0} {1}.{2} is not applicable\n\
({3})
######################################## ########################################
# Diagnostics for language feature changes # Diagnostics for language feature changes
######################################## ########################################
......
...@@ -65,8 +65,6 @@ import static com.sun.tools.javac.util.LayoutCharacters.*; ...@@ -65,8 +65,6 @@ import static com.sun.tools.javac.util.LayoutCharacters.*;
*/ */
public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter { public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
protected int currentIndentation = 0;
/** /**
* Create a basic formatter based on the supplied options. * Create a basic formatter based on the supplied options.
* *
...@@ -107,33 +105,28 @@ public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter { ...@@ -107,33 +105,28 @@ public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
} }
public String formatMessage(JCDiagnostic d, Locale l) { public String formatMessage(JCDiagnostic d, Locale l) {
int prevIndentation = currentIndentation; int currentIndentation = 0;
try { StringBuilder buf = new StringBuilder();
StringBuilder buf = new StringBuilder(); Collection<String> args = formatArguments(d, l);
Collection<String> args = formatArguments(d, l); String msg = localize(l, d.getCode(), args.toArray());
String msg = localize(l, d.getCode(), args.toArray()); String[] lines = msg.split("\n");
String[] lines = msg.split("\n"); if (getConfiguration().getVisible().contains(DiagnosticPart.SUMMARY)) {
if (getConfiguration().getVisible().contains(DiagnosticPart.SUMMARY)) { currentIndentation += getConfiguration().getIndentation(DiagnosticPart.SUMMARY);
currentIndentation += getConfiguration().getIndentation(DiagnosticPart.SUMMARY); buf.append(indent(lines[0], currentIndentation)); //summary
buf.append(indent(lines[0], currentIndentation)); //summary }
} if (lines.length > 1 && getConfiguration().getVisible().contains(DiagnosticPart.DETAILS)) {
if (lines.length > 1 && getConfiguration().getVisible().contains(DiagnosticPart.DETAILS)) { currentIndentation += getConfiguration().getIndentation(DiagnosticPart.DETAILS);
currentIndentation += getConfiguration().getIndentation(DiagnosticPart.DETAILS); for (int i = 1;i < lines.length; i++) {
for (int i = 1;i < lines.length; i++) { buf.append("\n" + indent(lines[i], currentIndentation));
buf.append("\n" + indent(lines[i], currentIndentation));
}
} }
if (d.isMultiline() && getConfiguration().getVisible().contains(DiagnosticPart.SUBDIAGNOSTICS)) { }
currentIndentation += getConfiguration().getIndentation(DiagnosticPart.SUBDIAGNOSTICS); if (d.isMultiline() && getConfiguration().getVisible().contains(DiagnosticPart.SUBDIAGNOSTICS)) {
currentIndentation += getConfiguration().getIndentation(DiagnosticPart.SUBDIAGNOSTICS);
for (String sub : formatSubdiagnostics(d, l)) { for (String sub : formatSubdiagnostics(d, l)) {
buf.append("\n" + sub); buf.append("\n" + indent(sub, currentIndentation));
}
} }
return buf.toString();
}
finally {
currentIndentation = prevIndentation;
} }
return buf.toString();
} }
protected String addSourceLineIfNeeded(JCDiagnostic d, String msg) { protected String addSourceLineIfNeeded(JCDiagnostic d, String msg) {
......
...@@ -35,11 +35,14 @@ import java.util.Set; ...@@ -35,11 +35,14 @@ import java.util.Set;
import javax.tools.DiagnosticListener; import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject; import javax.tools.JavaFileObject;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.api.DiagnosticFormatter; import com.sun.tools.javac.api.DiagnosticFormatter;
import com.sun.tools.javac.main.OptionName;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
import static com.sun.tools.javac.main.OptionName.*;
/** A class for error logs. Reports errors and warnings, and /** A class for error logs. Reports errors and warnings, and
* keeps track of error numbers and positions. * keeps track of error numbers and positions.
* *
...@@ -129,14 +132,14 @@ public class Log extends AbstractLog { ...@@ -129,14 +132,14 @@ public class Log extends AbstractLog {
this.noticeWriter = noticeWriter; this.noticeWriter = noticeWriter;
Options options = Options.instance(context); Options options = Options.instance(context);
this.dumpOnError = options.get("-doe") != null; this.dumpOnError = options.isSet(DOE);
this.promptOnError = options.get("-prompt") != null; this.promptOnError = options.isSet(PROMPT);
this.emitWarnings = options.get("-Xlint:none") == null; this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
this.suppressNotes = options.get("suppressNotes") != null; this.suppressNotes = options.isSet("suppressNotes");
this.MaxErrors = getIntOption(options, "-Xmaxerrs", getDefaultMaxErrors()); this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
this.MaxWarnings = getIntOption(options, "-Xmaxwarns", getDefaultMaxWarnings()); this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
boolean rawDiagnostics = options.get("rawDiagnostics") != null; boolean rawDiagnostics = options.isSet("rawDiagnostics");
messages = JavacMessages.instance(context); messages = JavacMessages.instance(context);
this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) : this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
new BasicDiagnosticFormatter(options, messages); new BasicDiagnosticFormatter(options, messages);
...@@ -150,7 +153,7 @@ public class Log extends AbstractLog { ...@@ -150,7 +153,7 @@ public class Log extends AbstractLog {
expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *"))); expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
} }
// where // where
private int getIntOption(Options options, String optionName, int defaultValue) { private int getIntOption(Options options, OptionName optionName, int defaultValue) {
String s = options.get(optionName); String s = options.get(optionName);
try { try {
if (s != null) { if (s != null) {
......
...@@ -271,7 +271,7 @@ public class Names { ...@@ -271,7 +271,7 @@ public class Names {
} }
protected Name.Table createTable(Options options) { protected Name.Table createTable(Options options) {
boolean useUnsharedTable = options.get("useUnsharedTable") != null; boolean useUnsharedTable = options.isSet("useUnsharedTable");
if (useUnsharedTable) if (useUnsharedTable)
return new UnsharedNameTable(this); return new UnsharedNameTable(this);
else else
......
...@@ -25,8 +25,9 @@ ...@@ -25,8 +25,9 @@
package com.sun.tools.javac.util; package com.sun.tools.javac.util;
import com.sun.tools.javac.main.OptionName;
import java.util.*; import java.util.*;
import com.sun.tools.javac.main.OptionName;
import static com.sun.tools.javac.main.OptionName.*;
/** A table of all command-line options. /** A table of all command-line options.
* If an option has an argument, the option name is mapped to the argument. * If an option has an argument, the option name is mapped to the argument.
...@@ -60,14 +61,62 @@ public class Options { ...@@ -60,14 +61,62 @@ public class Options {
context.put(optionsKey, this); context.put(optionsKey, this);
} }
/**
* Get the value for an undocumented option.
*/
public String get(String name) { public String get(String name) {
return values.get(name); return values.get(name);
} }
/**
* Get the value for an option.
*/
public String get(OptionName name) { public String get(OptionName name) {
return values.get(name.optionName); return values.get(name.optionName);
} }
/**
* Check if the value for an undocumented option has been set.
*/
public boolean isSet(String name) {
return (values.get(name) != null);
}
/**
* Check if the value for an option has been set.
*/
public boolean isSet(OptionName name) {
return (values.get(name.optionName) != null);
}
/**
* Check if the value for a choice option has been set to a specific value.
*/
public boolean isSet(OptionName name, String value) {
return (values.get(name.optionName + value) != null);
}
/**
* Check if the value for an undocumented option has not been set.
*/
public boolean isUnset(String name) {
return (values.get(name) == null);
}
/**
* Check if the value for an option has not been set.
*/
public boolean isUnset(OptionName name) {
return (values.get(name.optionName) == null);
}
/**
* Check if the value for a choice option has not been set to a specific value.
*/
public boolean isUnset(OptionName name, String value) {
return (values.get(name.optionName + value) == null);
}
public void put(String name, String value) { public void put(String name, String value) {
values.put(name, value); values.put(name, value);
} }
...@@ -92,16 +141,14 @@ public class Options { ...@@ -92,16 +141,14 @@ public class Options {
return values.size(); return values.size();
} }
static final String LINT = "-Xlint";
/** Check for a lint suboption. */ /** Check for a lint suboption. */
public boolean lint(String s) { public boolean lint(String s) {
// return true if either the specific option is enabled, or // return true if either the specific option is enabled, or
// they are all enabled without the specific one being // they are all enabled without the specific one being
// disabled // disabled
return return
get(LINT + ":" + s)!=null || isSet(XLINT_CUSTOM, s) ||
(get(LINT)!=null || get(LINT + ":all")!=null) && (isSet(XLINT) || isSet(XLINT_CUSTOM, "all")) &&
get(LINT+":-"+s)==null; isUnset(XLINT_CUSTOM, "-" + s);
} }
} }
/* /*
* Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -107,9 +107,6 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler { ...@@ -107,9 +107,6 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler {
// force the use of Messager as a Log // force the use of Messager as a Log
messager = Messager.instance0(context); messager = Messager.instance0(context);
// force the use of the scanner that captures Javadoc comments
DocCommentScanner.Factory.preRegister(context);
return new JavadocTool(context); return new JavadocTool(context);
} catch (CompletionFailure ex) { } catch (CompletionFailure ex) {
messager.error(Position.NOPOS, ex.getMessage()); messager.error(Position.NOPOS, ex.getMessage());
......
/* /*
* Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -526,15 +526,17 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask { ...@@ -526,15 +526,17 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
} }
private void showVersion(boolean full) { private void showVersion(boolean full) {
log.println(version(full ? "full" : "release")); log.println(version(full));
} }
private static final String versionRBName = "com.sun.tools.javah.resources.version"; private static final String versionRBName = "com.sun.tools.javah.resources.version";
private static ResourceBundle versionRB; private static ResourceBundle versionRB;
private String version(String key) { private String version(boolean full) {
// key=version: mm.nn.oo[-milestone] String msgKey = (full ? "javah.fullVersion" : "javah.version");
// key=full: mm.mm.oo[-milestone]-build String versionKey = (full ? "full" : "release");
// versionKey=product: mm.nn.oo[-milestone]
// versionKey=full: mm.mm.oo[-milestone]-build
if (versionRB == null) { if (versionRB == null) {
try { try {
versionRB = ResourceBundle.getBundle(versionRBName); versionRB = ResourceBundle.getBundle(versionRBName);
...@@ -543,7 +545,7 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask { ...@@ -543,7 +545,7 @@ public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
} }
} }
try { try {
return versionRB.getString(key); return getMessage(msgKey, "javah", versionRB.getString(versionKey));
} }
catch (MissingResourceException e) { catch (MissingResourceException e) {
return getMessage("version.unknown", System.getProperty("java.version")); return getMessage("version.unknown", System.getProperty("java.version"));
......
# #
# Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -113,7 +113,8 @@ main.usage.foot=\ ...@@ -113,7 +113,8 @@ main.usage.foot=\
# #
# Version string. # Version string.
# #
javah.version=javah version "{0}" javah.version={0} version "{1}"
javah.fullVersion={0} full version "{1}"
# #
# These should have better diagnostics. # These should have better diagnostics.
......
#
# Copyright (c) 2005, 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.
#
jdk=$(JDK_VERSION)
full=$(FULL_VERSION)
release=$(RELEASE)
/**
* This is a test that uses ISO 8859 encoding.
*/
class T6302184 { class T6302184 {
T6302184() { T6302184() {
......
/* /*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -35,7 +35,6 @@ import javax.tools.SimpleJavaFileObject; ...@@ -35,7 +35,6 @@ import javax.tools.SimpleJavaFileObject;
import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.parser.Parser; import com.sun.tools.javac.parser.Parser;
import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.parser.ParserFactory;
import com.sun.tools.javac.parser.Scanner;
import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Context;
...@@ -60,7 +59,6 @@ public class TestLog ...@@ -60,7 +59,6 @@ public class TestLog
log.multipleErrors = true; log.multipleErrors = true;
JavacFileManager.preRegister(context); JavacFileManager.preRegister(context);
Scanner.Factory sfac = Scanner.Factory.instance(context);
ParserFactory pfac = ParserFactory.instance(context); ParserFactory pfac = ParserFactory.instance(context);
final String text = final String text =
......
T6758789a.java:14:9: compiler.err.cant.apply.symbol: kindname.method, m1, compiler.misc.no.args, int, kindname.class, T6758789a, null T6758789a.java:14:9: compiler.err.cant.apply.symbol.1: kindname.method, m1, compiler.misc.no.args, int, kindname.class, T6758789a, (compiler.misc.arg.length.mismatch)
T6758789a.java:15:9: compiler.err.cant.apply.symbol: kindname.method, m2, int, compiler.misc.no.args, kindname.class, T6758789a, null T6758789a.java:15:9: compiler.err.cant.apply.symbol.1: kindname.method, m2, int, compiler.misc.no.args, kindname.class, T6758789a, (compiler.misc.arg.length.mismatch)
2 errors 2 errors
T6840059.java:15:9: compiler.err.cant.apply.symbol: kindname.constructor, T6840059, java.lang.Integer, java.lang.String, kindname.class, T6840059, null T6840059.java:15:9: compiler.err.cant.apply.symbol.1: kindname.constructor, T6840059, java.lang.Integer, java.lang.String, kindname.class, T6840059, (compiler.misc.no.conforming.assignment.exists: java.lang.String, java.lang.Integer)
T6840059.java:15:25: compiler.err.cant.apply.symbol: kindname.constructor, T6840059, java.lang.Integer, compiler.misc.no.args, kindname.class, T6840059, null T6840059.java:15:25: compiler.err.cant.apply.symbol.1: kindname.constructor, T6840059, java.lang.Integer, compiler.misc.no.args, kindname.class, T6840059, (compiler.misc.arg.length.mismatch)
2 errors 2 errors
T6857948.java:16:32: compiler.err.cant.resolve.location.args: kindname.method, nosuchfunction, , , kindname.class, Test T6857948.java:16:32: compiler.err.cant.resolve.location.args: kindname.method, nosuchfunction, , , kindname.class, Test
T6857948.java:16:50: compiler.err.cant.apply.symbol: kindname.constructor, Foo, java.lang.String, compiler.misc.no.args, kindname.class, Foo, null T6857948.java:16:50: compiler.err.cant.apply.symbol.1: kindname.constructor, Foo, java.lang.String, compiler.misc.no.args, kindname.class, Foo, (compiler.misc.arg.length.mismatch)
2 errors 2 errors
/**
* @test /nodynamiccopyright/
* @bug 6863465
* @summary javac doesn't detect circular subclass dependencies via qualified names
* @author Maurizio Cimadamore
* @compile/fail/ref=T6863465a.out -XDrawDiagnostics T6863465a.java
*/
class T6863465a {
static class a { static interface b {} }
static class c extends a implements z.y {}
static class x { static interface y {} }
static class z extends x implements c.b {}
}
T6863465a.java:11:12: compiler.err.cyclic.inheritance: T6863465a.c
1 error
/**
* @test /nodynamiccopyright/
* @bug 6863465
* @summary javac doesn't detect circular subclass dependencies via qualified names
* @author Maurizio Cimadamore
* @compile/fail/ref=T6863465b.out -XDrawDiagnostics T6863465b.java
*/
class T6863465b {
static class a { static interface b { static interface d {} } }
static class c extends a implements z.y, z.d {}
static class x { static interface y {} }
static class z extends x implements c.b {}
}
T6863465b.java:11:12: compiler.err.cyclic.inheritance: T6863465b.c
1 error
/**
* @test /nodynamiccopyright/
* @bug 6863465
* @summary javac doesn't detect circular subclass dependencies via qualified names
* @author Maurizio Cimadamore
* @compile/fail/ref=T6863465c.out -XDrawDiagnostics T6863465c.java
*/
class T6863465c {
static class x { static interface y {} }
static class z extends x implements c.b {}
static class a { static interface b { static interface d {} } }
static class c extends a implements z.y, z.d {}
}
T6863465c.java:13:47: compiler.err.cant.resolve.location: kindname.class, d, , , kindname.class, T6863465c.z
T6863465c.java:11:12: compiler.err.cyclic.inheritance: T6863465c.z
2 errors
/**
* @test /nodynamiccopyright/
* @bug 6863465
* @summary javac doesn't detect circular subclass dependencies via qualified names
* @author Maurizio Cimadamore
* @compile/fail/ref=T6863465d.out -XDrawDiagnostics T6863465d.java
*/
class T6863465d {
static class a { static interface b { static interface d {} } }
static class c extends a implements z.y, z.d {}
static class x { static interface y { static interface w {} } }
static class z extends x implements c.b, c.w {}
}
T6863465d.java:13:47: compiler.err.cant.resolve.location: kindname.class, w, , , kindname.class, T6863465d.c
T6863465d.java:11:12: compiler.err.cyclic.inheritance: T6863465d.c
2 errors
/*
* 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 6863465
* @summary javac doesn't detect circular subclass dependencies via qualified names
* @run main TestCircularClassfile
*/
import java.io.*;
import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import com.sun.source.util.JavacTask;
import java.util.EnumSet;
public class TestCircularClassfile {
enum ClassName {
A("A"),
B("B"),
C("C"),
OBJECT("Object");
String name;
ClassName(String name) {
this.name = name;
}
}
static class JavaSource extends SimpleJavaFileObject {
final static String sourceStub = "class #C extends #S {}";
String source;
public JavaSource(ClassName clazz, ClassName sup) {
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
source = sourceStub.replace("#C", clazz.name).replace("#S", sup.name);
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return source;
}
}
public static void main(String... args) throws Exception {
int count = 0;
for (ClassName clazz : EnumSet.of(ClassName.A, ClassName.B, ClassName.C)) {
for (ClassName sup : EnumSet.of(ClassName.A, ClassName.B, ClassName.C)) {
if (sup.ordinal() < clazz.ordinal()) continue;
check("sub_"+count++, clazz, sup);
}
}
}
static JavaSource[] initialSources = new JavaSource[] {
new JavaSource(ClassName.A, ClassName.OBJECT),
new JavaSource(ClassName.B, ClassName.A),
new JavaSource(ClassName.C, ClassName.B)
};
static String workDir = System.getProperty("user.dir");
static void check(String destPath, ClassName clazz, ClassName sup) throws Exception {
File destDir = new File(workDir, destPath); destDir.mkdir();
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask)tool.getTask(null, null, null,
Arrays.asList("-d", destPath), null, Arrays.asList(initialSources));
ct.generate();
File fileToRemove = new File(destPath, clazz.name + ".class");
fileToRemove.delete();
JavaSource newSource = new JavaSource(clazz, sup);
DiagnosticChecker checker = new DiagnosticChecker();
ct = (JavacTask)tool.getTask(null, null, checker,
Arrays.asList("-cp", destPath), null, Arrays.asList(newSource));
ct.analyze();
if (!checker.errorFound) {
throw new AssertionError(newSource.source);
}
}
static class DiagnosticChecker implements DiagnosticListener<JavaFileObject> {
boolean errorFound = false;
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
if (diagnostic.getKind() == Diagnostic.Kind.ERROR &&
diagnostic.getCode().equals("compiler.err.cyclic.inheritance")) {
errorFound = true;
}
}
}
}
...@@ -4,6 +4,6 @@ CyclicInheritance.java:20:1: compiler.err.cyclic.inheritance: I1 ...@@ -4,6 +4,6 @@ CyclicInheritance.java:20:1: compiler.err.cyclic.inheritance: I1
CyclicInheritance.java:22:1: compiler.err.cyclic.inheritance: I11 CyclicInheritance.java:22:1: compiler.err.cyclic.inheritance: I11
CyclicInheritance.java:27:1: compiler.err.cyclic.inheritance: C211 CyclicInheritance.java:27:1: compiler.err.cyclic.inheritance: C211
CyclicInheritance.java:31:1: compiler.err.cyclic.inheritance: C212 CyclicInheritance.java:31:1: compiler.err.cyclic.inheritance: C212
CyclicInheritance.java:36:27: compiler.err.report.access: C221.I, private, C221 CyclicInheritance.java:36:1: compiler.err.cyclic.inheritance: C221
CyclicInheritance.java:40:24: compiler.err.report.access: C222.C, private, C222 CyclicInheritance.java:40:1: compiler.err.cyclic.inheritance: C222
8 errors 8 errors
T6722234a.java:12:9: compiler.err.cant.apply.symbol: kindname.method, m, compiler.misc.type.var: T, 1, compiler.misc.type.var: T, 2, kindname.class, T6722234a<compiler.misc.type.var: T, 1>, null T6722234a.java:12:9: compiler.err.cant.apply.symbol.1: kindname.method, m, compiler.misc.type.var: T, 1, compiler.misc.type.var: T, 2, kindname.class, T6722234a<compiler.misc.type.var: T, 1>, (compiler.misc.no.conforming.assignment.exists: compiler.misc.type.var: T, 2, compiler.misc.type.var: T, 1)
1 error 1 error
T6722234a.java:12:9: compiler.err.cant.apply.symbol: kindname.method, m, compiler.misc.type.var: T, 1, compiler.misc.type.var: T, 2, kindname.class, T6722234a<compiler.misc.type.var: T, 1>, null T6722234a.java:12:9: compiler.err.cant.apply.symbol.1: kindname.method, m, compiler.misc.type.var: T, 1, compiler.misc.type.var: T, 2, kindname.class, T6722234a<compiler.misc.type.var: T, 1>, (compiler.misc.no.conforming.assignment.exists: compiler.misc.type.var: T, 2, compiler.misc.type.var: T, 1)
- compiler.misc.where.description.typevar.1: compiler.misc.type.var: T, 1,compiler.misc.type.var: T, 2,{(compiler.misc.where.typevar: compiler.misc.type.var: T, 1, java.lang.String, kindname.class, T6722234a),(compiler.misc.where.typevar: compiler.misc.type.var: T, 2, java.lang.Integer, kindname.method, <compiler.misc.type.var: T, 2>test(compiler.misc.type.var: T, 2))} - compiler.misc.where.description.typevar.1: compiler.misc.type.var: T, 1,compiler.misc.type.var: T, 2,{(compiler.misc.where.typevar: compiler.misc.type.var: T, 1, java.lang.String, kindname.class, T6722234a),(compiler.misc.where.typevar: compiler.misc.type.var: T, 2, java.lang.Integer, kindname.method, <compiler.misc.type.var: T, 2>test(compiler.misc.type.var: T, 2))}
1 error 1 error
T6722234b.java:16:9: compiler.err.cant.apply.symbol: kindname.method, m, List<T>,List<T>, List<compiler.misc.type.captureof: 1, ? extends T6722234b>,List<compiler.misc.type.captureof: 2, ? extends T6722234b>, kindname.class, T6722234b, null T6722234b.java:16:9: compiler.err.cant.apply.symbol.1: kindname.method, m, List<T>,List<T>, List<compiler.misc.type.captureof: 1, ? extends T6722234b>,List<compiler.misc.type.captureof: 2, ? extends T6722234b>, kindname.class, T6722234b, (compiler.misc.infer.no.conforming.assignment.exists: T, List<compiler.misc.type.captureof: 2, ? extends T6722234b>, List<T>)
1 error 1 error
T6722234b.java:16:9: compiler.err.cant.apply.symbol: kindname.method, m, List<T>,List<T>, List<compiler.misc.captured.type: 1>,List<compiler.misc.captured.type: 2>, kindname.class, T6722234b, null T6722234b.java:16:9: compiler.err.cant.apply.symbol.1: kindname.method, m, List<T>,List<T>, List<compiler.misc.captured.type: 1>,List<compiler.misc.captured.type: 2>, kindname.class, T6722234b, (compiler.misc.infer.no.conforming.assignment.exists: T, List<compiler.misc.captured.type: 2>, List<T>)
- compiler.misc.where.description.typevar: T,{(compiler.misc.where.typevar: T, Object, kindname.method, <T>m(List<T>,List<T>))} - compiler.misc.where.description.typevar: T,{(compiler.misc.where.typevar: T, Object, kindname.method, <T>m(List<T>,List<T>))}
- compiler.misc.where.description.captured.1: compiler.misc.captured.type: 1,compiler.misc.captured.type: 2,{(compiler.misc.where.captured.1: compiler.misc.captured.type: 1, T6722234b, compiler.misc.type.null, ? extends T6722234b),(compiler.misc.where.captured.1: compiler.misc.captured.type: 2, T6722234b, compiler.misc.type.null, ? extends T6722234b)} - compiler.misc.where.description.captured.1: compiler.misc.captured.type: 1,compiler.misc.captured.type: 2,{(compiler.misc.where.captured.1: compiler.misc.captured.type: 1, T6722234b, compiler.misc.type.null, ? extends T6722234b),(compiler.misc.where.captured.1: compiler.misc.captured.type: 2, T6722234b, compiler.misc.type.null, ? extends T6722234b)}
1 error 1 error
T6722234c.java:14:9: compiler.err.cant.apply.symbol: kindname.method, m, T6722234c.String, java.lang.String, kindname.class, T6722234c, null T6722234c.java:14:9: compiler.err.cant.apply.symbol.1: kindname.method, m, T6722234c.String, java.lang.String, kindname.class, T6722234c, (compiler.misc.infer.no.conforming.assignment.exists: T, java.lang.String, T6722234c.String)
1 error 1 error
T6799605.java:17:9: compiler.err.cant.resolve.location.args: kindname.method, m, , T6799605<compiler.misc.type.captureof: 1, ?>, kindname.class, T6799605<X> T6799605.java:17:9: compiler.err.cant.apply.symbols: kindname.method, m, T6799605<compiler.misc.type.captureof: 1, ?>,{(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>,T6799605<T>,T6799605<T>), (compiler.misc.infer.arg.length.mismatch)),(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>,T6799605<T>), (compiler.misc.infer.arg.length.mismatch)),(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>), (compiler.misc.inferred.do.not.conform.to.bounds: compiler.misc.type.captureof: 1, ?, T6799605<compiler.misc.type.captureof: 1, ?>))}
T6799605.java:18:9: compiler.err.cant.resolve.location.args: kindname.method, m, , T6799605<compiler.misc.type.captureof: 1, ?>,T6799605<compiler.misc.type.captureof: 2, ?>, kindname.class, T6799605<X> T6799605.java:18:9: compiler.err.cant.apply.symbols: kindname.method, m, T6799605<compiler.misc.type.captureof: 1, ?>,T6799605<compiler.misc.type.captureof: 2, ?>,{(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>,T6799605<T>,T6799605<T>), (compiler.misc.infer.arg.length.mismatch)),(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>,T6799605<T>), (compiler.misc.infer.no.conforming.assignment.exists: T, T6799605<compiler.misc.type.captureof: 2, ?>, T6799605<T>)),(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>), (compiler.misc.infer.arg.length.mismatch))}
T6799605.java:19:9: compiler.err.cant.resolve.location.args: kindname.method, m, , T6799605<compiler.misc.type.captureof: 1, ?>,T6799605<compiler.misc.type.captureof: 2, ?>,T6799605<compiler.misc.type.captureof: 3, ?>, kindname.class, T6799605<X> T6799605.java:19:9: compiler.err.cant.apply.symbols: kindname.method, m, T6799605<compiler.misc.type.captureof: 1, ?>,T6799605<compiler.misc.type.captureof: 2, ?>,T6799605<compiler.misc.type.captureof: 3, ?>,{(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>,T6799605<T>,T6799605<T>), (compiler.misc.infer.no.conforming.assignment.exists: T, T6799605<compiler.misc.type.captureof: 2, ?>, T6799605<T>)),(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>,T6799605<T>), (compiler.misc.infer.arg.length.mismatch)),(compiler.misc.inapplicable.method: kindname.method, T6799605, <T>m(T6799605<T>), (compiler.misc.infer.arg.length.mismatch))}
3 errors 3 errors
T6862608a.java:19:41: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.no.conforming.instance.exists: T, java.util.Comparator<T>, java.util.Comparator<java.lang.String>)), <T>java.util.Comparator<T>, java.util.Comparator<java.lang.String> T6862608a.java:19:41: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.infer.no.conforming.instance.exists: T, java.util.Comparator<T>, java.util.Comparator<java.lang.String>)), <T>java.util.Comparator<T>, java.util.Comparator<java.lang.String>
- compiler.misc.where.description.typevar: T,{(compiler.misc.where.typevar: T, java.lang.Object, kindname.method, <T>compound(java.lang.Iterable<? extends java.util.Comparator<? super T>>))} - compiler.misc.where.description.typevar: T,{(compiler.misc.where.typevar: T, java.lang.Object, kindname.method, <T>compound(java.lang.Iterable<? extends java.util.Comparator<? super T>>))}
1 error 1 error
T6862608b.java:11:7: compiler.err.cant.apply.symbol: kindname.method, test, compiler.misc.type.var: T, 1, compiler.misc.type.var: T, 2, kindname.class, T66862608b<compiler.misc.type.var: T, 1,compiler.misc.type.var: S, 2>, null T6862608b.java:11:7: compiler.err.cant.apply.symbol.1: kindname.method, test, compiler.misc.type.var: T, 1, compiler.misc.type.var: T, 2, kindname.class, T66862608b<compiler.misc.type.var: T, 1,compiler.misc.type.var: S, 2>, (compiler.misc.no.conforming.assignment.exists: compiler.misc.type.var: T, 2, compiler.misc.type.var: T, 1)
- compiler.misc.where.description.typevar.1: compiler.misc.type.var: T, 1,compiler.misc.type.var: T, 2,compiler.misc.type.var: S, 1,compiler.misc.type.var: S, 2,{(compiler.misc.where.typevar: compiler.misc.type.var: T, 1, java.lang.String, kindname.class, T66862608b),(compiler.misc.where.typevar: compiler.misc.type.var: T, 2, compiler.misc.type.var: S, 1, kindname.method, <compiler.misc.type.var: S, 1,compiler.misc.type.var: T, 2>foo(compiler.misc.type.var: T, 2)),(compiler.misc.where.typevar: compiler.misc.type.var: S, 1, java.lang.Object, kindname.method, <compiler.misc.type.var: S, 1,compiler.misc.type.var: T, 2>foo(compiler.misc.type.var: T, 2)),(compiler.misc.where.typevar: compiler.misc.type.var: S, 2, java.lang.Object, kindname.class, T66862608b)} - compiler.misc.where.description.typevar.1: compiler.misc.type.var: T, 1,compiler.misc.type.var: T, 2,compiler.misc.type.var: S, 1,compiler.misc.type.var: S, 2,{(compiler.misc.where.typevar: compiler.misc.type.var: T, 1, java.lang.String, kindname.class, T66862608b),(compiler.misc.where.typevar: compiler.misc.type.var: T, 2, compiler.misc.type.var: S, 1, kindname.method, <compiler.misc.type.var: S, 1,compiler.misc.type.var: T, 2>foo(compiler.misc.type.var: T, 2)),(compiler.misc.where.typevar: compiler.misc.type.var: S, 1, java.lang.Object, kindname.method, <compiler.misc.type.var: S, 1,compiler.misc.type.var: T, 2>foo(compiler.misc.type.var: T, 2)),(compiler.misc.where.typevar: compiler.misc.type.var: S, 2, java.lang.Object, kindname.class, T66862608b)}
1 error 1 error
NameCollision.java:13:31: compiler.err.intf.expected.here NameCollision.java:13:31: compiler.err.intf.expected.here
1 error NameCollision.java:13:5: compiler.err.cyclic.inheritance: NameCollision.Runnable
2 errors
T6326754.java:44:12: compiler.err.name.clash.same.erasure: TestConstructor(T), TestConstructor(K) T6326754.java:44:12: compiler.err.name.clash.same.erasure: TestConstructor(T), TestConstructor(K)
T6326754.java:52:17: compiler.err.name.clash.same.erasure: setT(K), setT(T) T6326754.java:52:17: compiler.err.name.clash.same.erasure: setT(K), setT(T)
T6326754.java:64:18: compiler.err.prob.found.req: (compiler.misc.incompatible.types), T, T T6326754.java:64:18: compiler.err.prob.found.req: (compiler.misc.incompatible.types), T, T
T6326754.java:70:11: compiler.err.cant.apply.symbol: kindname.method, setT, java.lang.Object, compiler.misc.no.args, kindname.class, TestC<T>, null T6326754.java:70:11: compiler.err.cant.apply.symbol.1: kindname.method, setT, java.lang.Object, compiler.misc.no.args, kindname.class, TestC<T>, (compiler.misc.arg.length.mismatch)
- compiler.note.unchecked.filename: T6326754.java - compiler.note.unchecked.filename: T6326754.java
- compiler.note.unchecked.recompile - compiler.note.unchecked.recompile
4 errors 4 errors
/*
* 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 6587674
* @summary NoClassdefFound when anonymously extending a class.
*/
import java.util.Vector;
public class T6587674 {
private static final Vector<String> list =
true ? null : new Vector<String>() { };
public static void main(String[] args) {
System.out.println("T6587674 runs fine!");
}
}
/* /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -31,8 +31,8 @@ ...@@ -31,8 +31,8 @@
*/ */
import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.parser.*; // XXX import com.sun.tools.javac.parser.*;
import com.sun.tools.javac.util.*; // XXX import com.sun.tools.javac.util.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.nio.*; import java.nio.*;
...@@ -65,7 +65,7 @@ public class TestJavacTaskScanner extends ToolTester { ...@@ -65,7 +65,7 @@ public class TestJavacTaskScanner extends ToolTester {
fm.getJavaFileObjects(new File[] {file}); fm.getJavaFileObjects(new File[] {file});
StandardJavaFileManager fm = getLocalFileManager(tool, null, null); StandardJavaFileManager fm = getLocalFileManager(tool, null, null);
task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, compilationUnits); task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, compilationUnits);
task.getContext().put(Scanner.Factory.scannerFactoryKey, task.getContext().put(ScannerFactory.scannerFactoryKey,
new MyScanner.Factory(task.getContext(), this)); new MyScanner.Factory(task.getContext(), this));
elements = task.getElements(); elements = task.getElements();
types = task.getTypes(); types = task.getTypes();
...@@ -170,34 +170,36 @@ public class TestJavacTaskScanner extends ToolTester { ...@@ -170,34 +170,36 @@ public class TestJavacTaskScanner extends ToolTester {
class MyScanner extends Scanner { class MyScanner extends Scanner {
public static class Factory extends Scanner.Factory { public static class Factory extends ScannerFactory {
public Factory(Context context, TestJavacTaskScanner test) { public Factory(Context context, TestJavacTaskScanner test) {
super(context); super(context);
this.test = test; this.test = test;
} }
@Override @Override
public Scanner newScanner(CharSequence input) { public Scanner newScanner(CharSequence input, boolean keepDocComments) {
assert !keepDocComments;
if (input instanceof CharBuffer) { if (input instanceof CharBuffer) {
return new MyScanner(this, (CharBuffer)input, test); return new MyScanner(this, (CharBuffer)input, test);
} else { } else {
char[] array = input.toString().toCharArray(); char[] array = input.toString().toCharArray();
return newScanner(array, array.length); return newScanner(array, array.length, keepDocComments);
} }
} }
@Override @Override
public Scanner newScanner(char[] input, int inputLength) { public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) {
assert !keepDocComments;
return new MyScanner(this, input, inputLength, test); return new MyScanner(this, input, inputLength, test);
} }
private TestJavacTaskScanner test; private TestJavacTaskScanner test;
} }
protected MyScanner(Factory fac, CharBuffer buffer, TestJavacTaskScanner test) { protected MyScanner(ScannerFactory fac, CharBuffer buffer, TestJavacTaskScanner test) {
super(fac, buffer); super(fac, buffer);
this.test = test; this.test = test;
} }
protected MyScanner(Factory fac, char[] input, int inputLength, TestJavacTaskScanner test) { protected MyScanner(ScannerFactory fac, char[] input, int inputLength, TestJavacTaskScanner test) {
super(fac, input, inputLength); super(fac, input, inputLength);
this.test = test; this.test = test;
} }
......
...@@ -401,7 +401,7 @@ class Example implements Comparable<Example> { ...@@ -401,7 +401,7 @@ class Example implements Comparable<Example> {
} }
} }
for (JCDiagnostic sd: d.getSubdiagnostics()) for (JCDiagnostic sd: d.getSubdiagnostics())
scanForKeys(d, keys); scanForKeys(sd, keys);
} }
} }
......
...@@ -3,7 +3,7 @@ compiler.err.already.defined.this.unit # seems to be masked by ...@@ -3,7 +3,7 @@ compiler.err.already.defined.this.unit # seems to be masked by
compiler.err.annotation.value.not.allowable.type # cannot happen: precluded by complete type-specific tests compiler.err.annotation.value.not.allowable.type # cannot happen: precluded by complete type-specific tests
compiler.err.assignment.from.super-bound # DEAD compiler.err.assignment.from.super-bound # DEAD
compiler.err.assignment.to.extends-bound # DEAD compiler.err.assignment.to.extends-bound # DEAD
compiler.err.cant.apply.symbol.1 compiler.err.cant.apply.symbol
compiler.err.cant.read.file # (apt.JavaCompiler?) compiler.err.cant.read.file # (apt.JavaCompiler?)
compiler.err.cant.select.static.class.from.param.type compiler.err.cant.select.static.class.from.param.type
compiler.err.illegal.char.for.encoding compiler.err.illegal.char.for.encoding
...@@ -43,7 +43,6 @@ compiler.err.undetermined.type ...@@ -43,7 +43,6 @@ compiler.err.undetermined.type
compiler.err.unexpected.type compiler.err.unexpected.type
compiler.err.unknown.enum.constant # in bad class file compiler.err.unknown.enum.constant # in bad class file
compiler.err.unsupported.cross.fp.lit # Scanner: host system dependent compiler.err.unsupported.cross.fp.lit # Scanner: host system dependent
compiler.misc.arg.length.mismatch
compiler.misc.assignment.from.super-bound compiler.misc.assignment.from.super-bound
compiler.misc.assignment.to.extends-bound compiler.misc.assignment.to.extends-bound
compiler.misc.bad.class.file.header # bad class file compiler.misc.bad.class.file.header # bad class file
...@@ -73,7 +72,6 @@ compiler.misc.kindname.static ...@@ -73,7 +72,6 @@ compiler.misc.kindname.static
compiler.misc.kindname.type.variable compiler.misc.kindname.type.variable
compiler.misc.kindname.type.variable.bound compiler.misc.kindname.type.variable.bound
compiler.misc.kindname.value compiler.misc.kindname.value
compiler.misc.no.conforming.assignment.exists
compiler.misc.non.denotable.type compiler.misc.non.denotable.type
compiler.misc.no.unique.minimal.instance.exists compiler.misc.no.unique.minimal.instance.exists
compiler.misc.resume.abort # prompt for a response compiler.misc.resume.abort # prompt for a response
......
/*
* 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.
*/
// key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.explicit.param.do.not.conform.to.bounds
class ExplicitParamsDoNotConformToBounds {
<X extends Number> void m() {}
{ this.<String>m(); }
}
/*
* 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.
*/
// key: compiler.err.cant.apply.symbols
// key: compiler.misc.arg.length.mismatch
// key: compiler.misc.inapplicable.method
class ExplicitParamsDoNotConformToBounds {
void m(int i1) {}
void m(int i1, int i2) {}
{ this.m(); }
}
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
*/ */
// key: compiler.misc.incompatible.types.1 // key: compiler.misc.incompatible.types.1
// key: compiler.misc.no.conforming.instance.exists // key: compiler.misc.infer.no.conforming.instance.exists
// key: compiler.err.prob.found.req // key: compiler.err.prob.found.req
class IncompatibleTypes1<V> { class IncompatibleTypes1<V> {
......
/*
* 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.
*/
// key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.infer.arg.length.mismatch
class InferArgsLengthMismatch {
<X extends Number> void m(X x1, X x2) {}
{ this.m(1); }
}
...@@ -24,7 +24,9 @@ ...@@ -24,7 +24,9 @@
// key: compiler.misc.kindname.constructor // key: compiler.misc.kindname.constructor
// key: compiler.misc.kindname.class // key: compiler.misc.kindname.class
// key: compiler.misc.no.args // key: compiler.misc.no.args
// key: compiler.err.cant.apply.symbol // key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.arg.length.mismatch
// key: compiler.misc.no.conforming.assignment.exists
// key: compiler.misc.count.error.plural // key: compiler.misc.count.error.plural
// run: backdoor // run: backdoor
......
...@@ -22,7 +22,8 @@ ...@@ -22,7 +22,8 @@
*/ */
// key: compiler.misc.no.args // key: compiler.misc.no.args
// key: compiler.err.cant.apply.symbol // key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.arg.length.mismatch
// run: simple // run: simple
class X { class X {
......
/*
* 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.
*/
// key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.varargs.argument.mismatch
class VarargsArgumentMismatch {
void m(String s, Integer... is) {}
{ this.m("1", "2", "3"); }
}
...@@ -25,7 +25,8 @@ ...@@ -25,7 +25,8 @@
// key: compiler.misc.where.description.captured.1 // key: compiler.misc.where.description.captured.1
// key: compiler.misc.where.description.typevar // key: compiler.misc.where.description.typevar
// key: compiler.misc.where.typevar // key: compiler.misc.where.typevar
// key: compiler.err.cant.apply.symbol // key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.infer.no.conforming.assignment.exists
// key: compiler.misc.captured.type // key: compiler.misc.captured.type
// options: -XDdiags=where,simpleNames // options: -XDdiags=where,simpleNames
// run: simple // run: simple
......
...@@ -25,7 +25,8 @@ ...@@ -25,7 +25,8 @@
// key: compiler.misc.where.description.captured.1 // key: compiler.misc.where.description.captured.1
// key: compiler.misc.where.description.typevar // key: compiler.misc.where.description.typevar
// key: compiler.misc.where.typevar // key: compiler.misc.where.typevar
// key: compiler.err.cant.apply.symbol // key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.infer.no.conforming.assignment.exists
// key: compiler.misc.captured.type // key: compiler.misc.captured.type
// key: compiler.misc.type.null // key: compiler.misc.type.null
// options: -XDdiags=where,simpleNames // options: -XDdiags=where,simpleNames
......
...@@ -24,7 +24,8 @@ ...@@ -24,7 +24,8 @@
// key: compiler.misc.where.typevar // key: compiler.misc.where.typevar
// key: compiler.misc.where.description.typevar.1 // key: compiler.misc.where.description.typevar.1
// key: compiler.misc.type.var // key: compiler.misc.type.var
// key: compiler.err.cant.apply.symbol // key: compiler.err.cant.apply.symbol.1
// key: compiler.misc.no.conforming.assignment.exists
// options: -XDdiags=where,disambiguateTvars // options: -XDdiags=where,disambiguateTvars
// run: simple // run: simple
......
Neg06.java:18:36: compiler.err.cant.apply.diamond.1: (compiler.misc.diamond: Neg06.IFoo), (compiler.misc.no.conforming.instance.exists: X, Neg06.IFoo<X>, Neg06.ISuperFoo<java.lang.String>) Neg06.java:18:36: compiler.err.cant.apply.diamond.1: (compiler.misc.diamond: Neg06.IFoo), (compiler.misc.infer.no.conforming.instance.exists: X, Neg06.IFoo<X>, Neg06.ISuperFoo<java.lang.String>)
Neg06.java:19:37: compiler.err.cant.apply.diamond.1: (compiler.misc.diamond: Neg06.CFoo), (compiler.misc.no.conforming.instance.exists: X, Neg06.CFoo<X>, Neg06.CSuperFoo<java.lang.String>) Neg06.java:19:37: compiler.err.cant.apply.diamond.1: (compiler.misc.diamond: Neg06.CFoo), (compiler.misc.infer.no.conforming.instance.exists: X, Neg06.CFoo<X>, Neg06.CSuperFoo<java.lang.String>)
Neg06.java:20:37: compiler.err.cant.apply.diamond.1: (compiler.misc.diamond: Neg06.CFoo), (compiler.misc.no.conforming.instance.exists: X, Neg06.CFoo<X>, Neg06.CSuperFoo<java.lang.String>) Neg06.java:20:37: compiler.err.cant.apply.diamond.1: (compiler.misc.diamond: Neg06.CFoo), (compiler.misc.infer.no.conforming.instance.exists: X, Neg06.CFoo<X>, Neg06.CSuperFoo<java.lang.String>)
3 errors 3 errors
T6315770.java:16:42: compiler.err.undetermined.type.1: <T>T6315770<T>, (compiler.misc.no.unique.maximal.instance.exists: T, java.lang.String,java.lang.Integer,java.lang.Runnable) T6315770.java:16:42: compiler.err.undetermined.type.1: <T>T6315770<T>, (compiler.misc.no.unique.maximal.instance.exists: T, java.lang.String,java.lang.Integer,java.lang.Runnable)
T6315770.java:17:40: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.no.conforming.instance.exists: T, T6315770<T>, T6315770<? super java.lang.String>)), <T>T6315770<T>, T6315770<? super java.lang.String> T6315770.java:17:40: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.infer.no.conforming.instance.exists: T, T6315770<T>, T6315770<? super java.lang.String>)), <T>T6315770<T>, T6315770<? super java.lang.String>
2 errors 2 errors
T6611449.java:18:9: compiler.err.cant.resolve.location.args: kindname.constructor, T6611449, , int, kindname.class, T6611449<S> T6611449.java:18:9: compiler.err.cant.apply.symbols: kindname.constructor, T6611449, int,{(compiler.misc.inapplicable.method: kindname.constructor, T6611449, <T>T6611449(T,T), (compiler.misc.infer.arg.length.mismatch)),(compiler.misc.inapplicable.method: kindname.constructor, T6611449, <T>T6611449(T), (compiler.misc.inferred.do.not.conform.to.bounds: java.lang.Integer, S))}
T6611449.java:19:9: compiler.err.cant.resolve.location.args: kindname.constructor, T6611449, , int,int, kindname.class, T6611449<S> T6611449.java:19:9: compiler.err.cant.apply.symbols: kindname.constructor, T6611449, int,int,{(compiler.misc.inapplicable.method: kindname.constructor, T6611449, <T>T6611449(T,T), (compiler.misc.inferred.do.not.conform.to.bounds: java.lang.Integer, S)),(compiler.misc.inapplicable.method: kindname.constructor, T6611449, <T>T6611449(T), (compiler.misc.infer.arg.length.mismatch))}
T6611449.java:20:9: compiler.err.cant.apply.symbol: kindname.method, m1, T, int, kindname.class, T6611449<S>, null T6611449.java:20:9: compiler.err.cant.apply.symbol.1: kindname.method, m1, T, int, kindname.class, T6611449<S>, (compiler.misc.inferred.do.not.conform.to.bounds: java.lang.Integer, S)
T6611449.java:21:9: compiler.err.cant.apply.symbol: kindname.method, m2, T,T, int,int, kindname.class, T6611449<S>, null T6611449.java:21:9: compiler.err.cant.apply.symbol.1: kindname.method, m2, T,T, int,int, kindname.class, T6611449<S>, (compiler.misc.inferred.do.not.conform.to.bounds: java.lang.Integer, S)
4 errors 4 errors
T6638712a.java:16:41: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.no.conforming.instance.exists: T, java.util.Comparator<T>, java.util.Comparator<java.lang.String>)), <T>java.util.Comparator<T>, java.util.Comparator<java.lang.String> T6638712a.java:16:41: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.infer.no.conforming.instance.exists: T, java.util.Comparator<T>, java.util.Comparator<java.lang.String>)), <T>java.util.Comparator<T>, java.util.Comparator<java.lang.String>
1 error 1 error
T6638712b.java:14:21: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.no.conforming.instance.exists: T, T, java.lang.String)), <T>T, java.lang.String T6638712b.java:14:21: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.infer.no.conforming.instance.exists: T, T, java.lang.String)), <T>T, java.lang.String
1 error 1 error
T6638712c.java:16:9: compiler.err.cant.apply.symbol: kindname.method, sort, T[],java.util.Comparator<? super T>, java.lang.Enum[],java.util.Comparator<java.lang.Enum<?>>, kindname.class, T6638712c, null T6638712c.java:16:9: compiler.err.cant.apply.symbol.1: kindname.method, sort, T[],java.util.Comparator<? super T>, java.lang.Enum[],java.util.Comparator<java.lang.Enum<?>>, kindname.class, T6638712c, (compiler.misc.inferred.do.not.conform.to.params: java.lang.Enum[],java.util.Comparator<? super java.lang.Enum>, java.lang.Enum[],java.util.Comparator<java.lang.Enum<?>>)
1 error 1 error
T6638712d.java:16:9: compiler.err.cant.apply.symbol: kindname.method, m, U,java.util.List<java.util.List<U>>, int,java.util.List<java.util.List<java.lang.String>>, kindname.class, T6638712d, null T6638712d.java:16:9: compiler.err.cant.apply.symbol.1: kindname.method, m, U,java.util.List<java.util.List<U>>, int,java.util.List<java.util.List<java.lang.String>>, kindname.class, T6638712d, (compiler.misc.inferred.do.not.conform.to.params: java.lang.String,java.util.List<java.util.List<java.lang.String>>, int,java.util.List<java.util.List<java.lang.String>>)
1 error 1 error
T6638712e.java:17:27: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.no.conforming.instance.exists: X, T6638712e.Foo<X,java.lang.String>, T6638712e.Foo<java.lang.Object,java.lang.String>)), <X>T6638712e.Foo<X,java.lang.String>, T6638712e.Foo<java.lang.Object,java.lang.String> T6638712e.java:17:27: compiler.err.prob.found.req: (compiler.misc.incompatible.types.1: (compiler.misc.infer.no.conforming.instance.exists: X, T6638712e.Foo<X,java.lang.String>, T6638712e.Foo<java.lang.Object,java.lang.String>)), <X>T6638712e.Foo<X,java.lang.String>, T6638712e.Foo<java.lang.Object,java.lang.String>
1 error 1 error
/*
* 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.
*/
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import static javax.lang.model.SourceVersion.*;
import javax.lang.model.element.*;
import javax.lang.model.util.*;
/**
* An abstract annotation processor tailored to javac regression testing.
*/
public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
private static final Set<String> allAnnotations;
static {
Set<String> tmp = new HashSet<>();
tmp.add("*");
allAnnotations = Collections.unmodifiableSet(tmp);
}
protected Elements eltUtils;
protected Elements elements;
protected Types typeUtils;
protected Types types;
protected Filer filer;
protected Messager messager;
protected Map<String, String> options;
/**
* Constructor for subclasses to call.
*/
protected JavacTestingAbstractProcessor() {
super();
}
/**
* Return the latest source version. Unless this method is
* overridden, an {@code IllegalStateException} will be thrown if a
* subclass has a {@code SupportedSourceVersion} annotation.
*/
@Override
public SourceVersion getSupportedSourceVersion() {
SupportedSourceVersion ssv = this.getClass().getAnnotation(SupportedSourceVersion.class);
if (ssv != null)
throw new IllegalStateException("SupportedSourceVersion annotation not supported here.");
return SourceVersion.latest();
}
/**
* If the processor class is annotated with {@link
* SupportedAnnotationTypes}, return an unmodifiable set with the
* same set of strings as the annotation. If the class is not so
* annotated, a one-element set containing {@code "*"} is returned
* to indicate all annotations are processed.
*
* @return the names of the annotation types supported by this
* processor, or an empty set if none
*/
@Override
public Set<String> getSupportedAnnotationTypes() {
SupportedAnnotationTypes sat = this.getClass().getAnnotation(SupportedAnnotationTypes.class);
if (sat != null)
return super.getSupportedAnnotationTypes();
else
return allAnnotations;
}
@Override
public void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
elements = eltUtils = processingEnv.getElementUtils();
types = typeUtils = processingEnv.getTypeUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
options = processingEnv.getOptions();
}
}
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -27,10 +27,8 @@ import javax.annotation.processing.*; ...@@ -27,10 +27,8 @@ import javax.annotation.processing.*;
import javax.lang.model.*; import javax.lang.model.*;
import javax.lang.model.element.*; import javax.lang.model.element.*;
@SupportedAnnotationTypes("*") public class A extends JavacTestingAbstractProcessor {
public class A extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) { public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) {
Filer filer = processingEnv.getFiler();
try { try {
OutputStream out = filer.createClassFile(getClass().getName()+"_0").openOutputStream(); OutputStream out = filer.createClassFile(getClass().getName()+"_0").openOutputStream();
out.close(); out.close();
...@@ -39,8 +37,4 @@ public class A extends AbstractProcessor { ...@@ -39,8 +37,4 @@ public class A extends AbstractProcessor {
} }
return true; return true;
} }
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
} }
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,7 +25,8 @@ ...@@ -25,7 +25,8 @@
* @test * @test
* @bug 6441871 * @bug 6441871
* @summary javac crashes at com.sun.tools.javac.jvm.ClassReader$BadClassFile * @summary javac crashes at com.sun.tools.javac.jvm.ClassReader$BadClassFile
* @build A * @library ../../lib
* @build JavacTestingAbstractProcessor A
* @run main T6348499 * @run main T6348499
*/ */
...@@ -54,7 +55,6 @@ public class T6348499 { ...@@ -54,7 +55,6 @@ public class T6348499 {
fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "A.java"))); fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "A.java")));
Iterable<String> opts = Arrays.asList("-proc:only", Iterable<String> opts = Arrays.asList("-proc:only",
"-processor", "A", "-processor", "A",
"-source", "1.6",
"-processorpath", testClasses); "-processorpath", testClasses);
StringWriter out = new StringWriter(); StringWriter out = new StringWriter();
JavacTask task = tool.getTask(out, fm, dl, opts, null, files); JavacTask task = tool.getTask(out, fm, dl, opts, null, files);
......
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -26,6 +26,8 @@ ...@@ -26,6 +26,8 @@
* @bug 6359313 * @bug 6359313
* @summary error compiling annotated package * @summary error compiling annotated package
* @author Peter von der Ah\u00e9 * @author Peter von der Ah\u00e9
* @library ../../lib
* @build JavacTestingAbstractProcessor
* @compile T6359313.java * @compile T6359313.java
* @compile -processor T6359313 package-info.java Foo.java * @compile -processor T6359313 package-info.java Foo.java
*/ */
...@@ -37,7 +39,7 @@ import javax.annotation.processing.SupportedAnnotationTypes; ...@@ -37,7 +39,7 @@ import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeElement;
@SupportedAnnotationTypes("Foo") @SupportedAnnotationTypes("Foo")
public class T6359313 extends AbstractProcessor { public class T6359313 extends JavacTestingAbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) { RoundEnvironment roundEnvironment) {
return true; return true;
......
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -31,13 +31,11 @@ import static javax.tools.Diagnostic.Kind.*; ...@@ -31,13 +31,11 @@ import static javax.tools.Diagnostic.Kind.*;
/** /**
* Second of several processors to run. * Second of several processors to run.
*/ */
@SupportedAnnotationTypes("*") public class ProcBar extends JavacTestingAbstractProcessor {
public class ProcBar extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) { RoundEnvironment roundEnvironment) {
if (!roundEnvironment.processingOver()) if (!roundEnvironment.processingOver())
processingEnv.getMessager().printMessage(NOTE, messager.printMessage(NOTE, "Hello from ProcBar");
"Hello from ProcBar");
return false; return false;
} }
} }
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -31,13 +31,11 @@ import static javax.tools.Diagnostic.Kind.*; ...@@ -31,13 +31,11 @@ import static javax.tools.Diagnostic.Kind.*;
/** /**
* First of several processors to run. * First of several processors to run.
*/ */
@SupportedAnnotationTypes("*") public class ProcFoo extends JavacTestingAbstractProcessor {
public class ProcFoo extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) { RoundEnvironment roundEnvironment) {
if (!roundEnvironment.processingOver()) if (!roundEnvironment.processingOver())
processingEnv.getMessager().printMessage(NOTE, messager.printMessage(NOTE, "Hello from ProcFoo");
"Hello from ProcFoo");
return false; return false;
} }
} }
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -26,6 +26,8 @@ ...@@ -26,6 +26,8 @@
* @bug 6365040 6358129 * @bug 6365040 6358129
* @summary Test -processor foo,bar,baz * @summary Test -processor foo,bar,baz
* @author Joseph D. Darcy * @author Joseph D. Darcy
* @library ../../lib
* @build JavacTestingAbstractProcessor
* @compile ProcFoo.java * @compile ProcFoo.java
* @compile ProcBar.java * @compile ProcBar.java
* @compile T6365040.java * @compile T6365040.java
...@@ -43,13 +45,11 @@ import javax.annotation.processing.SupportedAnnotationTypes; ...@@ -43,13 +45,11 @@ import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeElement;
import static javax.tools.Diagnostic.Kind.*; import static javax.tools.Diagnostic.Kind.*;
@SupportedAnnotationTypes("*") public class T6365040 extends JavacTestingAbstractProcessor {
public class T6365040 extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) { RoundEnvironment roundEnvironment) {
if (!roundEnvironment.processingOver()) if (!roundEnvironment.processingOver())
processingEnv.getMessager().printMessage(NOTE, messager.printMessage(NOTE, "Hello from T6365040");
"Hello from T6365040");
return true; return true;
} }
} }
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -26,6 +26,8 @@ ...@@ -26,6 +26,8 @@
* @bug 6413690 6380018 * @bug 6413690 6380018
* @summary JavacProcessingEnvironment does not enter trees from preceding rounds * @summary JavacProcessingEnvironment does not enter trees from preceding rounds
* @author Peter von der Ah\u00e9 * @author Peter von der Ah\u00e9
* @library ../../lib
* @build JavacTestingAbstractProcessor
* @compile T6413690.java * @compile T6413690.java
* @compile -XDfatalEnterError -verbose -processor T6413690 src/Super.java TestMe.java * @compile -XDfatalEnterError -verbose -processor T6413690 src/Super.java TestMe.java
*/ */
...@@ -42,11 +44,9 @@ import javax.lang.model.element.TypeElement; ...@@ -42,11 +44,9 @@ import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements; import javax.lang.model.util.Elements;
@SupportedAnnotationTypes("TestMe") @SupportedAnnotationTypes("TestMe")
public class T6413690 extends AbstractProcessor { public class T6413690 extends JavacTestingAbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) { RoundEnvironment roundEnvironment) {
Elements elements = processingEnv.getElementUtils();
Filer filer = processingEnv.getFiler();
TypeElement testMe = elements.getTypeElement(TestMe.class.getName()); TypeElement testMe = elements.getTypeElement(TestMe.class.getName());
Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe); Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe);
try { try {
......
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -29,9 +29,8 @@ import javax.lang.model.*; ...@@ -29,9 +29,8 @@ import javax.lang.model.*;
import javax.lang.model.element.*; import javax.lang.model.element.*;
import javax.tools.*; import javax.tools.*;
@SupportedAnnotationTypes("*") @SuppressWarnings("")
public class A extends AbstractProcessor { public class A extends JavacTestingAbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Messager m = processingEnv.getMessager(); Messager m = processingEnv.getMessager();
for (TypeElement anno: annotations) { for (TypeElement anno: annotations) {
...@@ -42,8 +41,6 @@ public class A extends AbstractProcessor { ...@@ -42,8 +41,6 @@ public class A extends AbstractProcessor {
return true; return true;
} }
@Override @SuppressWarnings("")
public SourceVersion getSupportedSourceVersion() { private void foo() {}
return SourceVersion.latest();
}
} }
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,7 +25,8 @@ ...@@ -25,7 +25,8 @@
* @test * @test
* @bug 6414633 6440109 * @bug 6414633 6440109
* @summary Only the first processor message at a source location is reported * @summary Only the first processor message at a source location is reported
* @build A T6414633 * @library ../../lib
* @build JavacTestingAbstractProcessor A T6414633
* @run main T6414633 * @run main T6414633
*/ */
...@@ -55,8 +56,7 @@ public class T6414633 { ...@@ -55,8 +56,7 @@ public class T6414633 {
fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, A.class.getName()+".java"))); fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, A.class.getName()+".java")));
String[] opts = { "-proc:only", String[] opts = { "-proc:only",
"-processor", A.class.getName(), "-processor", A.class.getName(),
"-source", "1.6", "-classpath", testClasses + System.getProperty("path.separator") + "../../lib" };
"-classpath", testClasses };
JavacTask task = tool.getTask(null, fm, dl, Arrays.asList(opts), null, files); JavacTask task = tool.getTask(null, fm, dl, Arrays.asList(opts), null, files);
task.call(); task.call();
......
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,7 +25,8 @@ ...@@ -25,7 +25,8 @@
* @test * @test
* @bug 6441871 * @bug 6441871
* @summary spurious compiler error elicited by packageElement.getEnclosedElements() * @summary spurious compiler error elicited by packageElement.getEnclosedElements()
* @build b6341534 * @library ../../lib
* @build JavacTestingAbstractProcessor b6341534
* @run main T6430209 * @run main T6430209
*/ */
...@@ -54,7 +55,7 @@ public class T6430209 { ...@@ -54,7 +55,7 @@ public class T6430209 {
// run annotation processor b6341534 so we can check diagnostics // run annotation processor b6341534 so we can check diagnostics
// -proc:only -processor b6341534 -cp . ./src/*.java // -proc:only -processor b6341534 -cp . ./src/*.java
String testSrc = System.getProperty("test.src", "."); String testSrc = System.getProperty("test.src", ".");
String testClasses = System.getProperty("test.classes"); String testClasses = System.getProperty("test.classes") + System.getProperty("path.separator") + "../../lib";
JavacTool tool = JavacTool.create(); JavacTool tool = JavacTool.create();
MyDiagListener dl = new MyDiagListener(); MyDiagListener dl = new MyDiagListener();
StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null); StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
......
/* /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -30,16 +30,9 @@ import static javax.tools.Diagnostic.Kind.*; ...@@ -30,16 +30,9 @@ import static javax.tools.Diagnostic.Kind.*;
import java.util.*; import java.util.*;
import java.util.Set; import java.util.Set;
@SupportedAnnotationTypes({"*"}) public class b6341534 extends JavacTestingAbstractProcessor {
public class b6341534 extends AbstractProcessor {
static int r = 0; static int r = 0;
static Elements E = null;
static Messager msgr = null;
public void init(ProcessingEnvironment penv) {
processingEnv = penv;
msgr = penv.getMessager();
E = penv.getElementUtils();
}
//Create directory 'dir1' and a test class in dir1 //Create directory 'dir1' and a test class in dir1
public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv)
{ {
...@@ -49,13 +42,13 @@ public class b6341534 extends AbstractProcessor { ...@@ -49,13 +42,13 @@ public class b6341534 extends AbstractProcessor {
System.out.println("Round"+r+ ": " + t.toString()); System.out.println("Round"+r+ ": " + t.toString());
try { try {
PackageElement PE = E.getPackageElement("dir1"); PackageElement PE = eltUtils.getPackageElement("dir1");
List<? extends Element> LEE = PE.getEnclosedElements(); /* <=This line elicits the error message. */ List<? extends Element> LEE = PE.getEnclosedElements(); /* <=This line elicits the error message. */
for(Element e : LEE) for(Element e : LEE)
System.out.println("found " + e.toString() + " in dir1."); System.out.println("found " + e.toString() + " in dir1.");
} }
catch(NullPointerException npe) { catch(NullPointerException npe) {
msgr.printMessage(ERROR,npe.toString()); messager.printMessage(ERROR,npe.toString());
//npe.printStackTrace(); //npe.printStackTrace();
return false; return false;
} }
...@@ -63,13 +56,8 @@ public class b6341534 extends AbstractProcessor { ...@@ -63,13 +56,8 @@ public class b6341534 extends AbstractProcessor {
// on round 1, expect errorRaised == false && processingOver == false // on round 1, expect errorRaised == false && processingOver == false
// on round 2, expect errorRaised == true && processingOver == true // on round 2, expect errorRaised == true && processingOver == true
if( renv.errorRaised() != renv.processingOver()) { if( renv.errorRaised() != renv.processingOver()) {
msgr.printMessage(ERROR, "FAILED"); messager.printMessage(ERROR, "FAILED");
} }
return true; return true;
} }
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
} }
...@@ -32,20 +32,17 @@ import javax.tools.Diagnostic.Kind; ...@@ -32,20 +32,17 @@ import javax.tools.Diagnostic.Kind;
* @test * @test
* @bug 6499119 * @bug 6499119
* @summary Created package-info class file modeled improperly * @summary Created package-info class file modeled improperly
* @library ../../lib
* @build JavacTestingAbstractProcessor
* @compile ClassProcessor.java package-info.java * @compile ClassProcessor.java package-info.java
* @compile/process -cp . -processor ClassProcessor -Akind=java java.lang.Object * @compile/process -cp . -processor ClassProcessor -Akind=java java.lang.Object
* @compile/process -cp . -processor ClassProcessor -Akind=class java.lang.Object * @compile/process -cp . -processor ClassProcessor -Akind=class java.lang.Object
*/ */
@SupportedOptions({ "gen", "expect" }) @SupportedOptions({ "gen", "expect" })
@SupportedAnnotationTypes({"*"}) public class ClassProcessor extends JavacTestingAbstractProcessor {
public class ClassProcessor extends AbstractProcessor {
int round = 1; int round = 1;
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (round == 1) { if (round == 1) {
System.out.println("-- Round 1 --"); System.out.println("-- Round 1 --");
...@@ -71,8 +68,6 @@ public class ClassProcessor extends AbstractProcessor { ...@@ -71,8 +68,6 @@ public class ClassProcessor extends AbstractProcessor {
} }
private void createPackageFile() { private void createPackageFile() {
Filer filer = processingEnv.getFiler();
String kind = processingEnv.getOptions().get("kind"); String kind = processingEnv.getOptions().get("kind");
File pkgInfo; File pkgInfo;
...@@ -125,7 +120,6 @@ public class ClassProcessor extends AbstractProcessor { ...@@ -125,7 +120,6 @@ public class ClassProcessor extends AbstractProcessor {
} }
private void error(String msg) { private void error(String msg) {
Messager messager = processingEnv.getMessager();
messager.printMessage(Kind.ERROR, msg); messager.printMessage(Kind.ERROR, msg);
} }
} }
......
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册