提交 a4468a66 编写于 作者: T tbell

Merge

......@@ -29,7 +29,7 @@ import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic;
import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Messages;
import com.sun.tools.javac.util.JavacMessages;
import com.sun.tools.javac.util.Position;
/** A subtype of Log for use in APT.
......@@ -87,7 +87,7 @@ public class Bark extends Log {
context.put(barkKey, this);
// register additional resource bundle for APT messages.
Messages aptMessages = Messages.instance(context);
JavacMessages aptMessages = JavacMessages.instance(context);
aptMessages.add("com.sun.tools.apt.resources.apt");
aptDiags = new JCDiagnostic.Factory(aptMessages, "apt");
......
......@@ -51,7 +51,7 @@ import java.io.*;
*/
public class ConfigurationImpl extends Configuration {
private static final ConfigurationImpl instance = new ConfigurationImpl();
private static ConfigurationImpl instance = new ConfigurationImpl();
/**
* The build date. Note: For now, we will use
......@@ -189,6 +189,15 @@ public class ConfigurationImpl extends Configuration {
"com.sun.tools.doclets.formats.html.resources.standard");
}
/**
* Reset to a fresh new ConfigurationImpl, to allow multiple invocations
* of javadoc within a single VM. It would be better not to be using
* static fields at all, but .... (sigh).
*/
public static void reset() {
instance = new ConfigurationImpl();
}
public static ConfigurationImpl getInstance() {
return instance;
}
......@@ -475,7 +484,7 @@ public class ConfigurationImpl extends Configuration {
* {@inheritDoc}
*/
public WriterFactory getWriterFactory() {
return WriterFactoryImpl.getInstance();
return new WriterFactoryImpl(this);
}
/**
......
......@@ -41,12 +41,14 @@ import java.io.*;
*
*/
public class HtmlDoclet extends AbstractDoclet {
public HtmlDoclet() {
configuration = (ConfigurationImpl) configuration();
}
/**
* The global configuration information for this run.
*/
public ConfigurationImpl configuration =
(ConfigurationImpl) configuration();
public ConfigurationImpl configuration;
/**
* The "start" method as required by Javadoc.
......@@ -56,8 +58,12 @@ public class HtmlDoclet extends AbstractDoclet {
* @return true if the doclet ran without encountering any errors.
*/
public static boolean start(RootDoc root) {
HtmlDoclet doclet = new HtmlDoclet();
return doclet.start(doclet, root);
try {
HtmlDoclet doclet = new HtmlDoclet();
return doclet.start(doclet, root);
} finally {
ConfigurationImpl.reset();
}
}
/**
......
......@@ -37,26 +37,12 @@ import com.sun.javadoc.*;
*/
public class WriterFactoryImpl implements WriterFactory {
private static WriterFactoryImpl instance;
private ConfigurationImpl configuration;
private WriterFactoryImpl(ConfigurationImpl configuration) {
public WriterFactoryImpl(ConfigurationImpl configuration) {
this.configuration = configuration;
}
/**
* Return an instance of this factory.
*
* @return an instance of this factory.
*/
public static WriterFactoryImpl getInstance() {
if (instance == null) {
instance = new WriterFactoryImpl(ConfigurationImpl.getInstance());
}
return instance;
}
/**
* {@inheritDoc}
*/
......
......@@ -45,7 +45,7 @@ public abstract class AbstractDoclet {
/**
* The global configuration information for this run.
*/
public Configuration configuration = configuration();
public Configuration configuration;
/**
* The only doclet that may use this toolkit is {@value}
......@@ -74,6 +74,7 @@ public abstract class AbstractDoclet {
* @return true if the doclet executed without error. False otherwise.
*/
public boolean start(AbstractDoclet doclet, RootDoc root) {
configuration = configuration();
configuration.root = root;
if (! isValidDoclet(doclet)) {
return false;
......
......@@ -113,9 +113,9 @@ public abstract class Configuration {
public boolean keywords = false;
/**
* The meta tag keywords sole-instance.
* The meta tag keywords instance.
*/
public final MetaKeywords metakeywords = MetaKeywords.getInstance(this);
public final MetaKeywords metakeywords = new MetaKeywords(this);
/**
* The list of doc-file subdirectories to exclude
......@@ -211,12 +211,12 @@ public abstract class Configuration {
public boolean notimestamp= false;
/**
* The package grouping sole-instance.
* The package grouping instance.
*/
public final Group group = Group.getInstance(this);
public final Group group = new Group(this);
/**
* The tracker of external package links (sole-instance).
* The tracker of external package links.
*/
public final Extern extern = new Extern(this);
......
......@@ -56,8 +56,6 @@ import java.util.*;
*/
public class Group {
private static Group instance;
/**
* Map of regular expressions with the corresponding group name.
*/
......@@ -96,17 +94,10 @@ public class Group {
}
}
private Group(Configuration configuration) {
public Group(Configuration configuration) {
this.configuration = configuration;
}
public static Group getInstance(Configuration configuration) {
if (instance == null) {
instance = new Group(configuration);
}
return instance;
}
/**
* Depending upon the format of the package name provided in the "-group"
* option, generate two separate maps. There will be a map for mapping
......
......@@ -43,8 +43,6 @@ import java.util.*;
*/
public class MetaKeywords {
private static MetaKeywords instance = null;
/**
* The global configuration information for this run.
*/
......@@ -53,22 +51,10 @@ public class MetaKeywords {
/**
* Constructor
*/
private MetaKeywords(Configuration configuration) {
public MetaKeywords(Configuration configuration) {
this.configuration = configuration;
}
/**
* Return an instance of MetaKeywords. This class is a singleton.
*
* @param configuration the current configuration of the doclet.
*/
public static MetaKeywords getInstance(Configuration configuration) {
if (instance == null) {
instance = new MetaKeywords(configuration);
}
return instance;
}
/**
* Returns an array of strings where each element
* is a class, method or field name. This array is
......
......@@ -25,7 +25,7 @@
package com.sun.tools.javac.api;
import java.util.ResourceBundle;
import java.util.Locale;
/**
* This interface must be implemented by any javac class that has non-trivial
......@@ -39,10 +39,11 @@ public interface Formattable {
* Used to obtain a localized String representing the object accordingly
* to a given locale
*
* @param bundle resource bundle class used for localization
* @param locale locale in which the object's representation is to be rendered
* @param messages messages object used for localization
* @return a locale-dependent string representing the object
*/
public String toString(ResourceBundle bundle);
public String toString(Locale locale, Messages messages);
/**
* Retrieve a pretty name of this object's kind
* @return a string representing the object's kind
......
......@@ -68,6 +68,7 @@ public class JavacTaskImpl extends JavacTask {
private JavacTool tool;
private Main compilerMain;
private JavaCompiler compiler;
private Locale locale;
private String[] args;
private Context context;
private List<JavaFileObject> fileObjects;
......@@ -89,6 +90,7 @@ public class JavacTaskImpl extends JavacTask {
this.args = args;
this.context = context;
this.fileObjects = fileObjects;
setLocale(Locale.getDefault());
// null checks
compilerMain.getClass();
args.getClass();
......@@ -156,9 +158,9 @@ public class JavacTaskImpl extends JavacTask {
}
public void setLocale(Locale locale) {
// locale argument is ignored, see RFE 6443132
if (used.get())
throw new IllegalStateException();
this.locale = locale;
}
private void prepareCompiler() throws IOException {
......@@ -191,6 +193,8 @@ public class JavacTaskImpl extends JavacTask {
if (taskListener != null)
context.put(TaskListener.class, wrap(taskListener));
tool.beginContext(context);
//initialize compiler's default locale
JavacMessages.instance(context).setCurrentLocale(locale);
}
// where
private TaskListener wrap(final TaskListener tl) {
......
......@@ -49,6 +49,7 @@ import com.sun.tools.javac.main.RecognizedOptions.GrumpyHelper;
import com.sun.tools.javac.main.RecognizedOptions;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.JavacMessages;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.util.Pair;
import java.nio.charset.Charset;
......@@ -144,6 +145,7 @@ public final class JavacTool implements JavaCompiler {
Locale locale,
Charset charset) {
Context context = new Context();
JavacMessages.instance(context).setCurrentLocale(locale);
if (diagnosticListener != null)
context.put(DiagnosticListener.class, diagnosticListener);
context.put(Log.outKey, new PrintWriter(System.err, true)); // FIXME
......
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javac.api;
import java.util.Locale;
import java.util.MissingResourceException;
/**
* This interface defines the minimum requirements in order to provide support
* for localized formatted strings.
*
* @author Maurizio Cimadamore
*/
public interface Messages {
/**
* Add a new resource bundle to the list that is searched for localized messages.
* @param bundleName the name to identify the resource bundle of localized messages.
* @throws MissingResourceException if the given resource is not found
*/
void add(String bundleName) throws MissingResourceException;
/**
* Get a localized formatted string
* @param l locale in which the text is to be localized
* @param key locale-independent message key
* @param args misc message arguments
* @return a localized formatted string
*/
String getLocalizedString(Locale l, String key, Object... args);
}
......@@ -26,9 +26,10 @@
package com.sun.tools.javac.code;
import java.util.EnumSet;
import java.util.ResourceBundle;
import java.util.Locale;
import com.sun.tools.javac.api.Formattable;
import com.sun.tools.javac.api.Messages;
import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.code.Flags.*;
......@@ -117,9 +118,9 @@ public class Kinds {
return "Kindname";
}
public String toString(ResourceBundle bundle) {
public String toString(Locale locale, Messages messages) {
String s = toString();
return bundle.getString("compiler.misc." + s);
return messages.getLocalizedString(locale, "compiler.misc." + s);
}
}
......
......@@ -336,7 +336,7 @@ public class Symtab {
// create the basic builtin symbols
rootPackage = new PackageSymbol(names.empty, null);
final Messages messages = Messages.instance(context);
final JavacMessages messages = JavacMessages.instance(context);
unnamedPackage = new PackageSymbol(names.empty, rootPackage) {
public String toString() {
return messages.getLocalizedString("compiler.misc.unnamed.package");
......
......@@ -67,7 +67,7 @@ public class Types {
new Context.Key<Types>();
final Symtab syms;
final Messages messages;
final JavacMessages messages;
final Names names;
final boolean allowBoxing;
final ClassReader reader;
......@@ -93,7 +93,7 @@ public class Types {
source = Source.instance(context);
chk = Check.instance(context);
capturedName = names.fromString("<captured wildcard>");
messages = Messages.instance(context);
messages = JavacMessages.instance(context);
}
// </editor-fold>
......@@ -1430,6 +1430,10 @@ public class Types {
long flags = sym.flags();
if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
Type base = asOuterSuper(t, owner);
//if t is an intersection type T = CT & I1 & I2 ... & In
//its supertypes CT, I1, ... In might contain wildcards
//so we need to go through capture conversion
base = t.isCompound() ? capture(base) : base;
if (base != null) {
List<Type> ownerParams = owner.type.allparams();
List<Type> baseParams = base.allparams();
......@@ -3209,6 +3213,7 @@ public class Types {
containsType(t, s) && containsType(s, t);
}
// <editor-fold defaultstate="collapsed" desc="adapt">
/**
* Adapt a type by computing a substitution which maps a source
* type to a target type.
......@@ -3222,94 +3227,115 @@ public class Types {
Type target,
ListBuffer<Type> from,
ListBuffer<Type> to) throws AdaptFailure {
Map<Symbol,Type> mapping = new HashMap<Symbol,Type>();
adaptRecursive(source, target, from, to, mapping);
List<Type> fromList = from.toList();
List<Type> toList = to.toList();
while (!fromList.isEmpty()) {
Type val = mapping.get(fromList.head.tsym);
if (toList.head != val)
toList.head = val;
fromList = fromList.tail;
toList = toList.tail;
}
new Adapter(from, to).adapt(source, target);
}
// where
private void adaptRecursive(Type source,
Type target,
ListBuffer<Type> from,
ListBuffer<Type> to,
Map<Symbol,Type> mapping) throws AdaptFailure {
if (source.tag == TYPEVAR) {
// Check to see if there is
// already a mapping for $source$, in which case
// the old mapping will be merged with the new
Type val = mapping.get(source.tsym);
if (val != null) {
if (val.isSuperBound() && target.isSuperBound()) {
val = isSubtype(lowerBound(val), lowerBound(target))
? target : val;
} else if (val.isExtendsBound() && target.isExtendsBound()) {
val = isSubtype(upperBound(val), upperBound(target))
? val : target;
} else if (!isSameType(val, target)) {
throw new AdaptFailure();
}
} else {
val = target;
from.append(source);
to.append(target);
}
mapping.put(source.tsym, val);
} else if (source.tag == target.tag) {
switch (source.tag) {
case CLASS:
adapt(source.allparams(), target.allparams(),
from, to, mapping);
break;
case ARRAY:
adaptRecursive(elemtype(source), elemtype(target),
from, to, mapping);
break;
case WILDCARD:
if (source.isExtendsBound()) {
adaptRecursive(upperBound(source), upperBound(target),
from, to, mapping);
} else if (source.isSuperBound()) {
adaptRecursive(lowerBound(source), lowerBound(target),
from, to, mapping);
}
break;
class Adapter extends SimpleVisitor<Void, Type> {
ListBuffer<Type> from;
ListBuffer<Type> to;
Map<Symbol,Type> mapping;
Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
this.from = from;
this.to = to;
mapping = new HashMap<Symbol,Type>();
}
public void adapt(Type source, Type target) throws AdaptFailure {
visit(source, target);
List<Type> fromList = from.toList();
List<Type> toList = to.toList();
while (!fromList.isEmpty()) {
Type val = mapping.get(fromList.head.tsym);
if (toList.head != val)
toList.head = val;
fromList = fromList.tail;
toList = toList.tail;
}
}
@Override
public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
if (target.tag == CLASS)
adaptRecursive(source.allparams(), target.allparams());
return null;
}
@Override
public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
if (target.tag == ARRAY)
adaptRecursive(elemtype(source), elemtype(target));
return null;
}
@Override
public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
if (source.isExtendsBound())
adaptRecursive(upperBound(source), upperBound(target));
else if (source.isSuperBound())
adaptRecursive(lowerBound(source), lowerBound(target));
return null;
}
@Override
public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
// Check to see if there is
// already a mapping for $source$, in which case
// the old mapping will be merged with the new
Type val = mapping.get(source.tsym);
if (val != null) {
if (val.isSuperBound() && target.isSuperBound()) {
val = isSubtype(lowerBound(val), lowerBound(target))
? target : val;
} else if (val.isExtendsBound() && target.isExtendsBound()) {
val = isSubtype(upperBound(val), upperBound(target))
? val : target;
} else if (!isSameType(val, target)) {
throw new AdaptFailure();
}
} else {
val = target;
from.append(source);
to.append(target);
}
mapping.put(source.tsym, val);
return null;
}
public static class AdaptFailure extends Exception {
static final long serialVersionUID = -7490231548272701566L;
@Override
public Void visitType(Type source, Type target) {
return null;
}
/**
* Adapt a type by computing a substitution which maps a list of
* source types to a list of target types.
*
* @param source the source type
* @param target the target type
* @param from the type variables of the computed substitution
* @param to the types of the computed substitution.
*/
private void adapt(List<Type> source,
List<Type> target,
ListBuffer<Type> from,
ListBuffer<Type> to,
Map<Symbol,Type> mapping) throws AdaptFailure {
if (source.length() == target.length()) {
while (source.nonEmpty()) {
adaptRecursive(source.head, target.head, from, to, mapping);
source = source.tail;
target = target.tail;
private Set<TypePair> cache = new HashSet<TypePair>();
private void adaptRecursive(Type source, Type target) {
TypePair pair = new TypePair(source, target);
if (cache.add(pair)) {
try {
visit(source, target);
} finally {
cache.remove(pair);
}
}
}
private void adaptRecursive(List<Type> source, List<Type> target) {
if (source.length() == target.length()) {
while (source.nonEmpty()) {
adaptRecursive(source.head, target.head);
source = source.tail;
target = target.tail;
}
}
}
}
public static class AdaptFailure extends RuntimeException {
static final long serialVersionUID = -7490231548272701566L;
}
private void adaptSelf(Type t,
ListBuffer<Type> from,
ListBuffer<Type> to) {
......@@ -3322,6 +3348,7 @@ public class Types {
throw new AssertionError(ex);
}
}
// </editor-fold>
/**
* Rewrite all type variables (universal quantifiers) in the given
......
......@@ -1884,6 +1884,9 @@ public class Lower extends TreeTranslator {
}
});
}
case JCTree.TYPECAST: {
return abstractLval(((JCTypeCast)lval).expr, builder);
}
}
throw new AssertionError(lval);
}
......@@ -2713,10 +2716,7 @@ public class Lower extends TreeTranslator {
// boxing required; need to rewrite as x = (unbox typeof x)(x op y);
// or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
// (but without recomputing x)
JCTree arg = (tree.lhs.getTag() == JCTree.TYPECAST)
? ((JCTypeCast)tree.lhs).expr
: tree.lhs;
JCTree newTree = abstractLval(arg, new TreeBuilder() {
JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
public JCTree build(final JCTree lhs) {
int newTag = tree.getTag() - JCTree.ASGOffset;
// Erasure (TransTypes) can change the type of
......@@ -2768,9 +2768,8 @@ public class Lower extends TreeTranslator {
// or
// translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
// where OP is += or -=
final boolean cast = tree.arg.getTag() == JCTree.TYPECAST;
final JCExpression arg = cast ? ((JCTypeCast)tree.arg).expr : tree.arg;
return abstractLval(arg, new TreeBuilder() {
final boolean cast = TreeInfo.skipParens(tree.arg).getTag() == JCTree.TYPECAST;
return abstractLval(tree.arg, new TreeBuilder() {
public JCTree build(final JCTree tmp1) {
return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
public JCTree build(final JCTree tmp2) {
......
......@@ -741,7 +741,7 @@ public class Resolve {
while (ct.tag == TYPEVAR)
ct = ct.getUpperBound();
ClassSymbol c = (ClassSymbol)ct.tsym;
if ((c.flags() & (ABSTRACT | INTERFACE)) == 0)
if ((c.flags() & (ABSTRACT | INTERFACE | ENUM)) == 0)
abstractok = false;
for (Scope.Entry e = c.members().lookup(name);
e.scope != null;
......
......@@ -623,8 +623,8 @@ public class TransTypes extends TreeTranslator {
}
public void visitAssignop(JCAssignOp tree) {
tree.lhs = translate(tree.lhs, null);
tree.rhs = translate(tree.rhs, erasure(tree.rhs.type));
tree.lhs = translate(tree.lhs, tree.operator.type.getParameterTypes().head);
tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
tree.type = erasure(tree.type);
result = tree;
}
......
......@@ -89,6 +89,8 @@ class RegularFileObject extends BaseFileObject {
for (File dir: path) {
//System.err.println("dir: " + dir);
String dPath = dir.getPath();
if (dPath.length() == 0)
dPath = System.getProperty("user.dir");
if (!dPath.endsWith(File.separator))
dPath += File.separator;
if (fPath.regionMatches(true, 0, dPath, 0, dPath.length())
......
......@@ -484,7 +484,7 @@ public class Main {
public static String getLocalizedString(String key, Object... args) { // FIXME sb private
try {
if (messages == null)
messages = new Messages(javacBundleName);
messages = new JavacMessages(javacBundleName);
return messages.getLocalizedString("javac." + key, args);
}
catch (MissingResourceException e) {
......@@ -494,18 +494,18 @@ public class Main {
public static void useRawMessages(boolean enable) {
if (enable) {
messages = new Messages(javacBundleName) {
messages = new JavacMessages(javacBundleName) {
public String getLocalizedString(String key, Object... args) {
return key;
}
};
} else {
messages = new Messages(javacBundleName);
messages = new JavacMessages(javacBundleName);
}
}
private static final String javacBundleName =
"com.sun.tools.javac.resources.javac";
private static Messages messages;
private static JavacMessages messages;
}
......@@ -25,9 +25,10 @@
package com.sun.tools.javac.parser;
import java.util.ResourceBundle;
import java.util.Locale;
import com.sun.tools.javac.api.Formattable;
import com.sun.tools.javac.api.Messages;
/** An interface that defines codes for Java source tokens
* returned from lexical analysis.
......@@ -191,8 +192,7 @@ public enum Token implements Formattable {
return "Token";
}
public String toString(ResourceBundle bundle) {
String s = toString();
return s.startsWith("token.") ? bundle.getString("compiler.misc." + s) : s;
public String toString(Locale locale, Messages messages) {
return name != null ? toString() : messages.getLocalizedString(locale, "compiler.misc." + toString());
}
}
......@@ -69,6 +69,7 @@ import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.JavacMessages;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Options;
......@@ -133,9 +134,14 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
*/
Source source;
/**
* JavacMessages object used for localization
*/
private JavacMessages messages;
private Context context;
public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) {
public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) {
options = Options.instance(context);
this.context = context;
log = Log.instance(context);
......@@ -157,6 +163,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
typeUtils = new JavacTypes(context);
processorOptions = initProcessorOptions(context);
unmatchedProcessorOptions = initUnmatchedProcessorOptions();
messages = JavacMessages.instance(context);
initProcessorIterator(context, processors);
}
......@@ -1246,7 +1253,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
}
public Locale getLocale() {
return Locale.getDefault();
return messages.getCurrentLocale();
}
public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
......
......@@ -27,11 +27,13 @@ package com.sun.tools.javac.util;
import java.util.Collection;
import java.util.Locale;
import javax.tools.JavaFileObject;
import java.util.ResourceBundle;
import com.sun.tools.javac.api.DiagnosticFormatter;
import com.sun.tools.javac.api.Formattable;
import com.sun.tools.javac.api.DiagnosticFormatter.PositionKind;
import com.sun.tools.javac.file.JavacFileManager;
import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticType.*;
/**
* This abstract class provides a basic implementation of the functionalities that should be provided
......@@ -48,16 +50,24 @@ import com.sun.tools.javac.file.JavacFileManager;
public abstract class AbstractDiagnosticFormatter implements DiagnosticFormatter<JCDiagnostic> {
/**
* Messages object used by this formatter for i18n
* JavacMessages object used by this formatter for i18n
*/
protected Messages messages;
protected JavacMessages messages;
protected boolean showSource;
/**
* Initialize an AbstractDiagnosticFormatter by setting its Messages object
* Initialize an AbstractDiagnosticFormatter by setting its JavacMessages object
* @param messages
*/
protected AbstractDiagnosticFormatter(Messages messages) {
protected AbstractDiagnosticFormatter(JavacMessages messages, Options options, boolean showSource) {
this.messages = messages;
this.showSource = options.get("showSource") == null ? showSource :
options.get("showSource").equals("true");
}
protected AbstractDiagnosticFormatter(JavacMessages messages, boolean showSource) {
this.messages = messages;
this.showSource = showSource;
}
public String formatMessage(JCDiagnostic d, Locale l) {
......@@ -131,7 +141,7 @@ public abstract class AbstractDiagnosticFormatter implements DiagnosticFormatter
else if (arg instanceof JavaFileObject)
return JavacFileManager.getJavacBaseFileName((JavaFileObject)arg);
else if (arg instanceof Formattable)
return ((Formattable)arg).toString(Messages.getDefaultBundle());
return ((Formattable)arg).toString(l, messages);
else
return String.valueOf(arg);
}
......@@ -155,6 +165,27 @@ public abstract class AbstractDiagnosticFormatter implements DiagnosticFormatter
return sbuf.toString();
}
/** Format the faulty source code line and point to the error.
* @param d The diagnostic for which the error line should be printed
*/
protected String formatSourceLine(JCDiagnostic d) {
StringBuilder buf = new StringBuilder();
DiagnosticSource source = d.getDiagnosticSource();
int pos = d.getIntPosition();
if (d.getIntPosition() != Position.NOPOS) {
String line = (source == null ? null : source.getLine(pos));
if (line == null)
return "";
buf.append(line+"\n");
int col = source.getColumnNumber(pos, false);
for (int i = 0; i < col - 1; i++) {
buf.append((line.charAt(i) == '\t') ? "\t" : " ");
}
buf.append("^");
}
return buf.toString();
}
/**
* Converts a String into a locale-dependent representation accordingly to a given locale
*
......@@ -164,6 +195,10 @@ public abstract class AbstractDiagnosticFormatter implements DiagnosticFormatter
* @return a locale-dependent string
*/
protected String localize(Locale l, String key, Object... args) {
return messages.getLocalizedString(key, args);
return messages.getLocalizedString(l, key, args);
}
public boolean displaySource(JCDiagnostic d) {
return showSource && d.getType() != FRAGMENT;
}
}
......@@ -59,10 +59,11 @@ public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
* Create a basic formatter based on the supplied options.
*
* @param opts list of command-line options
* @param msgs Messages object used for i18n
* @param msgs JavacMessages object used for i18n
*/
BasicDiagnosticFormatter(Options opts, Messages msgs) {
this(msgs); //common init
BasicDiagnosticFormatter(Options opts, JavacMessages msgs) {
super(msgs, opts, true);
initAvailableFormats();
String fmt = opts.get("diags");
if (fmt != null) {
String[] formats = fmt.split("\\|");
......@@ -80,10 +81,14 @@ public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
/**
* Create a standard basic formatter
*
* @param msgs Messages object used for i18n
* @param msgs JavacMessages object used for i18n
*/
public BasicDiagnosticFormatter(Messages msgs) {
super(msgs);
public BasicDiagnosticFormatter(JavacMessages msgs) {
super(msgs, true);
initAvailableFormats();
}
public void initAvailableFormats() {
availableFormats = new HashMap<BasicFormatKind, String>();
availableFormats.put(DEFAULT_POS_FORMAT, "%f:%l:%_%t%m");
availableFormats.put(DEFAULT_NO_POS_FORMAT, "%p%m");
......@@ -91,6 +96,8 @@ public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
}
public String format(JCDiagnostic d, Locale l) {
if (l == null)
l = messages.getCurrentLocale();
String format = selectFormat(d);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < format.length(); i++) {
......@@ -102,6 +109,9 @@ public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
}
buf.append(meta ? formatMeta(c, d, l) : String.valueOf(c));
}
if (displaySource(d)) {
buf.append("\n" + formatSourceLine(d));
}
return buf.toString();
}
......@@ -165,10 +175,6 @@ public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
return format;
}
public boolean displaySource(JCDiagnostic d) {
return true;
}
/**
* This enum contains all the kinds of formatting patterns supported
* by a basic diagnostic formatter.
......
......@@ -64,12 +64,12 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
/** Create a new diagnostic factory. */
protected Factory(Context context) {
this(Messages.instance(context), "compiler");
this(JavacMessages.instance(context), "compiler");
context.put(diagnosticFactoryKey, this);
}
/** Create a new diagnostic factory. */
public Factory(Messages messages, String prefix) {
public Factory(JavacMessages messages, String prefix) {
this.prefix = prefix;
this.formatter = new BasicDiagnosticFormatter(messages);
}
......@@ -178,7 +178,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
@Deprecated
public static DiagnosticFormatter<JCDiagnostic> getFragmentFormatter() {
if (fragmentFormatter == null) {
fragmentFormatter = new BasicDiagnosticFormatter(Messages.getDefaultMessages());
fragmentFormatter = new BasicDiagnosticFormatter(JavacMessages.getDefaultMessages());
}
return fragmentFormatter;
}
......
......@@ -25,75 +25,114 @@
package com.sun.tools.javac.util;
import com.sun.tools.javac.api.Messages;
import java.lang.ref.SoftReference;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* Support for localized messages.
* Support for formatted localized messages.
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. 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 Messages {
/** The context key for the Messages object. */
protected static final Context.Key<Messages> messagesKey =
new Context.Key<Messages>();
/** Get the Messages instance for this context. */
public static Messages instance(Context context) {
Messages instance = context.get(messagesKey);
public class JavacMessages implements Messages {
/** The context key for the JavacMessages object. */
protected static final Context.Key<JavacMessages> messagesKey =
new Context.Key<JavacMessages>();
/** Get the JavacMessages instance for this context. */
public static JavacMessages instance(Context context) {
JavacMessages instance = context.get(messagesKey);
if (instance == null)
instance = new Messages(context);
instance = new JavacMessages(context);
return instance;
}
private List<ResourceBundle> bundles = List.nil();
private Map<Locale, SoftReference<List<ResourceBundle>>> bundleCache;
/** Creates a Messages object.
private List<String> bundleNames;
private Locale currentLocale;
private List<ResourceBundle> currentBundles;
public Locale getCurrentLocale() {
return currentLocale;
}
public void setCurrentLocale(Locale locale) {
if (locale == null) {
locale = Locale.getDefault();
}
this.currentBundles = getBundles(locale);
this.currentLocale = locale;
}
/** Creates a JavacMessages object.
*/
public Messages(Context context) {
public JavacMessages(Context context) {
this(defaultBundleName);
context.put(messagesKey, this);
add(getDefaultBundle());
}
/** Creates a Messages object.
* @param bundle the name to identify the resource buundle of localized messages.
/** Creates a JavacMessages object.
* @param bundleName the name to identify the resource buundle of localized messages.
*/
public Messages(String bundleName) throws MissingResourceException {
public JavacMessages(String bundleName) throws MissingResourceException {
bundleNames = List.nil();
bundleCache = new HashMap<Locale, SoftReference<List<ResourceBundle>>>();
add(bundleName);
setCurrentLocale(Locale.getDefault());
}
/** Creates a Messages object.
* @param bundle the name to identif the resource buundle of localized messages.
*/
public Messages(ResourceBundle bundle) throws MissingResourceException {
add(bundle);
public JavacMessages() throws MissingResourceException {
this(defaultBundleName);
}
/** Add a new resource bundle to the list that is searched for localized messages.
* @param bundle the name to identify the resource bundle of localized messages.
*/
public void add(String bundleName) throws MissingResourceException {
add(ResourceBundle.getBundle(bundleName));
bundleNames = bundleNames.prepend(bundleName);
if (!bundleCache.isEmpty())
bundleCache.clear();
currentBundles = null;
}
/** Add a new resource bundle to the list that is searched for localized messages.
* Resource bundles will be searched in reverse order in which they are added.
* @param bundle the bundle of localized messages.
*/
public void add(ResourceBundle bundle) {
bundles = bundles.prepend(bundle);
public List<ResourceBundle> getBundles(Locale locale) {
if (locale == currentLocale && currentBundles != null)
return currentBundles;
SoftReference<List<ResourceBundle>> bundles = bundleCache.get(locale);
List<ResourceBundle> bundleList = bundles == null ? null : bundles.get();
if (bundleList == null) {
bundleList = List.nil();
for (String bundleName : bundleNames) {
try {
ResourceBundle rb = ResourceBundle.getBundle(bundleName, locale);
bundleList = bundleList.prepend(rb);
} catch (MissingResourceException e) {
throw new InternalError("Cannot find javac resource bundle for locale " + locale);
}
}
bundleCache.put(locale, new SoftReference<List<ResourceBundle>>(bundleList));
}
return bundleList;
}
/** Gets the localized string corresponding to a key, formatted with a set of args.
*/
public String getLocalizedString(String key, Object... args) {
return getLocalizedString(bundles, key, args);
return getLocalizedString(currentLocale, key, args);
}
public String getLocalizedString(Locale l, String key, Object... args) {
if (l == null)
l = getCurrentLocale();
return getLocalizedString(getBundles(l), key, args);
}
/* Static access:
* javac has a firmly entrenched notion of a default message bundle
......@@ -104,7 +143,7 @@ public class Messages {
private static final String defaultBundleName =
"com.sun.tools.javac.resources.compiler";
private static ResourceBundle defaultBundle;
private static Messages defaultMessages;
private static JavacMessages defaultMessages;
/**
......@@ -116,9 +155,10 @@ public class Messages {
}
// used to support legacy static Diagnostic.fragment
static Messages getDefaultMessages() {
@Deprecated
static JavacMessages getDefaultMessages() {
if (defaultMessages == null)
defaultMessages = new Messages(getDefaultBundle());
defaultMessages = new JavacMessages(defaultBundleName);
return defaultMessages;
}
......@@ -152,6 +192,4 @@ public class Messages {
}
return MessageFormat.format(msg, args);
}
}
......@@ -29,7 +29,6 @@ import java.io.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Locale;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
......@@ -97,6 +96,11 @@ public class Log extends AbstractLog {
*/
private DiagnosticFormatter<JCDiagnostic> diagFormatter;
/**
* JavacMessages object used for localization
*/
private JavacMessages messages;
/** Construct a log with given I/O redirections.
*/
@Deprecated
......@@ -115,9 +119,9 @@ public class Log extends AbstractLog {
this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
boolean rawDiagnostics = options.get("rawDiagnostics") != null;
Messages msgs = Messages.instance(context);
this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(msgs) :
new BasicDiagnosticFormatter(options, msgs);
messages = JavacMessages.instance(context);
this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
new BasicDiagnosticFormatter(options, messages);
@SuppressWarnings("unchecked") // FIXME
DiagnosticListener<? super JavaFileObject> diagListener =
context.get(DiagnosticListener.class);
......@@ -335,15 +339,7 @@ public class Log extends AbstractLog {
PrintWriter writer = getWriterForDiagnosticType(diag.getType());
printLines(writer, diagFormatter.format(diag, Locale.getDefault()));
if (diagFormatter.displaySource(diag)) {
int pos = diag.getIntPosition();
if (pos != Position.NOPOS) {
JavaFileObject prev = useSource(diag.getSource());
printErrLine(pos, writer);
useSource(prev);
}
}
printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
if (promptOnError) {
switch (diag.getType()) {
......@@ -384,7 +380,7 @@ public class Log extends AbstractLog {
* @param args Fields to substitute into the string.
*/
public static String getLocalizedString(String key, Object ... args) {
return Messages.getDefaultLocalizedString("compiler.misc." + key, args);
return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
}
/***************************************************************************
......
......@@ -41,8 +41,8 @@ public class RawDiagnosticFormatter extends AbstractDiagnosticFormatter {
* Create a formatter based on the supplied options.
* @param msgs
*/
public RawDiagnosticFormatter(Messages msgs) {
super(null);
public RawDiagnosticFormatter(Options opts) {
super(null, opts, false);
}
//provide common default formats
......@@ -61,6 +61,8 @@ public class RawDiagnosticFormatter extends AbstractDiagnosticFormatter {
buf.append('-');
buf.append(' ');
buf.append(formatMessage(d, null));
if (displaySource(d))
buf.append("\n" + formatSourceLine(d));
return buf.toString();
}
catch (Exception e) {
......@@ -94,8 +96,4 @@ public class RawDiagnosticFormatter extends AbstractDiagnosticFormatter {
}
return buf.toString();
}
public boolean displaySource(JCDiagnostic d) {
return false;
}
}
......@@ -72,7 +72,8 @@ public class AuthorDD
/** Run javadoc */
public static void runJavadoc(String[] javadocArgs) {
if (com.sun.tools.javadoc.Main.execute(javadocArgs) != 0) {
if (com.sun.tools.javadoc.Main.execute(AuthorDD.class.getClassLoader(),
javadocArgs) != 0) {
throw new Error("Javadoc failed to execute");
}
}
......
......@@ -197,6 +197,7 @@ public abstract class JavadocTester {
new PrintWriter(warnings, true),
new PrintWriter(notices, true),
docletClass,
getClass().getClassLoader(),
args);
System.setOut(prev);
standardOut = new StringBuffer(stdout.toString());
......
......@@ -33,6 +33,8 @@
* @run main TestSupplementary
*/
import java.util.Locale;
public class TestSupplementary extends JavadocTester {
private static final String BUG_ID = "4914724";
......@@ -56,9 +58,14 @@ public class TestSupplementary extends JavadocTester {
* @param args the array of command line arguments.
*/
public static void main(String[] args) {
TestSupplementary tester = new TestSupplementary();
run(tester, ARGS, TEST, NEGATED_TEST);
tester.printSummary();
Locale saveLocale = Locale.getDefault();
try {
TestSupplementary tester = new TestSupplementary();
run(tester, ARGS, TEST, NEGATED_TEST);
tester.printSummary();
} finally {
Locale.setDefault(saveLocale);
}
}
/**
......
......@@ -26,7 +26,6 @@
# @test
# @bug 5008759 4998341 5018369 5032476 5060121 5096932 5096931
# @run shell ../verifyVariables.sh
# @build Aggregate
# @run shell print.sh
# @summary test availabilty of print option
# @author Joseph D. Darcy
......@@ -42,6 +41,12 @@ case "${OS}" in
;;
esac
# Compile file directly, without TESTJAVACOPTS
# Don't use @build or @compile as these implicitly use jtreg -javacoption values
# and it is important that this file be compiled as expected, for later comparison
# against a golden file.
"${TESTJAVA}/bin/javac" ${TESTTOOLVMOPTS} -d ${TESTCLASSES} ${TESTSRC}/Aggregate.java
# Construct path to apt executable
APT="${TESTJAVA}/bin/apt ${TESTTOOLVMOPTS} \
-print "
......
......@@ -473,6 +473,9 @@ ${JAR} cf0 round4Apf.jar Round4Apf*.class META-INF
cp ${TESTCLASSES}/Round?.class .
${JAR} cf0 rounds.jar Round?.class
# cleanup file to prevent accidental discovery in current directory
rm -Rf META-INF/services/*
printf "%s\n" "-factorypath round1Apf.jar${SEP}round2Apf.jar${SEP}round3Apf.jar${SEP}round4Apf.jar" > options8
printf "%s\n" "-classpath rounds.jar" >> options8
printf "%s\n" "-s ./src" >> options8
......
......@@ -109,7 +109,8 @@ cp ${TESTSRC}/servicesPhantomTouch ./META-INF/services/com.sun.mirror.apt.Annota
${JAR} cf0 phantom/phantom.jar PhantomTouch*.class META-INF
# cleanup file to prevent accidental discovery in current directory
rm -f META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory
# Jar files created; verify right output file is touched
......
......@@ -28,7 +28,7 @@
* @summary Tests AnnotationMirror and AnnotationValue methods.
* @library ../../lib
* @compile -source 1.5 AnnoMirror.java
* @run main AnnoMirror
* @run main/othervm AnnoMirror
*/
......
......@@ -28,7 +28,7 @@
* @summary AnnotationTypeDeclaration tests
* @library ../../lib
* @compile -source 1.5 AnnoTypeDecl.java
* @run main AnnoTypeDecl
* @run main/othervm AnnoTypeDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary AnnotationTypeElementDeclaration tests
* @library ../../lib
* @compile -source 1.5 AnnoTypeElemDecl.java
* @run main AnnoTypeElemDecl
* @run main/othervm AnnoTypeElemDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary Tests AnnotationValue methods.
* @library ../../lib
* @compile -source 1.5 AnnoVal.java
* @run main AnnoVal
* @run main/othervm AnnoVal
*/
......
......@@ -28,7 +28,7 @@
* @summary ClassDeclaration tests
* @library ../../lib
* @compile -source 1.5 ClassDecl.java
* @run main ClassDecl
* @run main/othervm ClassDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary Tests FieldDeclaration.getConstantExpression method
* @library ../../lib
* @compile -source 1.5 ConstExpr.java
* @run main ConstExpr
* @run main/othervm ConstExpr
*/
......
......@@ -28,7 +28,7 @@
* @summary ConstructorDeclaration tests
* @library ../../lib
* @compile -source 1.5 ConstructorDecl.java
* @run main ConstructorDecl
* @run main/othervm ConstructorDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary EnumDeclaration tests
* @library ../../lib
* @compile -source 1.5 EnumDecl.java
* @run main EnumDecl
* @run main/othervm EnumDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary FieldDeclaration tests
* @library ../../lib
* @compile -source 1.5 FieldDecl.java
* @run main FieldDecl
* @run main/othervm FieldDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary Tests Declaration.getAnnotation method
* @library ../../lib
* @compile -source 1.5 GetAnno.java
* @run main GetAnno
* @run main/othervm GetAnno
*/
......
......@@ -28,7 +28,7 @@
* @summary InterfaceDeclaration tests
* @library ../../lib
* @compile -source 1.5 InterfaceDecl.java
* @run main InterfaceDecl
* @run main/othervm InterfaceDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary MethodDeclaration tests
* @library ../../lib
* @compile -source 1.5 MethodDecl.java
* @run main MethodDecl
* @run main/othervm MethodDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary PackageDeclaration tests
* @library ../../lib
* @compile -source 1.5 PackageDecl.java
* @run main PackageDecl
* @run main/othervm PackageDecl
*/
......
......@@ -27,6 +27,7 @@
* @bug 4853450 5031171
* @summary ParameterDeclaration tests
* @library ../../lib
* @run main/othervm ParameterDecl
*/
......
......@@ -28,7 +28,7 @@
* @summary AnnotationType tests
* @library ../../lib
* @compile -source 1.5 AnnoTyp.java
* @run main AnnoTyp
* @run main/othervm AnnoTyp
*/
......
......@@ -28,7 +28,7 @@
* @summary ArrayType tests
* @library ../../lib
* @compile -source 1.5 ArrayTyp.java
* @run main ArrayTyp
* @run main/othervm ArrayTyp
*/
......
......@@ -27,6 +27,7 @@
* @bug 4853450 5009360 5055963
* @summary ClassType tests
* @library ../../lib
* @run main/othervm ClassTyp
*/
......
......@@ -28,7 +28,7 @@
* @summary EnumType tests
* @library ../../lib
* @compile -source 1.5 EnumTyp.java
* @run main EnumTyp
* @run main/othervm EnumTyp
*/
......
......@@ -27,6 +27,7 @@
* @bug 4853450 5055963
* @summary InterfaceType tests
* @library ../../lib
* @run main/othervm InterfaceTyp
*/
......
......@@ -28,7 +28,7 @@
* @summary PrimitiveType tests
* @library ../../lib
* @compile -source 1.5 PrimitiveTyp.java
* @run main PrimitiveTyp
* @run main/othervm PrimitiveTyp
*/
......
......@@ -28,7 +28,7 @@
* @summary TypeVariable tests
* @library ../../lib
* @compile -source 1.5 TypeVar.java
* @run main TypeVar
* @run main/othervm TypeVar
*/
......
......@@ -28,7 +28,7 @@
* @summary WildcardType tests
* @library ../../lib
* @compile -source 1.5 WildcardTyp.java
* @run main WildcardTyp
* @run main/othervm WildcardTyp
*/
......
......@@ -27,6 +27,7 @@
* @bug 5037165
* @summary Test the Declarations.overrides method
* @library ../../lib
* @run main/othervm Overrides
*/
......
......@@ -27,6 +27,7 @@
* @bug 5033381
* @summary Test the type creation methods in Types.
* @library ../../lib
* @run main/othervm TypeCreation
*/
......
......@@ -35,7 +35,7 @@ import javax.lang.model.element.Element;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Messages;
import com.sun.tools.javac.util.JavacMessages;
import javax.tools.*;
......@@ -63,7 +63,7 @@ public class T6457284 {
throw new AssertionError("No top-level classes!");
}
static class MyMessages extends Messages {
static class MyMessages extends JavacMessages {
static void preRegister(Context context) {
context.put(messagesKey, new MyMessages());
}
......
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6738538 6687444
* @summary javac crashes when using a type parameter as a covariant method return type
* @author Maurizio Cimadamore
*
* @compile T6738538a.java
*/
class T6738538a {
class C<T> {
public T m(){
return null;
}
}
interface I<T>{
public T m();
}
class Crash<T extends C<?> & I> {}
}
\ No newline at end of file
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6738538 6687444
* @summary javac crashes when using a type parameter as a covariant method return type
* @author Maurizio Cimadamore
*
* @compile T6738538b.java
*/
class T6738538b {
interface I1 {
Object m();
}
interface I2 {}
class C1<T> implements I1 {
public T m() {
return null;
}
}
class C2<T extends C1<?> & I2> {}
}
\ No newline at end of file
@Deprecated
class A {
class A {}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6443132 6406133 6597678
* @summary Compiler API ignores locale settings
* @author Maurizio Cimadamore
* @library ../lib
*/
import javax.tools.*;
import javax.annotation.processing.*;
import javax.lang.model.element.*;
import java.util.*;
import java.io.*;
public class T6406133 extends ToolTester {
List<Locale> locales = Arrays.asList(Locale.US, Locale.JAPAN, Locale.CHINA);
class DiagnosticTester implements DiagnosticListener<JavaFileObject> {
Locale locale;
String result;
DiagnosticTester(Locale locale) {
this.locale = locale;
}
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
result = diagnostic.getMessage(locale); //6406133
}
}
class ProcessorTester extends AbstractProcessor {
Locale locale;
public Set<String> getSupportedAnnotationTypes() {
return new HashSet<String>(Arrays.asList("*"));
}
public void init(ProcessingEnvironment env) {
locale = env.getLocale();
}
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return true;
}
}
void compare(Locale loc1, Locale loc2, boolean useListener) {
String res1 = exec(useListener, loc1);
String res2 = exec(useListener, loc2);
boolean success = (loc1.equals(loc2) && res1.equals(res2)) ||
(!loc1.equals(loc2) && !res1.equals(res2));
if (!success)
throw new AssertionError("Error in diagnostic localization");
}
String exec(boolean useListener, Locale locale) {
final Iterable<? extends JavaFileObject> compilationUnits =
fm.getJavaFileObjects(new File(test_src, "Erroneous.java"));
StringWriter pw = new StringWriter();
DiagnosticTester listener = useListener ? new DiagnosticTester(locale) : null;
ProcessorTester processor = new ProcessorTester();
task = tool.getTask(pw, fm, listener, null, null, compilationUnits);
task.setProcessors(Arrays.asList(processor));
task.setLocale(locale); //6443132
task.call();
if (!processor.locale.equals(locale))
throw new AssertionError("Error in diagnostic localization during annotation processing");
String res = useListener ? listener.result : pw.toString();
System.err.println("[locale:"+ locale + ", listener:" + useListener + "] " +res);
return res;
}
void test() {
for (Locale l1 : locales) {
for (Locale l2 : locales) {
compare(l1, l2, true);
compare(l1, l2, false);
}
}
}
public static void main(String... args) throws Exception {
new T6406133().test();
}
}
class A {
boolean b;
boolean b;
}
\ No newline at end of file
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6731573
* @summary diagnostic output should optionally include source line
* @author Maurizio Cimadamore
* @library ../lib
*/
import java.io.*;
import java.util.*;
import javax.tools.*;
public class T6731573 extends ToolTester {
enum DiagnosticType {
BASIC(null) {
boolean shouldDisplaySource(SourceLine sourceLine) {
return sourceLine != SourceLine.DISABLED;
}
},
RAW("-XDrawDiagnostics") {
boolean shouldDisplaySource(SourceLine sourceLine) {
return sourceLine == SourceLine.ENABLED;
}
};
String optValue;
DiagnosticType(String optValue) {
this.optValue = optValue;
}
abstract boolean shouldDisplaySource(SourceLine sourceLine);
}
enum SourceLine {
STANDARD(null),
ENABLED("-XDshowSource=true"),
DISABLED("-XDshowSource=false");
String optValue;
SourceLine(String optValue) {
this.optValue = optValue;
}
}
void checkErrorLine(String output, boolean expected, List<String> options) {
System.err.println("\noptions = "+options);
System.err.println(output);
boolean errLinePresent = output.contains("^");
if (errLinePresent != expected) {
throw new AssertionError("Error in diagnostic: error line" +
(expected ? "" : " not") + " expected but" +
(errLinePresent ? "" : " not") + " found");
}
}
void exec(DiagnosticType diagType, SourceLine sourceLine) {
final Iterable<? extends JavaFileObject> compilationUnits =
fm.getJavaFileObjects(new File(test_src, "Erroneous.java"));
StringWriter pw = new StringWriter();
ArrayList<String> options = new ArrayList<String>();
if (diagType.optValue != null)
options.add(diagType.optValue);
if (sourceLine.optValue != null)
options.add(sourceLine.optValue);
task = tool.getTask(pw, fm, null, options, null, compilationUnits);
task.call();
checkErrorLine(pw.toString(),
diagType.shouldDisplaySource(sourceLine),
options);
}
void test() {
for (DiagnosticType dt : DiagnosticType.values()) {
for (SourceLine sl : SourceLine.values()) {
exec(dt, sl);
}
}
}
public static void main(String... args) throws Exception {
new T6731573().test();
}
}
\ No newline at end of file
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @author Maurizio Cimadamore
* @bug 6586091
* @summary javac crashes with StackOverflowError
* @compile T6586091.java
*/
class T6586091 {
static class A<T extends A<?>> {}
static class B extends A<A<?>> {}
A<A<?>> t = null;
B c = (B)t;
}
\ No newline at end of file
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6724345
*
* @summary incorrect method resolution for enum classes entered as source files
* @author Maurizio Cimadamore
*
* @compile T6509042.java
*/
class T6724345 {
interface I {
void i();
}
class U {
{
I i = E.V;
i.i();
E.V.i();
}
}
enum E implements I {
V {public void i() {}};
}
}
\ No newline at end of file
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6751514
* @summary Unary post-increment with type variables crash javac during lowering
* @author Maurizio Cimadamore
*/
public class T6751514 {
static class Foo<X> {
X x;
Foo (X x) {
this.x = x;
}
}
static void test1(Foo<Integer> foo) {
int start = foo.x;
equals(foo.x += 1, start + 1);
equals(foo.x++, start + 1);
equals(++foo.x, start + 3);
equals(foo.x--, start + 3);
equals(foo.x -= 1, start + 1);
equals(--foo.x, start);
}
static void test2(Foo<Integer> foo) {
int start = foo.x;
equals((foo.x) += 1, start + 1);
equals((foo.x)++, start + 1);
equals(++(foo.x), start + 3);
equals((foo.x)--, start + 3);
equals((foo.x) -= 1, start + 1);
equals(--(foo.x), start);
}
static void test3(Foo<Integer> foo) {
int start = foo.x;
equals(((foo.x)) += 1, start + 1);
equals(((foo.x))++, start + 1);
equals(++((foo.x)), start + 3);
equals(((foo.x))--, start + 3);
equals(((foo.x)) -= 1, start + 1);
equals(--((foo.x)), start);
}
public static void main(String[] args) {
test1(new Foo<Integer>(1));
test2(new Foo<Integer>(1));
test3(new Foo<Integer>(1));
}
static void equals(int found, int req) {
if (found != req) {
throw new AssertionError("Error (expected: "+ req +
" - found: " + found + ")");
}
}
}
\ No newline at end of file
......@@ -21,12 +21,4 @@
* have any questions.
*/
/*
* @test
* @bug 4266026
* @summary javac no longer follows symlinks
*
* @run shell links.sh
*/
class T extends a.B {}
......@@ -23,6 +23,12 @@
# have any questions.
#
# @test
# @bug 4266026
# @summary javac no longer follows symlinks
#
# @run shell links.sh
if [ "${TESTSRC}" = "" ]
then
......@@ -58,8 +64,11 @@ case "$OS" in
;;
esac
mkdir tmp
cp ${TESTSRC}/b/B.java tmp
rm -rf T.class B.class b/B.class "${TESTCLASSES}/a" "${TESTCLASSES}/classes"
ln -s "${TESTSRC}/b" "${TESTCLASSES}/a"
ln -s `pwd`/tmp "${TESTCLASSES}/a"
mkdir "${TESTCLASSES}/classes"
exec "${TESTJAVA}/bin/javac" ${TESTTOOLVMOPTS} -sourcepath "${TESTCLASSES}" -d "${TESTCLASSES}/classes" "${TESTSRC}/T.java" 2>&1
"${TESTJAVA}/bin/javac" ${TESTTOOLVMOPTS} -sourcepath "${TESTCLASSES}" -d "${TESTCLASSES}/classes" "${TESTSRC}/T.java" 2>&1
......@@ -118,10 +118,7 @@ public class T6348193 extends AbstractProcessor
// set up or remove a service configuration file
static void installConfigFile(NoGoodBad type) throws IOException {
URL self = T6348193.class.getClassLoader().getResource(myName+".class");
if (!self.getProtocol().equals("file"))
throw new AssertionError();
File f = new File(self.getFile()).getParentFile();
File f = new File(System.getProperty("test.classes", "."));
for (String s: new String[] { "META-INF", "services", Processor.class.getName() })
f = new File(f, s);
BufferedWriter out;
......
......@@ -37,7 +37,7 @@ public class BooleanConst extends Doclet
public static void main(String[] args) {
// run javadoc on package p
if (com.sun.tools.javadoc.Main.
execute("javadoc", "BooleanConst",
execute("javadoc", "BooleanConst", BooleanConst.class.getClassLoader(),
new String[] {System.getProperty("test.src", ".") + java.io.File.separatorChar + "BooleanConst.java"}) != 0)
throw new Error();
}
......
......@@ -41,6 +41,7 @@ public class BreakIteratorWarning extends Doclet {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"BreakIteratorWarning",
BreakIteratorWarning.class.getClassLoader(),
new String[] {"-Xwerror", thisFile}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
}
......
......@@ -40,6 +40,7 @@ public class FlagsTooEarly extends Doclet {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"FlagsTooEarly",
FlagsTooEarly.class.getClassLoader(),
new String[] {"-Xwerror", thisFile}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
}
......
......@@ -60,6 +60,7 @@ public class InlineTagsWithBraces extends Doclet {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"InlineTagsWithBraces",
InlineTagsWithBraces.class.getClassLoader(),
new String[] {"-Xwerror", thisFile}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
}
......
......@@ -43,6 +43,7 @@ public class LangVers extends Doclet {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"LangVers",
LangVers.class.getClassLoader(),
new String[] {"-source", "1.5", thisFile}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
}
......
......@@ -36,7 +36,7 @@ public class MethodLinks extends Doclet
{
public static void main(String[] args) {
if (com.sun.tools.javadoc.Main.
execute("javadoc", "MethodLinks",
execute("javadoc", "MethodLinks", MethodLinks.class.getClassLoader(),
new String[] {System.getProperty("test.src", ".") +
java.io.File.separatorChar + "MethodLinks.java"}
) != 0)
......
......@@ -44,7 +44,7 @@ public class NoStar extends Doclet
{
public static void main(String[] args) {
if (com.sun.tools.javadoc.Main.
execute("javadoc", "NoStar",
execute("javadoc", "NoStar", NoStar.class.getClassLoader(),
new String[] {System.getProperty("test.src", ".") + java.io.File.separatorChar + "NoStar.java"}) != 0)
throw new Error();
}
......
......@@ -55,7 +55,8 @@ public class T4994049 extends Doclet {
public static void main(String... args) {
for (String file : args) {
File source = new File(System.getProperty("test.src", "."), file);
if (execute("javadoc", "T4994049", new String[]{source.getPath()} ) != 0)
if (execute("javadoc", "T4994049", T4994049.class.getClassLoader(),
new String[]{source.getPath()} ) != 0)
throw new Error();
}
}
......
......@@ -36,7 +36,7 @@ public class XWerror extends Doclet
{
public static void main(String[] args) {
if (com.sun.tools.javadoc.Main.
execute("javadoc", "XWerror",
execute("javadoc", "XWerror", XWerror.class.getClassLoader(),
new String[] {"-Xwerror",
System.getProperty("test.src", ".") +
java.io.File.separatorChar +
......
......@@ -37,6 +37,7 @@ public class CompletionFailure extends Doclet
// run javadoc on package pkg
if (com.sun.tools.javadoc.Main.execute("javadoc",
"CompletionFailure",
CompletionFailure.class.getClassLoader(),
new String[]{"pkg"}) != 0)
throw new Error();
}
......
......@@ -36,7 +36,7 @@ public class DupOk extends Doclet
public static void main(String[] args) {
// run javadoc on package p
if (com.sun.tools.javadoc.Main.
execute("javadoc", "DupOk",
execute("javadoc", "DupOk", DupOk.class.getClassLoader(),
new String[]
{"-sourcepath",
System.getProperty("test.src", ".") + java.io.File.separatorChar + "sp1" +
......
......@@ -41,6 +41,7 @@ public class MissingImport extends Doclet {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"MissingImport",
MissingImport.class.getClassLoader(),
new String[] {thisFile}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
}
......
......@@ -89,7 +89,9 @@ public class Tester {
public void run() throws IOException {
try {
if (com.sun.tools.javadoc.Main.execute("javadoc",
docletName, args) != 0) {
docletName,
getClass().getClassLoader(),
args) != 0) {
throw new Error("Javadoc errors encountered.");
}
System.out.println("--> Output written to " + outputFile);
......
......@@ -39,7 +39,7 @@ public class NestedClass extends Doclet
public static void main(String[] args) {
if (com.sun.tools.javadoc.Main.
execute("javadoc", "NestedClass",
execute("javadoc", "NestedClass", NestedClass.class.getClassLoader(),
new String[] {System.getProperty("test.src", ".") +
java.io.File.separatorChar +
"NestedClass.java"})
......
......@@ -31,7 +31,7 @@ public class SourceOnly extends com.sun.javadoc.Doclet
public static void main(String[] args) {
// run javadoc on package p
int result = com.sun.tools.javadoc.Main.
execute("javadoc", "p.SourceOnly", new String[] {"p"});
execute("javadoc", "p.SourceOnly", SourceOnly.class.getClassLoader(), new String[] {"p"});
if (result != 0)
throw new Error();
}
......
......@@ -36,6 +36,7 @@ public class SourceOption extends Doclet {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"SourceOption",
SourceOption.class.getClassLoader(),
new String[] {"-source", "1.3", "p"}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
}
......
......@@ -36,6 +36,7 @@ public class SubpackageIgnore extends Doclet {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"SubpackageIgnore",
SubpackageIgnore.class.getClassLoader(),
new String[] {"-Xwerror",
"-sourcepath",
System.getProperty("test.src", "."),
......
......@@ -189,10 +189,7 @@ public class T6622260 {
void verify(String output) {
System.out.println(output);
if (output.startsWith("Classfile")) {
// make sure to ignore filename
output = output.substring(output.indexOf('\n'));
}
output = output.substring(output.indexOf("Test.java"));
if (output.indexOf("-") >= 0)
throw new Error("- found in output");
if (output.indexOf("FFFFFF") >= 0)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册