8345263: Make sure that lint categories are used correctly when logging lint warnings

Reviewed-by: vromero, jlahoda
This commit is contained in:
Maurizio Cimadamore 2024-12-16 10:20:13 +00:00
parent 32c8195c3a
commit dbffe33251
24 changed files with 530 additions and 392 deletions

View File

@ -48,6 +48,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
@ -87,9 +88,12 @@ public class ClassGenerator {
FACTORY_METHOD_DECL("factory.decl.method"),
FACTORY_METHOD_ARG("factory.decl.method.arg"),
FACTORY_METHOD_BODY("factory.decl.method.body"),
FACTORY_METHOD_BODY_LINT("factory.decl.method.body.lint"),
FACTORY_FIELD("factory.decl.field"),
FACTORY_FIELD_LINT("factory.decl.field.lint"),
WILDCARDS_EXTENDS("wildcards.extends"),
SUPPRESS_WARNINGS("suppress.warnings");
SUPPRESS_WARNINGS("suppress.warnings"),
LINT_CATEGORY("lint.category");
/** stub key (as it appears in the property file) */
String key;
@ -114,6 +118,7 @@ public class ClassGenerator {
enum FactoryKind {
ERR("err", "Error", "Errors"),
WARN("warn", "Warning", "Warnings"),
LINT_WARN("warn", "LintWarning", "LintWarnings"),
NOTE("note", "Note", "Notes"),
MISC("misc", "Fragment", "Fragments"),
OTHER(null, null, null);
@ -136,13 +141,24 @@ public class ClassGenerator {
/**
* Utility method for parsing a factory kind from a resource key prefix.
*/
static FactoryKind parseFrom(String prefix) {
static FactoryKind of(Entry<String, Message> messageEntry) {
String prefix = messageEntry.getKey().split("\\.")[1];
FactoryKind selected = null;
for (FactoryKind k : FactoryKind.values()) {
if (k.prefix == null || k.prefix.equals(prefix)) {
return k;
selected = k;
break;
}
}
return null;
if (selected == WARN) {
for (MessageLine line : messageEntry.getValue().getLines(false)) {
if (line.isLint()) {
selected = LINT_WARN;
break;
}
}
}
return selected;
}
}
@ -155,7 +171,7 @@ public class ClassGenerator {
messageFile.messages.entrySet().stream()
.collect(
Collectors.groupingBy(
e -> FactoryKind.parseFrom(e.getKey().split("\\.")[1]),
FactoryKind::of,
TreeMap::new,
toList()));
//generate nested classes
@ -165,7 +181,7 @@ public class ClassGenerator {
if (entry.getKey() == FactoryKind.OTHER) continue;
//emit members
String members = entry.getValue().stream()
.flatMap(e -> generateFactoryMethodsAndFields(e.getKey(), e.getValue()).stream())
.flatMap(e -> generateFactoryMethodsAndFields(entry.getKey(), e.getKey(), e.getValue()).stream())
.collect(Collectors.joining("\n\n"));
//emit nested class
String factoryDecl =
@ -230,7 +246,7 @@ public class ClassGenerator {
/**
* Generate a list of factory methods/fields to be added to a given factory nested class.
*/
List<String> generateFactoryMethodsAndFields(String key, Message msg) {
List<String> generateFactoryMethodsAndFields(FactoryKind k, String key, Message msg) {
MessageInfo msgInfo = msg.getMessageInfo();
List<MessageLine> lines = msg.getLines(false);
String javadoc = lines.stream()
@ -238,14 +254,27 @@ public class ClassGenerator {
.map(ml -> ml.text)
.collect(Collectors.joining("\n *"));
String[] keyParts = key.split("\\.");
FactoryKind k = FactoryKind.parseFrom(keyParts[1]);
String lintCategory = lines.stream()
.filter(MessageLine::isLint)
.map(MessageLine::lintCategory)
.findFirst().orElse(null);
//System.out.println("category for " + key + " = " + lintCategory);
String factoryName = factoryName(key);
if (msgInfo.getTypes().isEmpty()) {
//generate field
String factoryField = StubKind.FACTORY_FIELD.format(k.keyClazz, factoryName,
"\"" + keyParts[0] + "\"",
"\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"",
javadoc);
String factoryField;
if (lintCategory == null) {
factoryField = StubKind.FACTORY_FIELD.format(k.keyClazz, factoryName,
"\"" + keyParts[0] + "\"",
"\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"",
javadoc);
} else {
factoryField = StubKind.FACTORY_FIELD_LINT.format(k.keyClazz, factoryName,
StubKind.LINT_CATEGORY.format("\"" + lintCategory + "\""),
"\"" + keyParts[0] + "\"",
"\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"",
javadoc);
}
return Collections.singletonList(factoryField);
} else {
//generate method
@ -255,12 +284,22 @@ public class ClassGenerator {
List<String> argNames = argNames(types.size());
String suppressionString = needsSuppressWarnings(msgTypes) ?
StubKind.SUPPRESS_WARNINGS.format() : "";
String methodBody;
if (lintCategory == null) {
methodBody = StubKind.FACTORY_METHOD_BODY.format(k.keyClazz,
"\"" + keyParts[0] + "\"",
"\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"",
argNames.stream().collect(Collectors.joining(", ")));
} else {
methodBody = StubKind.FACTORY_METHOD_BODY_LINT.format(k.keyClazz,
StubKind.LINT_CATEGORY.format("\"" + lintCategory + "\""),
"\"" + keyParts[0] + "\"",
"\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"",
argNames.stream().collect(Collectors.joining(", ")));
}
String factoryMethod = StubKind.FACTORY_METHOD_DECL.format(suppressionString, k.keyClazz,
factoryName, argDecls(types, argNames).stream().collect(Collectors.joining(", ")),
indent(StubKind.FACTORY_METHOD_BODY.format(k.keyClazz,
"\"" + keyParts[0] + "\"",
"\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"",
argNames.stream().collect(Collectors.joining(", "))), 1),
indent(methodBody, 1),
javadoc);
factoryMethods.add(factoryMethod);
}

View File

@ -49,6 +49,9 @@ public final class Message {
public MessageInfo getMessageInfo() {
if (messageInfo == null) {
MessageLine l = firstLine.prev;
if (l != null && l.isLint()) {
l = l.prev;
}
if (l != null && l.isInfo())
messageInfo = new MessageInfo(l.text);
else
@ -71,7 +74,7 @@ public final class Message {
while (l.text.isEmpty())
l = l.next;
} else {
if (l.prev != null && l.prev.isInfo())
if (l.prev != null && (l.prev.isInfo() || l.prev.isLint()))
l = l.prev;
}

View File

@ -25,6 +25,7 @@
package propertiesparser.parser;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@ -37,6 +38,7 @@ public class MessageLine {
static final Pattern typePattern = Pattern.compile("[-\\\\'A-Z\\.a-z ]+( \\([-A-Za-z 0-9]+\\))?");
static final Pattern infoPattern = Pattern.compile(String.format("# ([0-9]+: %s, )*[0-9]+: %s",
typePattern.pattern(), typePattern.pattern()));
static final Pattern lintPattern = Pattern.compile("# lint: ([a-z\\-]+)");
public String text;
MessageLine prev;
@ -54,6 +56,19 @@ public class MessageLine {
return infoPattern.matcher(text).matches();
}
public boolean isLint() {
return lintPattern.matcher(text).matches();
}
public String lintCategory() {
Matcher matcher = lintPattern.matcher(text);
if (matcher.matches()) {
return matcher.group(1);
} else {
return null;
}
}
boolean hasContinuation() {
return (next != null) && text.endsWith("\\");
}

View File

@ -29,8 +29,10 @@ toplevel.decl=\
{1}\n\
import com.sun.tools.javac.util.JCDiagnostic.Error;\n\
import com.sun.tools.javac.util.JCDiagnostic.Warning;\n\
import com.sun.tools.javac.util.JCDiagnostic.LintWarning;\n\
import com.sun.tools.javac.util.JCDiagnostic.Note;\n\
import com.sun.tools.javac.util.JCDiagnostic.Fragment;\n\
import com.sun.tools.javac.code.Lint.LintCategory;\n\
\n\
public class {2} '{'\n\
{3}\n\
@ -58,16 +60,27 @@ factory.decl.method.arg=\
factory.decl.method.body=\
return new {0}({1}, {2}, {3});
factory.decl.method.body.lint=\
return new {0}({1}, {2}, {3}, {4});
factory.decl.field=\
/**\n\
' '* {4}\n\
' '*/\n\
public static final {0} {1} = new {0}({2}, {3});
factory.decl.field.lint=\
/**\n\
' '* {5}\n\
' '*/\n\
public static final {0} {1} = new {0}({2}, {3}, {4});
wildcards.extends=\
{0}<? extends {1}>
suppress.warnings=\
@SuppressWarnings("rawtypes")\n
lint.category=\
LintCategory.get({0})

View File

@ -33,7 +33,10 @@ import java.util.concurrent.ConcurrentHashMap;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.LintWarning;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.util.Pair;
@ -359,7 +362,7 @@ public class Lint
map.put(option, this);
}
static LintCategory get(String option) {
public static LintCategory get(String option) {
return map.get(option);
}
@ -385,6 +388,15 @@ public class Lint
return suppressedValues.contains(lc);
}
/**
* Helper method. Log a lint warning if its lint category is enabled.
*/
public void logIfEnabled(Log log, DiagnosticPosition pos, LintWarning warning) {
if (isEnabled(warning.getLintCategory())) {
log.warning(pos, warning);
}
}
protected static class AugmentVisitor implements Attribute.Visitor {
private final Context context;
private Symtab syms;

View File

@ -30,11 +30,13 @@ import com.sun.tools.javac.code.Source.Feature;
import com.sun.tools.javac.code.Symbol.ModuleSymbol;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.util.Assert;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.Error;
import com.sun.tools.javac.util.JCDiagnostic.LintWarning;
import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.Warning;
import com.sun.tools.javac.util.Log;
@ -175,8 +177,8 @@ public class Preview {
if (!lint.isSuppressed(LintCategory.PREVIEW)) {
sourcesWithPreviewFeatures.add(log.currentSourceFile());
previewHandler.report(pos, feature.isPlural() ?
Warnings.PreviewFeatureUsePlural(feature.nameFragment()) :
Warnings.PreviewFeatureUse(feature.nameFragment()));
LintWarnings.PreviewFeatureUsePlural(feature.nameFragment()) :
LintWarnings.PreviewFeatureUse(feature.nameFragment()));
}
}
@ -188,8 +190,8 @@ public class Preview {
public void warnPreview(JavaFileObject classfile, int majorVersion) {
Assert.check(isEnabled());
if (lint.isEnabled(LintCategory.PREVIEW)) {
log.mandatoryWarning(LintCategory.PREVIEW, null,
Warnings.PreviewFeatureUseClassfile(classfile, majorVersionToSource.get(majorVersion).name));
log.mandatoryWarning(null,
LintWarnings.PreviewFeatureUseClassfile(classfile, majorVersionToSource.get(majorVersion).name));
}
}
@ -197,7 +199,7 @@ public class Preview {
sourcesWithPreviewFeatures.add(log.currentSourceFile());
}
public void reportPreviewWarning(DiagnosticPosition pos, Warning warnKey) {
public void reportPreviewWarning(DiagnosticPosition pos, LintWarning warnKey) {
previewHandler.report(pos, warnKey);
}

View File

@ -58,6 +58,7 @@ import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
@ -1938,8 +1939,8 @@ public class Attr extends JCTree.Visitor {
public void visitSynchronized(JCSynchronized tree) {
chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
if (isValueBased(tree.lock.type)) {
env.info.lint.logIfEnabled(log, tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
}
attribStat(tree.body, env);
result = null;
@ -2045,9 +2046,8 @@ public class Attr extends JCTree.Visitor {
}
if (close.kind == MTH &&
close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
env.info.lint.isEnabled(LintCategory.TRY)) {
log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes())) {
env.info.lint.logIfEnabled(log, pos, LintWarnings.TryResourceThrowsInterruptedExc(resource));
}
}
}
@ -4446,9 +4446,8 @@ public class Attr extends JCTree.Visitor {
((VarSymbol)sitesym).isResourceVariable() &&
sym.kind == MTH &&
sym.name.equals(names.close) &&
sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
env.info.lint.isEnabled(LintCategory.TRY)) {
log.warning(LintCategory.TRY, tree, Warnings.TryExplicitCloseCall);
sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true)) {
env.info.lint.logIfEnabled(log, tree, LintWarnings.TryExplicitCloseCall);
}
// Disallow selecting a type from an expression
@ -4475,9 +4474,9 @@ public class Attr extends JCTree.Visitor {
// If the qualified item is not a type and the selected item is static, report
// a warning. Make allowance for the class of an array type e.g. Object[].class)
if (!sym.owner.isAnonymous()) {
chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
chk.lint.logIfEnabled(log, tree, LintWarnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
} else {
chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName()));
chk.lint.logIfEnabled(log, tree, LintWarnings.StaticNotQualifiedByType2(sym.kind.kindName()));
}
}
@ -4690,7 +4689,7 @@ public class Attr extends JCTree.Visitor {
if (s != null &&
s.isRaw() &&
!types.isSameType(v.type, v.erasure(types))) {
chk.warnUnchecked(tree.pos(), Warnings.UncheckedAssignToVar(v, s));
chk.warnUnchecked(tree.pos(), LintWarnings.UncheckedAssignToVar(v, s));
}
}
// The computed type of a variable is the type of the
@ -4888,7 +4887,7 @@ public class Attr extends JCTree.Visitor {
if (s != null && s.isRaw() &&
!types.isSameTypes(sym.type.getParameterTypes(),
sym.erasure(types).getParameterTypes())) {
chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedCallMbrOfRawType(sym, s));
chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedCallMbrOfRawType(sym, s));
}
}
@ -4938,7 +4937,7 @@ public class Attr extends JCTree.Visitor {
argtypes = argtypes.map(checkDeferredMap);
if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedMethInvocationApplied(kindName(sym),
chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedMethInvocationApplied(kindName(sym),
sym.name,
rs.methodArguments(sym.type.getParameterTypes()),
rs.methodArguments(argtypes.map(checkDeferredMap)),

View File

@ -28,7 +28,6 @@ package com.sun.tools.javac.comp;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToIntBiFunction;
@ -50,13 +49,14 @@ import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.Error;
import com.sun.tools.javac.util.JCDiagnostic.Fragment;
import com.sun.tools.javac.util.JCDiagnostic.Warning;
import com.sun.tools.javac.util.JCDiagnostic.LintWarning;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.code.Lint;
@ -79,11 +79,8 @@ import static com.sun.tools.javac.code.TypeTag.WILDCARD;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.ElementKindVisitor14;
/** Type checking helper class for the attribution phase.
@ -122,7 +119,7 @@ public class Check {
// The set of lint options currently in effect. It is initialized
// from the context, and then is set/reset as needed by Attr as it
// visits all the various parts of the trees during attribution.
private Lint lint;
Lint lint;
// The method being analyzed in Attr - it is set/reset as needed by
// Attr as it visits new method declarations.
@ -251,16 +248,16 @@ public class Check {
if (sym.isDeprecatedForRemoval()) {
if (!lint.isSuppressed(LintCategory.REMOVAL)) {
if (sym.kind == MDL) {
removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemovalModule(sym));
removalHandler.report(pos, LintWarnings.HasBeenDeprecatedForRemovalModule(sym));
} else {
removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemoval(sym, sym.location()));
removalHandler.report(pos, LintWarnings.HasBeenDeprecatedForRemoval(sym, sym.location()));
}
}
} else if (!lint.isSuppressed(LintCategory.DEPRECATION)) {
if (sym.kind == MDL) {
deprecationHandler.report(pos, Warnings.HasBeenDeprecatedModule(sym));
deprecationHandler.report(pos, LintWarnings.HasBeenDeprecatedModule(sym));
} else {
deprecationHandler.report(pos, Warnings.HasBeenDeprecated(sym, sym.location()));
deprecationHandler.report(pos, LintWarnings.HasBeenDeprecated(sym, sym.location()));
}
}
}
@ -269,7 +266,7 @@ public class Check {
* @param pos Position to be used for error reporting.
* @param msg A Warning describing the problem.
*/
public void warnPreviewAPI(DiagnosticPosition pos, Warning warnKey) {
public void warnPreviewAPI(DiagnosticPosition pos, LintWarning warnKey) {
if (!lint.isSuppressed(LintCategory.PREVIEW))
preview.reportPreviewWarning(pos, warnKey);
}
@ -280,7 +277,7 @@ public class Check {
*/
public void warnDeclaredUsingPreview(DiagnosticPosition pos, Symbol sym) {
if (!lint.isSuppressed(LintCategory.PREVIEW))
preview.reportPreviewWarning(pos, Warnings.DeclaredUsingPreview(kindName(sym), sym));
preview.reportPreviewWarning(pos, LintWarnings.DeclaredUsingPreview(kindName(sym), sym));
}
/** Log a preview warning.
@ -288,40 +285,18 @@ public class Check {
* @param msg A Warning describing the problem.
*/
public void warnRestrictedAPI(DiagnosticPosition pos, Symbol sym) {
if (lint.isEnabled(LintCategory.RESTRICTED))
log.warning(LintCategory.RESTRICTED, pos, Warnings.RestrictedMethod(sym.enclClass(), sym));
lint.logIfEnabled(log, pos, LintWarnings.RestrictedMethod(sym.enclClass(), sym));
}
/** Warn about unchecked operation.
* @param pos Position to be used for error reporting.
* @param msg A string describing the problem.
*/
public void warnUnchecked(DiagnosticPosition pos, Warning warnKey) {
public void warnUnchecked(DiagnosticPosition pos, LintWarning warnKey) {
if (!lint.isSuppressed(LintCategory.UNCHECKED))
uncheckedHandler.report(pos, warnKey);
}
/** Warn about unsafe vararg method decl.
* @param pos Position to be used for error reporting.
*/
void warnUnsafeVararg(DiagnosticPosition pos, Warning warnKey) {
if (lint.isEnabled(LintCategory.VARARGS))
log.warning(LintCategory.VARARGS, pos, warnKey);
}
public void warnStatic(DiagnosticPosition pos, Warning warnKey) {
if (lint.isEnabled(LintCategory.STATIC))
log.warning(LintCategory.STATIC, pos, warnKey);
}
/** Warn about division by integer constant zero.
* @param pos Position to be used for error reporting.
*/
void warnDivZero(DiagnosticPosition pos) {
if (lint.isEnabled(LintCategory.DIVZERO))
log.warning(LintCategory.DIVZERO, pos, Warnings.DivZero);
}
/**
* Report any deferred diagnostics.
*/
@ -674,9 +649,7 @@ public class Check {
&& !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
&& !is292targetTypeCast(tree)) {
deferredLintHandler.report(_l -> {
if (lint.isEnabled(LintCategory.CAST))
log.warning(LintCategory.CAST,
tree.pos(), Warnings.RedundantCast(tree.clazz.type));
lint.logIfEnabled(log, tree.pos(), LintWarnings.RedundantCast(tree.clazz.type));
});
}
}
@ -981,13 +954,13 @@ public class Check {
}
} else if (hasTrustMeAnno && varargElemType != null &&
types.isReifiable(varargElemType)) {
warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
lint.logIfEnabled(log, tree, LintWarnings.VarargsRedundantTrustmeAnno(
syms.trustMeType.tsym,
diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
}
else if (!hasTrustMeAnno && varargElemType != null &&
!types.isReifiable(varargElemType)) {
warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
warnUnchecked(tree.params.head.pos(), LintWarnings.UncheckedVarargsNonReifiableType(varargElemType));
}
}
//where
@ -1074,7 +1047,7 @@ public class Check {
if (!types.isReifiable(argtype) &&
(sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
!isTrustMeAllowedOnMethod(sym))) {
warnUnchecked(env.tree.pos(), Warnings.UncheckedGenericArrayCreation(argtype));
warnUnchecked(env.tree.pos(), LintWarnings.UncheckedGenericArrayCreation(argtype));
}
TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
}
@ -1350,11 +1323,7 @@ public class Check {
private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
try {
deferredLintHandler.report(_l -> {
if (lint.isEnabled(LintCategory.STRICTFP)) {
log.warning(LintCategory.STRICTFP,
pos, Warnings.Strictfp); }
});
deferredLintHandler.report(_ -> lint.logIfEnabled(log, pos, LintWarnings.Strictfp));
} finally {
deferredLintHandler.setPos(prevLintPos);
}
@ -1569,13 +1538,11 @@ public class Check {
}
void checkRaw(JCTree tree, Env<AttrContext> env) {
if (lint.isEnabled(LintCategory.RAW) &&
tree.type.hasTag(CLASS) &&
if (tree.type.hasTag(CLASS) &&
!TreeInfo.isDiamond(tree) &&
!withinAnonConstr(env) &&
tree.type.isRaw()) {
log.warning(LintCategory.RAW,
tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
lint.logIfEnabled(log, tree.pos(), LintWarnings.RawClassUse(tree.type, tree.type.tsym.type));
}
}
//where
@ -1877,7 +1844,7 @@ public class Check {
return;
} else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
Warnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres));
LintWarnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres));
}
// Error if overriding method throws an exception not reported
@ -1893,17 +1860,16 @@ public class Check {
}
else if (unhandledUnerased.nonEmpty()) {
warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
Warnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head));
LintWarnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head));
return;
}
// Optional warning if varargs don't agree
if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
&& lint.isEnabled(LintCategory.OVERRIDES)) {
log.warning(TreeInfo.diagnosticPositionFor(m, tree),
if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)) {
lint.logIfEnabled(log, TreeInfo.diagnosticPositionFor(m, tree),
((m.flags() & Flags.VARARGS) != 0)
? Warnings.OverrideVarargsMissing(varargsOverrides(m, other))
: Warnings.OverrideVarargsExtra(varargsOverrides(m, other)));
? LintWarnings.OverrideVarargsMissing(varargsOverrides(m, other))
: LintWarnings.OverrideVarargsExtra(varargsOverrides(m, other)));
}
// Warn if instance method overrides bridge method (compiler spec ??)
@ -2247,8 +2213,8 @@ public class Check {
someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
if (overridesEquals && !overridesHashCode) {
log.warning(LintCategory.OVERRIDES, pos,
Warnings.OverrideEqualsButNotHashcode(someClass));
log.warning(pos,
LintWarnings.OverrideEqualsButNotHashcode(someClass));
}
}
}
@ -2310,7 +2276,7 @@ public class Check {
String moduleNameComponentString = componentName.toString();
int nameLength = moduleNameComponentString.length();
if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName));
log.warning(pos, LintWarnings.PoorChoiceForModuleName(componentName));
}
}
}
@ -2781,8 +2747,8 @@ public class Check {
tree.pos();
// Log the warning
log.warning(LintCategory.OVERLOADS, pos,
Warnings.PotentiallyAmbiguousOverload(
log.warning(pos,
LintWarnings.PotentiallyAmbiguousOverload(
m1.asMemberOf(site, types), m1.location(),
m2.asMemberOf(site, types), m2.location()));
@ -3002,12 +2968,12 @@ public class Check {
isEffectivelyNonPublic(sym)) {
if (isLambda) {
if (belongsToRestrictedPackage(sym)) {
log.warning(LintCategory.SERIAL, tree.pos(),
Warnings.AccessToMemberFromSerializableLambda(sym));
log.warning(tree.pos(),
LintWarnings.AccessToMemberFromSerializableLambda(sym));
}
} else {
log.warning(tree.pos(),
Warnings.AccessToMemberFromSerializableElement(sym));
LintWarnings.AccessToMemberFromSerializableElement(sym));
}
}
}
@ -3790,14 +3756,13 @@ public class Check {
(s.flags() & DEPRECATED) != 0 &&
!syms.deprecatedType.isErroneous() &&
s.attribute(syms.deprecatedType.tsym) == null) {
log.warning(LintCategory.DEP_ANN,
pos, Warnings.MissingDeprecatedAnnotation);
log.warning(pos, LintWarnings.MissingDeprecatedAnnotation);
}
// Note: @Deprecated has no effect on local variables, parameters and package decls.
if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) {
if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
log.warning(LintCategory.DEPRECATION, pos,
Warnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
log.warning(pos,
LintWarnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
}
}
}
@ -3857,10 +3822,10 @@ public class Check {
log.error(pos, Errors.IsPreview(s));
} else {
preview.markUsesPreview(pos);
deferredLintHandler.report(_l -> warnPreviewAPI(pos, Warnings.IsPreview(s)));
deferredLintHandler.report(_l -> warnPreviewAPI(pos, LintWarnings.IsPreview(s)));
}
} else {
deferredLintHandler.report(_l -> warnPreviewAPI(pos, Warnings.IsPreviewReflective(s)));
deferredLintHandler.report(_l -> warnPreviewAPI(pos, LintWarnings.IsPreviewReflective(s)));
}
}
if (preview.declaredUsingPreviewFeature(s)) {
@ -4148,7 +4113,7 @@ public class Check {
int opc = ((OperatorSymbol)operator).opcode;
if (opc == ByteCodes.idiv || opc == ByteCodes.imod
|| opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
deferredLintHandler.report(_l -> warnDivZero(pos));
deferredLintHandler.report(_ -> lint.logIfEnabled(log, pos, LintWarnings.DivZero));
}
}
}
@ -4161,11 +4126,8 @@ public class Check {
*/
void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) {
if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) {
deferredLintHandler.report(_l -> {
if (lint.isEnabled(LintCategory.LOSSY_CONVERSIONS))
log.warning(LintCategory.LOSSY_CONVERSIONS,
pos, Warnings.PossibleLossOfPrecision(found, req));
});
deferredLintHandler.report(_ ->
lint.logIfEnabled(log, pos, LintWarnings.PossibleLossOfPrecision(found, req)));
}
}
@ -4173,9 +4135,9 @@ public class Check {
* Check for empty statements after if
*/
void checkEmptyIf(JCIf tree) {
if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
lint.isEnabled(LintCategory.EMPTY))
log.warning(LintCategory.EMPTY, tree.thenpart.pos(), Warnings.EmptyIf);
if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null) {
lint.logIfEnabled(log, tree.thenpart.pos(), LintWarnings.EmptyIf);
}
}
/** Check that symbol is unique in given scope.
@ -4317,13 +4279,12 @@ public class Check {
/** Check that an auxiliary class is not accessed from any other file than its own.
*/
void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
(c.flags() & AUXILIARY) != 0 &&
if ((c.flags() & AUXILIARY) != 0 &&
rs.isAccessible(env, c) &&
!fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
{
log.warning(pos,
Warnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
lint.logIfEnabled(log, pos,
LintWarnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
}
}
@ -4365,11 +4326,8 @@ public class Check {
// Warning may be suppressed by
// annotations; check again for being
// enabled in the deferred context.
deferredLintHandler.report(_l -> {
if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR))
log.warning(LintCategory.MISSING_EXPLICIT_CTOR,
pos, Warnings.MissingExplicitCtor(c, pkg, modle));
});
deferredLintHandler.report(_ ->
lint.logIfEnabled(log, pos, LintWarnings.MissingExplicitCtor(c, pkg, modle)));
} else {
return;
}
@ -4398,14 +4356,14 @@ public class Check {
if (warned) return; // suppress redundant diagnostics
switch (lint) {
case UNCHECKED:
Check.this.warnUnchecked(pos(), Warnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
Check.this.warnUnchecked(pos(), LintWarnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
break;
case VARARGS:
if (method != null &&
method.attribute(syms.trustMeType.tsym) != null &&
isTrustMeAllowedOnMethod(method) &&
!types.isReifiable(method.type.getParameterTypes().last())) {
Check.this.warnUnsafeVararg(pos(), Warnings.VarargsUnsafeUseVarargsParam(method.params.last()));
Check.this.lint.logIfEnabled(log, pos(), LintWarnings.VarargsUnsafeUseVarargsParam(method.params.last()));
}
break;
default:
@ -4660,7 +4618,7 @@ public class Check {
}
private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
if (!isAPISymbol(what) && !inSuperType) { //package private/private element
log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
log.warning(pos, LintWarnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
return ;
}
@ -4669,13 +4627,13 @@ public class Check {
ExportsDirective inExport = findExport(inPackage);
if (whatExport == null) { //package not exported:
log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
log.warning(pos, LintWarnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
return ;
}
if (whatExport.modules != null) {
if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
log.warning(pos, LintWarnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
}
}
@ -4697,36 +4655,32 @@ public class Check {
}
}
log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
log.warning(pos, LintWarnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
}
}
void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
if (msym.kind != MDL) {
deferredLintHandler.report(_l -> {
if (lint.isEnabled(LintCategory.MODULE))
log.warning(LintCategory.MODULE, pos, Warnings.ModuleNotFound(msym));
});
deferredLintHandler.report(_ ->
lint.logIfEnabled(log, pos, LintWarnings.ModuleNotFound(msym)));
}
}
void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
if (packge.members().isEmpty() &&
((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
deferredLintHandler.report(_l -> {
if (lint.isEnabled(LintCategory.OPENS))
log.warning(pos, Warnings.PackageEmptyOrNotFound(packge));
});
deferredLintHandler.report(_ ->
lint.logIfEnabled(log, pos, LintWarnings.PackageEmptyOrNotFound(packge)));
}
}
void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
deferredLintHandler.report(_l -> {
deferredLintHandler.report(_ -> {
if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) {
log.warning(pos, Warnings.RequiresTransitiveAutomatic);
} else if (lint.isEnabled(LintCategory.REQUIRES_AUTOMATIC)) {
log.warning(pos, Warnings.RequiresAutomatic);
log.warning(pos, LintWarnings.RequiresTransitiveAutomatic);
} else {
lint.logIfEnabled(log, pos, LintWarnings.RequiresAutomatic);
}
});
}
@ -5024,7 +4978,7 @@ public class Check {
}
if (svuidSym == null) {
log.warning(LintCategory.SERIAL, p.pos(), Warnings.MissingSVUID(c));
log.warning(p.pos(), LintWarnings.MissingSVUID(c));
}
// Check for serialPersistentFields to gate checks for
@ -5051,9 +5005,9 @@ public class Check {
// Note per JLS arrays are
// serializable even if the
// component type is not.
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(enclosed, tree),
Warnings.NonSerializableInstanceField);
log.warning(
TreeInfo.diagnosticPositionFor(enclosed, tree),
LintWarnings.NonSerializableInstanceField);
} else if (varType.hasTag(ARRAY)) {
ArrayType arrayType = (ArrayType)varType;
Type elementType = arrayType.elemtype;
@ -5062,9 +5016,9 @@ public class Check {
elementType = arrayType.elemtype;
}
if (!canBeSerialized(elementType)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(enclosed, tree),
Warnings.NonSerializableInstanceFieldArray(elementType));
log.warning(
TreeInfo.diagnosticPositionFor(enclosed, tree),
LintWarnings.NonSerializableInstanceFieldArray(elementType));
}
}
}
@ -5147,8 +5101,8 @@ public class Check {
}
}
}
log.warning(LintCategory.SERIAL, tree.pos(),
Warnings.ExternalizableMissingPublicNoArgCtor);
log.warning(tree.pos(),
LintWarnings.ExternalizableMissingPublicNoArgCtor);
} else {
// Approximate access to the no-arg constructor up in
// the superclass chain by checking that the
@ -5175,8 +5129,8 @@ public class Check {
// Handle nested classes and implicit this$0
(supertype.getNestingKind() == NestingKind.MEMBER &&
((supertype.flags() & STATIC) == 0)))
log.warning(LintCategory.SERIAL, tree.pos(),
Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
log.warning(tree.pos(),
LintWarnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
}
}
}
@ -5194,43 +5148,43 @@ public class Check {
// fields.
if ((svuid.flags() & (STATIC | FINAL)) !=
(STATIC | FINAL)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(svuid, tree),
Warnings.ImproperSVUID((Symbol)e));
log.warning(
TreeInfo.diagnosticPositionFor(svuid, tree),
LintWarnings.ImproperSVUID((Symbol)e));
}
// check svuid has type long
if (!svuid.type.hasTag(LONG)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(svuid, tree),
Warnings.LongSVUID((Symbol)e));
log.warning(
TreeInfo.diagnosticPositionFor(svuid, tree),
LintWarnings.LongSVUID((Symbol)e));
}
if (svuid.getConstValue() == null)
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(svuid, tree),
Warnings.ConstantSVUID((Symbol)e));
log.warning(
TreeInfo.diagnosticPositionFor(svuid, tree),
LintWarnings.ConstantSVUID((Symbol)e));
}
private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) {
// To be effective, serialPersisentFields must be private, static, and final.
if ((spf.flags() & (PRIVATE | STATIC | FINAL)) !=
(PRIVATE | STATIC | FINAL)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(spf, tree),
Warnings.ImproperSPF);
log.warning(
TreeInfo.diagnosticPositionFor(spf, tree),
LintWarnings.ImproperSPF);
}
if (!types.isSameType(spf.type, OSF_TYPE)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(spf, tree),
Warnings.OSFArraySPF);
log.warning(
TreeInfo.diagnosticPositionFor(spf, tree),
LintWarnings.OSFArraySPF);
}
if (isExternalizable((Type)(e.asType()))) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(spf, tree),
Warnings.IneffectualSerialFieldExternalizable);
log.warning(
TreeInfo.diagnosticPositionFor(spf, tree),
LintWarnings.IneffectualSerialFieldExternalizable);
}
// Warn if serialPersistentFields is initialized to a
@ -5240,8 +5194,8 @@ public class Check {
JCVariableDecl variableDef = (JCVariableDecl) spfDecl;
JCExpression initExpr = variableDef.init;
if (initExpr != null && TreeInfo.isNull(initExpr)) {
log.warning(LintCategory.SERIAL, initExpr.pos(),
Warnings.SPFNullInit);
log.warning(initExpr.pos(),
LintWarnings.SPFNullInit);
}
}
}
@ -5319,24 +5273,24 @@ public class Check {
private void checkExternMethodRecord(JCClassDecl tree, Element e, MethodSymbol method, Type argType,
boolean isExtern) {
if (isExtern && isExternMethod(tree, e, method, argType)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.IneffectualExternalizableMethodRecord(method.getSimpleName().toString()));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.IneffectualExternalizableMethodRecord(method.getSimpleName().toString()));
}
}
void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) {
var flags = method.flags();
if ((flags & PRIVATE) == 0) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.SerialMethodNotPrivate(method.getSimpleName()));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.SerialMethodNotPrivate(method.getSimpleName()));
}
if ((flags & STATIC) != 0) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.SerialMethodStatic(method.getSimpleName()));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.SerialMethodStatic(method.getSimpleName()));
}
}
@ -5359,18 +5313,18 @@ public class Check {
case FIELD -> {
var field = (VarSymbol)enclosed;
if (serialFieldNames.contains(name)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(field, tree),
Warnings.IneffectualSerialFieldEnum(name));
log.warning(
TreeInfo.diagnosticPositionFor(field, tree),
LintWarnings.IneffectualSerialFieldEnum(name));
}
}
case METHOD -> {
var method = (MethodSymbol)enclosed;
if (serialMethodNames.contains(name)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.IneffectualSerialMethodEnum(name));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.IneffectualSerialMethodEnum(name));
}
if (isExtern) {
@ -5408,9 +5362,9 @@ public class Check {
private void checkExternMethodEnum(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
if (isExternMethod(tree, e, method, argType)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.IneffectualExternMethodEnum(method.getSimpleName().toString()));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.IneffectualExternMethodEnum(method.getSimpleName().toString()));
}
}
@ -5440,9 +5394,9 @@ public class Check {
name = field.getSimpleName().toString();
switch(name) {
case "serialPersistentFields" -> {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(field, tree),
Warnings.IneffectualSerialFieldInterface);
log.warning(
TreeInfo.diagnosticPositionFor(field, tree),
LintWarnings.IneffectualSerialFieldInterface);
}
case "serialVersionUID" -> {
@ -5480,9 +5434,9 @@ public class Check {
Element e,
MethodSymbol method) {
if ((method.flags() & PRIVATE) == 0) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.NonPrivateMethodWeakerAccess);
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.NonPrivateMethodWeakerAccess);
}
}
@ -5490,9 +5444,9 @@ public class Check {
Element e,
MethodSymbol method) {
if ((method.flags() & DEFAULT) == DEFAULT) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.DefaultIneffective);
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.DefaultIneffective);
}
}
@ -5537,9 +5491,9 @@ public class Check {
var field = (VarSymbol)enclosed;
switch(name) {
case "serialPersistentFields" -> {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(field, tree),
Warnings.IneffectualSerialFieldRecord);
log.warning(
TreeInfo.diagnosticPositionFor(field, tree),
LintWarnings.IneffectualSerialFieldRecord);
}
case "serialVersionUID" -> {
@ -5561,9 +5515,9 @@ public class Check {
default -> {
if (serialMethodNames.contains(name)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.IneffectualSerialMethodRecord(name));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.IneffectualSerialMethodRecord(name));
}
}}
}}});
@ -5575,9 +5529,9 @@ public class Check {
Element enclosing,
MethodSymbol method) {
if ((method.flags() & (STATIC | ABSTRACT)) != 0) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.SerialConcreteInstanceMethod(method.getSimpleName()));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.SerialConcreteInstanceMethod(method.getSimpleName()));
}
}
@ -5592,9 +5546,9 @@ public class Check {
// checking.
Type rtype = method.getReturnType();
if (!types.isSameType(expectedReturnType, rtype)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.SerialMethodUnexpectedReturnType(method.getSimpleName(),
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.SerialMethodUnexpectedReturnType(method.getSimpleName(),
rtype, expectedReturnType));
}
}
@ -5608,17 +5562,17 @@ public class Check {
var parameters= method.getParameters();
if (parameters.size() != 1) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.SerialMethodOneArg(method.getSimpleName(), parameters.size()));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.SerialMethodOneArg(method.getSimpleName(), parameters.size()));
return;
}
Type parameterType = parameters.get(0).asType();
if (!types.isSameType(parameterType, expectedType)) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.SerialMethodParameterType(method.getSimpleName(),
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.SerialMethodParameterType(method.getSimpleName(),
expectedType,
parameterType));
}
@ -5637,18 +5591,18 @@ public class Check {
private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol method) {
var parameters = method.getParameters();
if (!parameters.isEmpty()) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(parameters.get(0), tree),
Warnings.SerialMethodNoArgs(method.getSimpleName()));
log.warning(
TreeInfo.diagnosticPositionFor(parameters.get(0), tree),
LintWarnings.SerialMethodNoArgs(method.getSimpleName()));
}
}
private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) {
// If the enclosing class is externalizable, warn for the method
if (isExternalizable((Type)enclosing.asType())) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.IneffectualSerialMethodExternalizable(method.getSimpleName()));
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.IneffectualSerialMethodExternalizable(method.getSimpleName()));
}
return;
}
@ -5675,9 +5629,9 @@ public class Check {
}
}
if (!declared) {
log.warning(LintCategory.SERIAL,
TreeInfo.diagnosticPositionFor(method, tree),
Warnings.SerialMethodUnexpectedException(method.getSimpleName(),
log.warning(
TreeInfo.diagnosticPositionFor(method, tree),
LintWarnings.SerialMethodUnexpectedException(method.getSimpleName(),
thrownType));
}
}

View File

@ -34,11 +34,11 @@ import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.LambdaExpressionTree.BodyKind;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
@ -60,8 +60,6 @@ import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
import com.sun.tools.javac.util.JCDiagnostic.Fragment;
import java.util.Arrays;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@ -726,11 +724,9 @@ public class Flow {
}
// Warn about fall-through if lint switch fallthrough enabled.
if (alive == Liveness.ALIVE &&
lint.isEnabled(Lint.LintCategory.FALLTHROUGH) &&
c.stats.nonEmpty() && l.tail.nonEmpty())
log.warning(Lint.LintCategory.FALLTHROUGH,
l.tail.head.pos(),
Warnings.PossibleFallThroughIntoCase);
lint.logIfEnabled(log, l.tail.head.pos(),
LintWarnings.PossibleFallThroughIntoCase);
}
tree.isExhaustive = tree.hasUnconditionalPattern ||
TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases);
@ -1237,11 +1233,8 @@ public class Flow {
scanStat(tree.finalizer);
tree.finallyCanCompleteNormally = alive != Liveness.DEAD;
if (alive == Liveness.DEAD) {
if (lint.isEnabled(Lint.LintCategory.FINALLY)) {
log.warning(Lint.LintCategory.FINALLY,
TreeInfo.diagEndPos(tree.finalizer),
Warnings.FinallyCannotComplete);
}
lint.logIfEnabled(log, TreeInfo.diagEndPos(tree.finalizer),
LintWarnings.FinallyCannotComplete);
} else {
while (exits.nonEmpty()) {
pendingExits.append(exits.next());
@ -2863,8 +2856,8 @@ public class Flow {
lint.isEnabled(Lint.LintCategory.TRY)) {
for (JCVariableDecl resVar : resourceVarDecls) {
if (unrefdResources.includes(resVar.sym) && !resVar.sym.isUnnamedVariable()) {
log.warning(Lint.LintCategory.TRY, resVar.pos(),
Warnings.TryResourceNotReferenced(resVar.sym));
log.warning(resVar.pos(),
LintWarnings.TryResourceNotReferenced(resVar.sym));
unrefdResources.remove(resVar.sym);
}
}

View File

@ -52,7 +52,6 @@ import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardLocation;
import com.sun.source.tree.ModuleTree.ModuleKind;
import com.sun.tools.javac.code.ClassFinder;
import com.sun.tools.javac.code.DeferredLintHandler;
import com.sun.tools.javac.code.Directive;
import com.sun.tools.javac.code.Directive.ExportsDirective;
@ -88,6 +87,7 @@ import com.sun.tools.javac.jvm.JNIWriter;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
@ -1275,8 +1275,8 @@ public class Modules extends JCTree.Visitor {
if (lintOptions) {
for (ModuleSymbol msym : limitMods) {
if (!observable.contains(msym)) {
log.warning(LintCategory.OPTIONS,
Warnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym));
log.warning(
LintWarnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym));
}
}
}
@ -1381,7 +1381,7 @@ public class Modules extends JCTree.Visitor {
.collect(Collectors.joining(","));
if (!incubatingModules.isEmpty()) {
log.warning(Warnings.IncubatingModules(incubatingModules));
log.warning(LintWarnings.IncubatingModules(incubatingModules));
}
}
@ -1731,8 +1731,8 @@ public class Modules extends JCTree.Visitor {
if (!unknownModules.contains(msym)) {
if (lintOptions) {
log.warning(LintCategory.OPTIONS,
Warnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym));
log.warning(
LintWarnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym));
}
unknownModules.add(msym);
}
@ -1770,7 +1770,7 @@ public class Modules extends JCTree.Visitor {
ModuleSymbol msym = syms.enterModule(names.fromString(sourceName));
if (!allModules.contains(msym)) {
if (lintOptions) {
log.warning(Warnings.ModuleForOptionNotFound(Option.ADD_READS, msym));
log.warning(LintWarnings.ModuleForOptionNotFound(Option.ADD_READS, msym));
}
continue;
}
@ -1790,7 +1790,7 @@ public class Modules extends JCTree.Visitor {
targetModule = syms.enterModule(names.fromString(targetName));
if (!allModules.contains(targetModule)) {
if (lintOptions) {
log.warning(LintCategory.OPTIONS, Warnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule));
log.warning(LintWarnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule));
}
continue;
}

View File

@ -31,12 +31,10 @@ import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
@ -53,6 +51,7 @@ import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
@ -63,7 +62,6 @@ import com.sun.tools.javac.util.JCDiagnostic;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Pair;
@ -424,12 +422,12 @@ class ThisEscapeAnalyzer extends TreeScanner {
previous = warning;
// Emit warnings showing the entire stack trace
JCDiagnostic.Warning key = Warnings.PossibleThisEscape;
JCDiagnostic.Warning key = LintWarnings.PossibleThisEscape;
int remain = warning.length;
do {
DiagnosticPosition pos = warning[--remain];
log.warning(Lint.LintCategory.THIS_ESCAPE, pos, key);
key = Warnings.PossibleThisEscapeLocation;
log.warning(pos, key);
key = LintWarnings.PossibleThisEscapeLocation;
} while (remain > 0);
}
warningList.clear();

View File

@ -29,8 +29,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
@ -41,7 +39,6 @@ import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Collection;
@ -56,13 +53,12 @@ import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.main.OptionHelper;
import com.sun.tools.javac.main.OptionHelper.GrumpyHelper;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.util.Abort;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.DefinedBy;
import com.sun.tools.javac.util.DefinedBy.Api;
@ -529,6 +525,6 @@ public abstract class BaseFileManager implements JavaFileManager {
// Check whether we've already opened this file for output
if (!outputFilesWritten.add(realPath))
log.warning(LintCategory.OUTPUT_FILE_CLASH, Warnings.OutputFileClash(path));
log.warning(LintWarnings.OutputFileClash(path));
}
}

View File

@ -77,10 +77,10 @@ import javax.tools.StandardJavaFileManager;
import javax.tools.StandardJavaFileManager.PathFactory;
import javax.tools.StandardLocation;
import com.sun.tools.javac.code.Lint;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import jdk.internal.jmod.JmodFile;
import com.sun.tools.javac.code.Lint;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
@ -224,7 +224,7 @@ public class Locations {
entries.add(getPath(s));
} catch (IllegalArgumentException e) {
if (warn) {
log.warning(LintCategory.PATH, Warnings.InvalidPath(s));
log.warning(LintWarnings.InvalidPath(s));
}
}
}
@ -319,8 +319,8 @@ public class Locations {
private void addDirectory(Path dir, boolean warn) {
if (!Files.isDirectory(dir)) {
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.DirPathElementNotFound(dir));
log.warning(
LintWarnings.DirPathElementNotFound(dir));
}
return;
}
@ -365,8 +365,8 @@ public class Locations {
if (!fsInfo.exists(file)) {
/* No such file or directory exists */
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.PathElementNotFound(file));
log.warning(
LintWarnings.PathElementNotFound(file));
}
super.add(file);
return;
@ -388,14 +388,14 @@ public class Locations {
try {
FileSystems.newFileSystem(file, (ClassLoader)null).close();
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.UnexpectedArchiveFile(file));
log.warning(
LintWarnings.UnexpectedArchiveFile(file));
}
} catch (IOException | ProviderNotFoundException e) {
// FIXME: include e.getLocalizedMessage in warning
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.InvalidArchiveFile(file));
log.warning(
LintWarnings.InvalidArchiveFile(file));
}
return;
}
@ -1660,9 +1660,9 @@ public class Locations {
if (!Files.isDirectory(prefix)) {
if (warn) {
Warning key = Files.exists(prefix)
? Warnings.DirPathElementNotDirectory(prefix)
: Warnings.DirPathElementNotFound(prefix);
log.warning(Lint.LintCategory.PATH, key);
? LintWarnings.DirPathElementNotDirectory(prefix)
: LintWarnings.DirPathElementNotFound(prefix);
log.warning(key);
}
return;
}

View File

@ -64,6 +64,7 @@ import com.sun.tools.javac.jvm.PoolConstant.NameAndType;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.ByteBuffer.UnderflowException;
@ -855,8 +856,8 @@ public class ClassReader {
if (lintClassfile && !warnedAttrs.contains(name)) {
JavaFileObject prev = log.useSource(currentClassFile);
try {
log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null,
Warnings.FutureAttr(name, version.major, version.minor, majorVersion, minorVersion));
log.warning((DiagnosticPosition) null,
LintWarnings.FutureAttr(name, version.major, version.minor, majorVersion, minorVersion));
} finally {
log.useSource(prev);
}
@ -1610,7 +1611,7 @@ public class ClassReader {
//the RuntimeVisibleParameterAnnotations and RuntimeInvisibleParameterAnnotations
//provide annotations for a different number of parameters, ignore:
if (lintClassfile) {
log.warning(LintCategory.CLASSFILE, Warnings.RuntimeVisibleInvisibleParamAnnotationsMismatch(currentClassFile));
log.warning(LintWarnings.RuntimeVisibleInvisibleParamAnnotationsMismatch(currentClassFile));
}
for (int pnum = 0; pnum < numParameters; pnum++) {
readAnnotations();
@ -2078,9 +2079,9 @@ public class ClassReader {
try {
if (lintClassfile) {
if (failure == null) {
log.warning(Warnings.AnnotationMethodNotFound(container, name));
log.warning(LintWarnings.AnnotationMethodNotFound(container, name));
} else {
log.warning(Warnings.AnnotationMethodNotFoundReason(container,
log.warning(LintWarnings.AnnotationMethodNotFoundReason(container,
name,
failure.getDetailValue()));//diagnostic, if present
}
@ -2960,7 +2961,7 @@ public class ClassReader {
private void dropParameterAnnotations() {
parameterAnnotations = null;
if (lintClassfile) {
log.warning(LintCategory.CLASSFILE, Warnings.RuntimeInvisibleParameterAnnotations(currentClassFile));
log.warning(LintWarnings.RuntimeInvisibleParameterAnnotations(currentClassFile));
}
}
/**

View File

@ -63,6 +63,7 @@ import com.sun.tools.javac.platform.PlatformDescription;
import com.sun.tools.javac.platform.PlatformUtils;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic;
@ -497,7 +498,7 @@ public class Arguments {
if (lintPaths) {
Path outDirParent = outDir.getParent();
if (outDirParent != null && Files.exists(outDirParent.resolve("module-info.class"))) {
log.warning(LintCategory.PATH, Warnings.OutdirIsInExplodedModule(outDir));
log.warning(LintWarnings.OutdirIsInExplodedModule(outDir));
}
}
}
@ -571,10 +572,10 @@ public class Arguments {
if (fm instanceof BaseFileManager baseFileManager) {
if (source.compareTo(Source.JDK8) <= 0) {
if (baseFileManager.isDefaultBootClassPath())
log.warning(LintCategory.OPTIONS, Warnings.SourceNoBootclasspath(source.name, releaseNote(source, targetString)));
log.warning(LintWarnings.SourceNoBootclasspath(source.name, releaseNote(source, targetString)));
} else {
if (baseFileManager.isDefaultSystemModulesPath())
log.warning(LintCategory.OPTIONS, Warnings.SourceNoSystemModulesPath(source.name, releaseNote(source, targetString)));
log.warning(LintWarnings.SourceNoSystemModulesPath(source.name, releaseNote(source, targetString)));
}
}
}
@ -584,14 +585,14 @@ public class Arguments {
if (source.compareTo(Source.MIN) < 0) {
log.error(Errors.OptionRemovedSource(source.name, Source.MIN.name));
} else if (source == Source.MIN && lintOptions) {
log.warning(LintCategory.OPTIONS, Warnings.OptionObsoleteSource(source.name));
log.warning(LintWarnings.OptionObsoleteSource(source.name));
obsoleteOptionFound = true;
}
if (target.compareTo(Target.MIN) < 0) {
log.error(Errors.OptionRemovedTarget(target, Target.MIN));
} else if (target == Target.MIN && lintOptions) {
log.warning(LintCategory.OPTIONS, Warnings.OptionObsoleteTarget(target));
log.warning(LintWarnings.OptionObsoleteTarget(target));
obsoleteOptionFound = true;
}
@ -625,7 +626,7 @@ public class Arguments {
}
if (obsoleteOptionFound && lintOptions) {
log.warning(LintCategory.OPTIONS, Warnings.OptionObsoleteSuppression);
log.warning(LintWarnings.OptionObsoleteSuppression);
}
SourceVersion sv = Source.toSourceVersion(source);
@ -636,7 +637,7 @@ public class Arguments {
validateDefaultModuleForCreatedFiles(sv);
if (lintOptions && options.isSet(Option.ADD_OPENS)) {
log.warning(LintCategory.OPTIONS, Warnings.AddopensIgnored);
log.warning(LintWarnings.AddopensIgnored);
}
return !errors && (log.nerrors == 0);

View File

@ -33,14 +33,13 @@ import com.sun.tools.javac.code.Source.Feature;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.*;
import java.nio.CharBuffer;
import java.util.Iterator;
import java.util.Set;
import static com.sun.tools.javac.parser.Tokens.*;
@ -222,13 +221,12 @@ public class JavaTokenizer extends UnicodeReader {
/**
* Report an error at the given position using the provided arguments.
*
* @param lc lint category.
* @param pos position in input buffer.
* @param key error key to report.
*/
protected void lexWarning(LintCategory lc, int pos, JCDiagnostic.Warning key) {
protected void lexWarning(int pos, JCDiagnostic.Warning key) {
DiagnosticPosition dp = new SimpleDiagnosticPosition(pos) ;
log.warning(lc, dp, key);
log.warning(dp, key);
}
/**
@ -1075,12 +1073,12 @@ public class JavaTokenizer extends UnicodeReader {
Set<TextBlockSupport.WhitespaceChecks> checks =
TextBlockSupport.checkWhitespace(string);
if (checks.contains(TextBlockSupport.WhitespaceChecks.INCONSISTENT)) {
lexWarning(LintCategory.TEXT_BLOCKS, pos,
Warnings.InconsistentWhiteSpaceIndentation);
lexWarning(pos,
LintWarnings.InconsistentWhiteSpaceIndentation);
}
if (checks.contains(TextBlockSupport.WhitespaceChecks.TRAILING)) {
lexWarning(LintCategory.TEXT_BLOCKS, pos,
Warnings.TrailingWhiteSpaceWillBeRemoved);
lexWarning(pos,
LintWarnings.TrailingWhiteSpaceWillBeRemoved);
}
}
// Remove incidental indentation.

View File

@ -42,6 +42,7 @@ import com.sun.tools.javac.file.PathFileObject;
import com.sun.tools.javac.parser.Tokens.*;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
@ -669,8 +670,8 @@ public class JavacParser implements Parser {
deferredLintHandler.report(lint -> {
if (lint.isEnabled(Lint.LintCategory.DANGLING_DOC_COMMENTS) &&
!shebang(c, pos)) {
log.warning(Lint.LintCategory.DANGLING_DOC_COMMENTS,
pos, Warnings.DanglingDocComment);
log.warning(
pos, LintWarnings.DanglingDocComment);
}
});
}

View File

@ -57,6 +57,7 @@ import com.sun.tools.javac.code.Symbol.ModuleSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.comp.Modules;
import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.DefinedBy.Api;
@ -492,7 +493,7 @@ public class JavacFiler implements Filer, Closeable {
String base = name.substring(periodIndex);
String extn = (isSourceFile ? ".java" : ".class");
if (base.equals(extn))
log.warning(Warnings.ProcSuspiciousClassName(name, extn));
log.warning(LintWarnings.ProcSuspiciousClassName(name, extn));
}
}
checkNameAndExistence(mod, name, isSourceFile);
@ -708,7 +709,7 @@ public class JavacFiler implements Filer, Closeable {
private void checkName(String name, boolean allowUnnamedPackageInfo) throws FilerException {
if (!SourceVersion.isName(name) && !isPackageInfo(name, allowUnnamedPackageInfo)) {
if (lint)
log.warning(Warnings.ProcIllegalFileName(name));
log.warning(LintWarnings.ProcIllegalFileName(name));
throw new FilerException("Illegal name " + name);
}
}
@ -737,11 +738,11 @@ public class JavacFiler implements Filer, Closeable {
containedInInitialInputs(typename);
if (alreadySeen) {
if (lint)
log.warning(Warnings.ProcTypeRecreate(typename));
log.warning(LintWarnings.ProcTypeRecreate(typename));
throw new FilerException("Attempt to recreate a file for type " + typename);
}
if (lint && existing != null) {
log.warning(Warnings.ProcTypeAlreadyExists(typename));
log.warning(LintWarnings.ProcTypeAlreadyExists(typename));
}
if (!mod.isUnnamed() && !typename.contains(".")) {
throw new FilerException("Attempt to create a type in unnamed package of a named module: " + typename);
@ -771,7 +772,7 @@ public class JavacFiler implements Filer, Closeable {
private void checkFileReopening(FileObject fileObject, boolean forWriting) throws FilerException {
if (isInFileObjectHistory(fileObject, forWriting)) {
if (lint)
log.warning(Warnings.ProcFileReopening(fileObject.getName()));
log.warning(LintWarnings.ProcFileReopening(fileObject.getName()));
throw new FilerException("Attempt to reopen a file for path " + fileObject.getName());
}
if (forWriting)

View File

@ -66,6 +66,7 @@ import com.sun.tools.javac.model.JavacTypes;
import com.sun.tools.javac.platform.PlatformDescription;
import com.sun.tools.javac.platform.PlatformDescription.PluginInfo;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
@ -648,7 +649,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
add(importStringToPattern(allowModules, annotationPattern,
processor, log, lint));
if (lint && !patternAdded) {
log.warning(Warnings.ProcDuplicateSupportedAnnotation(annotationPattern,
log.warning(LintWarnings.ProcDuplicateSupportedAnnotation(annotationPattern,
p.getClass().getName()));
}
}
@ -662,7 +663,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
if (lint &&
supportedAnnotationPatterns.contains(MatchingUtils.validImportStringToPattern("*")) &&
supportedAnnotationPatterns.size() > 1) {
log.warning(Warnings.ProcRedundantTypesWithWildcard(p.getClass().getName()));
log.warning(LintWarnings.ProcRedundantTypesWithWildcard(p.getClass().getName()));
}
supportedOptionNames = new LinkedHashSet<>();
@ -670,7 +671,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
if (checkOptionName(optionName, log)) {
boolean optionAdded = supportedOptionNames.add(optionName);
if (lint && !optionAdded) {
log.warning(Warnings.ProcDuplicateOptionName(optionName,
log.warning(LintWarnings.ProcDuplicateOptionName(optionName,
p.getClass().getName()));
}
}
@ -891,7 +892,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
// Remove annotations processed by javac
unmatchedAnnotations.keySet().removeAll(platformAnnotations);
if (unmatchedAnnotations.size() > 0) {
log.warning(Warnings.ProcAnnotationsWithoutProcessors(unmatchedAnnotations.keySet()));
log.warning(LintWarnings.ProcAnnotationsWithoutProcessors(unmatchedAnnotations.keySet()));
}
}
@ -1688,7 +1689,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
private static Pattern warnAndNoMatches(String s, Processor p, Log log, boolean lint) {
if (lint) {
log.warning(Warnings.ProcMalformedSupportedString(s, p.getClass().getName()));
log.warning(LintWarnings.ProcMalformedSupportedString(s, p.getClass().getName()));
}
return noMatches; // won't match any valid identifier
}

View File

@ -708,9 +708,11 @@ compiler.err.not.in.profile=\
compiler.warn.forward.ref=\
reference to variable ''{0}'' before it has been initialized
# lint: this-escape
compiler.warn.possible.this.escape=\
possible ''this'' escape before subclass is fully initialized
# lint: this-escape
compiler.warn.possible.this.escape.location=\
previous possible ''this'' escape happens here via invocation
@ -731,9 +733,11 @@ compiler.err.illegal.line.end.in.char.lit=\
compiler.err.illegal.text.block.open=\
illegal text block open delimiter sequence, missing line terminator
# lint: text-blocks
compiler.warn.inconsistent.white.space.indentation=\
inconsistent white space indentation
# lint: text-blocks
compiler.warn.trailing.white.space.will.be.removed=\
trailing white space will be removed
@ -1591,6 +1595,7 @@ compiler.err.multi-module.outdir.cannot.be.exploded.module=\
in multi-module mode, the output directory cannot be an exploded module: {0}
# 0: path
# lint: path
compiler.warn.outdir.is.in.exploded.module=\
the output directory is within an exploded module: {0}
@ -1658,6 +1663,7 @@ compiler.warn.file.from.future=\
Modification date is in the future for file {0}
# 0: path
# lint: output-file-clash
compiler.warn.output.file.clash=\
output file written more than once: {0}
@ -1870,47 +1876,59 @@ compiler.warn.lintOption=\
[{0}]\u0020
# 0: symbol
# lint: serial
compiler.warn.constant.SVUID=\
serialVersionUID must be constant in class {0}
# lint: dangling
compiler.warn.dangling.doc.comment=\
documentation comment is not attached to any declaration
# 0: path
# lint: path
compiler.warn.dir.path.element.not.found=\
bad path element "{0}": no such directory
# 0: file name
# lint: path
compiler.warn.dir.path.element.not.directory=\
bad path element "{0}": not a directory
# 0: symbol, 1: symbol, 2: symbol
# lint: missing-explicit-ctor
compiler.warn.missing-explicit-ctor=\
class {0} in exported package {1} declares no explicit constructors, thereby exposing a default constructor to clients of module {2}
# lint: strictfp
compiler.warn.strictfp=\
as of release 17, all floating-point expressions are evaluated strictly and ''strictfp'' is not required
# lint: finally
compiler.warn.finally.cannot.complete=\
finally clause cannot complete normally
# 0: name
# lint: module
compiler.warn.poor.choice.for.module.name=\
module name component {0} should avoid terminal digits
# 0: string
# lint: incubating
compiler.warn.incubating.modules=\
using incubating module(s): {0}
# 0: symbol, 1: symbol
# lint: deprecation
compiler.warn.has.been.deprecated=\
{0} in {1} has been deprecated
# 0: symbol, 1: symbol
# lint: removal
compiler.warn.has.been.deprecated.for.removal=\
{0} in {1} has been deprecated and marked for removal
# 0: symbol
# lint: preview
compiler.warn.is.preview=\
{0} is a preview API and may be removed in a future release.
@ -1920,19 +1938,23 @@ compiler.err.is.preview=\
(use --enable-preview to enable preview APIs)
# 0: symbol
# lint: preview
compiler.warn.is.preview.reflective=\
{0} is a reflective preview API and may be removed in a future release.
# 0: symbol, 1: symbol
# lint: restricted
compiler.warn.restricted.method=\
{0}.{1} is a restricted method.\n\
(Restricted methods are unsafe and, if used incorrectly, might crash the Java runtime or corrupt memory)
# 0: symbol
# lint: deprecation
compiler.warn.has.been.deprecated.module=\
module {0} has been deprecated
# 0: symbol
# lint: removal
compiler.warn.has.been.deprecated.for.removal.module=\
module {0} has been deprecated and marked for removal
@ -1944,12 +1966,15 @@ compiler.warn.illegal.char.for.encoding=\
unmappable character for encoding {0}
# 0: symbol
# lint: serial
compiler.warn.improper.SVUID=\
serialVersionUID must be declared static final in class {0}
# lint: serial
compiler.warn.improper.SPF=\
serialPersistentFields must be declared private static final to be effective
# lint: serial
compiler.warn.SPF.null.init=\
serialPersistentFields ineffective if initialized to null.\n\
Initialize to an empty array to indicate no fields
@ -1972,112 +1997,141 @@ compiler.warn.unreachable.catch.1=\
thrown types {0} have already been caught
# 0: symbol
# lint: serial
compiler.warn.long.SVUID=\
serialVersionUID must be of type long in class {0}
# lint: serial
compiler.warn.OSF.array.SPF=\
serialPersistentFields must be of type java.io.ObjectStreamField[] to be effective
# 0: symbol
# lint: serial
compiler.warn.missing.SVUID=\
serializable class {0} has no definition of serialVersionUID
# 0: name
# lint: serial
compiler.warn.serializable.missing.access.no.arg.ctor=\
cannot access a no-arg constructor in first non-serializable superclass {0}
# 0: name
# lint: serial
compiler.warn.serial.method.not.private=\
serialization-related method {0} not declared private
# 0: name
# lint: serial
compiler.warn.serial.concrete.instance.method=\
serialization-related method {0} must be a concrete instance method to be effective, neither abstract nor static
# 0: name
# lint: serial
compiler.warn.serial.method.static=\
serialization-related method {0} declared static; must instead be an instance method to be effective
# 0: name
# lint: serial
compiler.warn.serial.method.no.args=\
to be effective serialization-related method {0} must have no parameters
# 0: name, 1: number
# lint: serial
compiler.warn.serial.method.one.arg=\
to be effective serialization-related method {0} must have exactly one parameter rather than {1} parameters
# 0: name, 1: type, 2: type
# lint: serial
compiler.warn.serial.method.parameter.type=\
sole parameter of serialization-related method {0} must have type {1} to be effective rather than type {2}
# 0: name, 1: type, 2: type
# lint: serial
compiler.warn.serial.method.unexpected.return.type=\
serialization-related method {0} declared with a return type of {1} rather than expected type {2}.\n\
As declared, the method will be ineffective for serialization
# 0: name, 1: type
# lint: serial
compiler.warn.serial.method.unexpected.exception=\
serialization-related method {0} declared to throw an unexpected type {1}
# lint: serial
compiler.warn.ineffectual.serial.field.interface=\
serialPersistentFields is not effective in an interface
# 0: string
# lint: serial
compiler.warn.ineffectual.serial.field.enum=\
serialization-related field {0} is not effective in an enum class
# 0: string
# lint: serial
compiler.warn.ineffectual.serial.method.enum=\
serialization-related method {0} is not effective in an enum class
# 0: string
# lint: serial
compiler.warn.ineffectual.extern.method.enum=\
externalization-related method {0} is not effective in an enum class
# lint: serial
compiler.warn.ineffectual.serial.field.record=\
serialPersistentFields is not effective in a record class
# 0: string
# lint: serial
compiler.warn.ineffectual.serial.method.record=\
serialization-related method {0} is not effective in a record class
# 0: string
# lint: serial
compiler.warn.ineffectual.externalizable.method.record=\
externalization-related method {0} is not effective in a record class
# 0: name
# lint: serial
compiler.warn.ineffectual.serial.method.externalizable=\
serialization-related method {0} is not effective in an Externalizable class
# lint: serial
compiler.warn.ineffectual.serial.field.externalizable=\
serialPersistentFields is not effective in an Externalizable class
# lint: serial
compiler.warn.externalizable.missing.public.no.arg.ctor=\
an Externalizable class needs a public no-arg constructor
# lint: serial
compiler.warn.non.serializable.instance.field=\
non-transient instance field of a serializable class declared with a non-serializable type
# 0: type
# lint: serial
compiler.warn.non.serializable.instance.field.array=\
non-transient instance field of a serializable class declared with an array having a non-serializable base component type {0}
# lint: serial
compiler.warn.non.private.method.weaker.access=\
serialization-related method declared non-private in an interface will prevent\n\
classes implementing the interface from declaring the method as private
# lint: serial
compiler.warn.default.ineffective=\
serialization-related default method from an interface will not be run by serialization for an implementing class
# 0: symbol, 1: symbol, 2: symbol, 3: symbol
# lint: overloads
compiler.warn.potentially.ambiguous.overload=\
{0} in {1} is potentially ambiguous with {2} in {3}
# 0: message segment
# lint: overrides
compiler.warn.override.varargs.missing=\
{0}; overridden method has no ''...''
# 0: message segment
# lint: overrides
compiler.warn.override.varargs.extra=\
{0}; overriding method is missing ''...''
@ -2090,13 +2144,16 @@ compiler.warn.pkg-info.already.seen=\
a package-info.java file has already been seen for package {0}
# 0: path
# lint: path
compiler.warn.path.element.not.found=\
bad path element "{0}": no such file or directory
# lint: fallthrough
compiler.warn.possible.fall-through.into.case=\
possible fall-through into case
# 0: type
# lint: cast
compiler.warn.redundant.cast=\
redundant cast to {0}
@ -2114,18 +2171,22 @@ compiler.warn.invalid.utf8.in.classfile=\
{0}: classfile contains invalid UTF-8: {1}
# 0: kind name, 1: symbol
# lint: static
compiler.warn.static.not.qualified.by.type=\
static {0} should be qualified by type name, {1}, instead of by an expression
# 0: kind name
# lint: static
compiler.warn.static.not.qualified.by.type2=\
static {0} should not be used as a member of an anonymous class
# 0: string, 1: fragment
# lint: options
compiler.warn.source.no.bootclasspath=\
bootstrap class path is not set in conjunction with -source {0}\n{1}
# 0: string, 1: fragment
# lint: options
compiler.warn.source.no.system.modules.path=\
location of system modules is not set in conjunction with -source {0}\n{1}
@ -2150,10 +2211,12 @@ compiler.misc.source.no.system.modules.path.with.target=\
--release {0} is recommended instead of -source {0} -target {1} because it sets the location of system modules automatically
# 0: string
# lint: options
compiler.warn.option.obsolete.source=\
source value {0} is obsolete and will be removed in a future release
# 0: target
# lint: options
compiler.warn.option.obsolete.target=\
target value {0} is obsolete and will be removed in a future release
@ -2165,16 +2228,20 @@ compiler.err.option.removed.source=\
compiler.err.option.removed.target=\
Target option {0} is no longer supported. Use {1} or later.
# lint: options
compiler.warn.option.obsolete.suppression=\
To suppress warnings about obsolete options, use -Xlint:-options.
# 0: name, 1: number, 2: number, 3: number, 4: number
# lint: classfile
compiler.warn.future.attr=\
{0} attribute introduced in version {1}.{2} class files is ignored in version {3}.{4} class files
# lint: requires-automatic
compiler.warn.requires.automatic=\
requires directive for an automatic module
# lint: requires-transitive-automatic
compiler.warn.requires.transitive.automatic=\
requires transitive directive for an automatic module
@ -2184,22 +2251,27 @@ compiler.warn.proc.package.does.not.exist=\
package {0} does not exist
# 0: string
# lint: processing
compiler.warn.proc.file.reopening=\
Attempt to create a file for ''{0}'' multiple times
# 0: string
# lint: processing
compiler.warn.proc.type.already.exists=\
A file for type ''{0}'' already exists on the sourcepath or classpath
# 0: string
# lint: processing
compiler.warn.proc.type.recreate=\
Attempt to create a file for type ''{0}'' multiple times
# 0: string
# lint: processing
compiler.warn.proc.illegal.file.name=\
Cannot create file for illegal name ''{0}''.
# 0: string, 1: string
# lint: processing
compiler.warn.proc.suspicious.class.name=\
Creating file for a type whose name ends in {1}: ''{0}''
@ -2208,10 +2280,12 @@ compiler.warn.proc.file.create.last.round=\
File for type ''{0}'' created in the last round will not be subject to annotation processing.
# 0: string, 1: string
# lint: processing
compiler.warn.proc.malformed.supported.string=\
Malformed string ''{0}'' for a supported annotation interface returned by processor ''{1}''
# 0: set of string
# lint: processing
compiler.warn.proc.annotations.without.processors=\
No processor claimed any of these annotations: {0}
@ -2220,15 +2294,18 @@ compiler.warn.proc.processor.incompatible.source.version=\
Supported source version ''{0}'' from annotation processor ''{1}'' less than -source ''{2}''
# 0: string, 1: string
# lint: processing
compiler.warn.proc.duplicate.option.name=\
Duplicate supported option ''{0}'' returned by annotation processor ''{1}''
# 0: string, 1: string
# lint: processing
compiler.warn.proc.duplicate.supported.annotation=\
Duplicate supported annotation interface ''{0}'' returned by annotation processor ''{1}''
# 0: string
# lint: processing
compiler.warn.proc.redundant.types.with.wildcard=\
Annotation processor ''{0}'' redundantly supports both ''*'' and other annotation interfaces
@ -2256,57 +2333,71 @@ compiler.warn.proc.unclosed.type.files=\
compiler.warn.proc.unmatched.processor.options=\
The following options were not recognized by any processor: ''{0}''
# lint: try
compiler.warn.try.explicit.close.call=\
explicit call to close() on an auto-closeable resource
# 0: symbol
# lint: try
compiler.warn.try.resource.not.referenced=\
auto-closeable resource {0} is never referenced in body of corresponding try statement
# 0: type
# lint: try
compiler.warn.try.resource.throws.interrupted.exc=\
auto-closeable resource {0} has a member method close() that could throw InterruptedException
# lint: unchecked
compiler.warn.unchecked.assign=\
unchecked assignment: {0} to {1}
# 0: symbol, 1: type
# lint: unchecked
compiler.warn.unchecked.assign.to.var=\
unchecked assignment to variable {0} as member of raw type {1}
# 0: symbol, 1: type
# lint: unchecked
compiler.warn.unchecked.call.mbr.of.raw.type=\
unchecked call to {0} as a member of the raw type {1}
# lint: unchecked
compiler.warn.unchecked.cast.to.type=\
unchecked cast to type {0}
# 0: kind name, 1: name, 2: object, 3: object, 4: kind name, 5: symbol
# lint: unchecked
compiler.warn.unchecked.meth.invocation.applied=\
unchecked method invocation: {0} {1} in {4} {5} is applied to given types\n\
required: {2}\n\
found: {3}
# 0: type
# lint: unchecked
compiler.warn.unchecked.generic.array.creation=\
unchecked generic array creation for varargs parameter of type {0}
# 0: type
# lint: unchecked
compiler.warn.unchecked.varargs.non.reifiable.type=\
Possible heap pollution from parameterized vararg type {0}
# 0: symbol
# lint: varargs
compiler.warn.varargs.unsafe.use.varargs.param=\
Varargs method could cause heap pollution from non-reifiable varargs parameter {0}
# lint: dep-ann
compiler.warn.missing.deprecated.annotation=\
deprecated item is not annotated with @Deprecated
# 0: kind name
# lint: deprecation
compiler.warn.deprecated.annotation.has.no.effect=\
@Deprecated annotation has no effect on this {0} declaration
# 0: string
# lint: path
compiler.warn.invalid.path=\
Invalid filename: {0}
@ -2319,10 +2410,12 @@ compiler.err.invalid.path=\
# 0: path
# lint: path
compiler.warn.invalid.archive.file=\
Unexpected file on path: {0}
# 0: path
# lint: path
compiler.warn.unexpected.archive.file=\
Unexpected extension for archive file: {0}
@ -2330,17 +2423,21 @@ compiler.warn.unexpected.archive.file=\
compiler.err.no.zipfs.for.archive=\
No file system provider is available to handle this file: {0}
# lint: divzero
compiler.warn.div.zero=\
division by zero
# lint: empty
compiler.warn.empty.if=\
empty statement after if
# 0: type, 1: name
# lint: classfile
compiler.warn.annotation.method.not.found=\
Cannot find annotation method ''{1}()'' in type ''{0}''
# 0: type, 1: name, 2: message segment
# lint: classfile
compiler.warn.annotation.method.not.found.reason=\
Cannot find annotation method ''{1}()'' in type ''{0}'': {2}
@ -2359,6 +2456,7 @@ compiler.warn.unknown.enum.constant.reason=\
reason: {3}
# 0: type, 1: type
# lint: rawtypes
compiler.warn.raw.class.use=\
found raw type: {0}\n\
missing type arguments for generic class {1}
@ -2376,14 +2474,17 @@ compiler.warn.method.redundant.typeargs=\
Redundant type arguments in method call.
# 0: symbol, 1: message segment
# lint: varargs
compiler.warn.varargs.redundant.trustme.anno=\
Redundant {0} annotation. {1}
# 0: symbol
# lint: serial
compiler.warn.access.to.member.from.serializable.element=\
access to member {0} from serializable element can be publicly accessible to untrusted code
# 0: symbol
# lint: serial
compiler.warn.access.to.member.from.serializable.lambda=\
access to member {0} from serializable lambda can be publicly accessible to untrusted code
@ -2541,12 +2642,14 @@ compiler.misc.bad.enclosing.method=\
bad enclosing method attribute for class {0}
# 0: file name
# lint: classfile
compiler.warn.runtime.visible.invisible.param.annotations.mismatch=\
the length of parameters in RuntimeVisibleParameterAnnotations attribute and \
RuntimeInvisibleParameterAnnotations attribute in: {0} \
do not match, ignoring both attributes
# 0: file name
# lint: classfile
compiler.warn.runtime.invisible.parameter.annotations=\
the RuntimeVisibleParameterAnnotations and RuntimeInvisibleParameterAnnotations attributes \
in: {0} \
@ -2673,6 +2776,7 @@ compiler.misc.prob.found.req=\
incompatible types: {0}
# 0: message segment, 1: type, 2: type
# lint: unchecked
compiler.warn.prob.found.req=\
{0}\n\
required: {2}\n\
@ -2687,6 +2791,7 @@ compiler.misc.possible.loss.of.precision=\
possible lossy conversion from {0} to {1}
# 0: type, 1: type
# lint: lossy-conversions
compiler.warn.possible.loss.of.precision=\
implicit cast from {0} to {1} in compound assignment is possibly lossy
@ -2862,6 +2967,7 @@ compiler.misc.varargs.argument.mismatch=\
#####
# 0: symbol or type, 1: file name
# lint: auxiliaryclass
compiler.warn.auxiliary.class.accessed.from.outside.of.its.source.file=\
auxiliary class {0} in {1} should not be accessed from outside its own source file
@ -3066,16 +3172,19 @@ compiler.err.override.incompatible.ret=\
return type {1} is not compatible with {2}
# 0: message segment, 1: type, 2: type
# lint: unchecked
compiler.warn.override.unchecked.ret=\
{0}\n\
return type requires unchecked conversion from {1} to {2}
# 0: message segment, 1: type
# lint: unchecked
compiler.warn.override.unchecked.thrown=\
{0}\n\
overridden method does not throw {1}
# 0: symbol
# lint: overrides
compiler.warn.override.equals.but.not.hashcode=\
Class {0} overrides equals, but neither it nor any superclass overrides hashCode method
@ -3168,14 +3277,17 @@ compiler.err.preview.feature.disabled.classfile=\
(use --enable-preview to allow loading of class files which contain preview features)
# 0: message segment (feature)
# lint: preview
compiler.warn.preview.feature.use=\
{0} is a preview feature and may be removed in a future release.
# 0: message segment (feature)
# lint: preview
compiler.warn.preview.feature.use.plural=\
{0} are a preview feature and may be removed in a future release.
# 0: file object (classfile), 1: string (expected version)
# lint: preview
compiler.warn.preview.feature.use.classfile=\
class file for {0} uses preview features of Java SE {1}.
@ -3558,6 +3670,7 @@ compiler.err.module.not.found=\
module not found: {0}
# 0: symbol
# lint: module
compiler.warn.module.not.found=\
module not found: {0}
@ -3653,6 +3766,7 @@ compiler.err.package.empty.or.not.found=\
package is empty or does not exist: {0}
# 0: symbol
# lint: opens
compiler.warn.package.empty.or.not.found=\
package is empty or does not exist: {0}
@ -3736,6 +3850,7 @@ compiler.err.bad.name.for.option=\
bad name in value for {0} option: ''{1}''
# 0: option name, 1: symbol
# lint: options
compiler.warn.module.for.option.not.found=\
module name in {0} option not found: {1}
@ -3751,6 +3866,7 @@ compiler.err.add.exports.with.release=\
compiler.err.add.reads.with.release=\
adding read edges for system module {0} is not allowed with --release
# lint: options
compiler.warn.addopens.ignored=\
--add-opens has no effect at compile time
@ -3781,15 +3897,19 @@ compiler.warn.service.provided.but.not.exported.or.used=\
service interface provided but not exported or used
# 0: kind name, 1: symbol, 2: symbol
# lint: exports
compiler.warn.leaks.not.accessible=\
{0} {1} in module {2} is not accessible to clients that require this module
# 0: kind name, 1: symbol, 2: symbol
# lint: exports
compiler.warn.leaks.not.accessible.unexported=\
{0} {1} in module {2} is not exported
# 0: kind name, 1: symbol, 2: symbol
# lint: exports
compiler.warn.leaks.not.accessible.not.required.transitive=\
{0} {1} in module {2} is not indirectly exported using ''requires transitive''
# 0: kind name, 1: symbol, 2: symbol
# lint: exports
compiler.warn.leaks.not.accessible.unexported.qualified=\
{0} {1} in module {2} may not be visible to all clients that require this module
@ -4119,9 +4239,11 @@ compiler.err.incorrect.number.of.nested.patterns=\
found: {1}
# 0: kind name, 1: symbol
# lint: preview
compiler.warn.declared.using.preview=\
{0} {1} is declared using a preview feature, which may be removed in a future release.
# lint: synchronization
compiler.warn.attempt.to.synchronize.on.instance.of.value.based.class=\
attempt to synchronize on an instance of a value-based class

View File

@ -29,7 +29,6 @@ import java.util.HashMap;
import java.util.Map;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.Error;
import com.sun.tools.javac.util.JCDiagnostic.Note;
@ -155,21 +154,14 @@ public abstract class AbstractLog {
report(diags.error(flag, source, wrap(pos), errorKey));
}
/** Report a warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param warningKey The key for the localized warning message.
/**
* Report a lint warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
*
* @param warningKey The key for the localized warning message.
*/
public void warning(Warning warningKey) {
report(diags.warning(null, source, null, warningKey));
}
/** Report a lint warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param lc The lint category for the diagnostic
* @param warningKey The key for the localized warning message.
*/
public void warning(LintCategory lc, Warning warningKey) {
report(diags.warning(lc, null, null, warningKey));
report(diags.warning(source, null, warningKey));
}
/** Report a warning, unless suppressed by the -nowarn option or the
@ -178,17 +170,7 @@ public abstract class AbstractLog {
* @param warningKey The key for the localized warning message.
*/
public void warning(DiagnosticPosition pos, Warning warningKey) {
report(diags.warning(null, source, pos, warningKey));
}
/** Report a lint warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param lc The lint category for the diagnostic
* @param pos The source position at which to report the warning.
* @param warningKey The key for the localized warning message.
*/
public void warning(LintCategory lc, DiagnosticPosition pos, Warning warningKey) {
report(diags.warning(lc, source, pos, warningKey));
report(diags.warning(source, pos, warningKey));
}
/** Report a warning, unless suppressed by the -nowarn option or the
@ -197,7 +179,7 @@ public abstract class AbstractLog {
* @param warningKey The key for the localized warning message.
*/
public void warning(int pos, Warning warningKey) {
report(diags.warning(null, source, wrap(pos), warningKey));
report(diags.warning(source, wrap(pos), warningKey));
}
/** Report a warning.
@ -205,16 +187,7 @@ public abstract class AbstractLog {
* @param warningKey The key for the localized warning message.
*/
public void mandatoryWarning(DiagnosticPosition pos, Warning warningKey) {
report(diags.mandatoryWarning(null, source, pos, warningKey));
}
/** Report a warning.
* @param lc The lint category for the diagnostic
* @param pos The source position at which to report the warning.
* @param warningKey The key for the localized warning message.
*/
public void mandatoryWarning(LintCategory lc, DiagnosticPosition pos, Warning warningKey) {
report(diags.mandatoryWarning(lc, source, pos, warningKey));
report(diags.mandatoryWarning(source, pos, warningKey));
}
/** Provide a non-fatal notification, unless suppressed by the -nowarn option.

View File

@ -111,7 +111,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic error(
DiagnosticFlag flag, DiagnosticSource source, DiagnosticPosition pos, Error errorKey) {
JCDiagnostic diag = create(null, EnumSet.copyOf(defaultErrorFlags), source, pos, errorKey);
JCDiagnostic diag = create(EnumSet.copyOf(defaultErrorFlags), source, pos, errorKey);
if (flag != null) {
diag.setFlag(flag);
}
@ -130,21 +130,19 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
public JCDiagnostic mandatoryWarning(
LintCategory lc,
DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return mandatoryWarning(lc, source, pos, warningKey(key, args));
return mandatoryWarning(source, pos, warningKey(lc, key, args));
}
/**
* Create a warning diagnostic that will not be hidden by the -nowarn or -Xlint:none options.
* @param lc The lint category for the diagnostic
* @param source The source of the compilation unit, if any, in which to report the warning.
* @param pos The source position at which to report the warning.
* @param warningKey The key for the localized warning message.
* @see MandatoryWarningHandler
*/
public JCDiagnostic mandatoryWarning(
LintCategory lc,
DiagnosticSource source, DiagnosticPosition pos, Warning warningKey) {
return create(lc, EnumSet.of(DiagnosticFlag.MANDATORY), source, pos, warningKey);
return create(EnumSet.of(DiagnosticFlag.MANDATORY), source, pos, warningKey);
}
/**
@ -158,20 +156,19 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic warning(
LintCategory lc, DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return warning(lc, source, pos, warningKey(key, args));
return warning(source, pos, warningKey(lc, key, args));
}
/**
* Create a warning diagnostic.
* @param lc The lint category for the diagnostic
* @param source The source of the compilation unit, if any, in which to report the warning.
* @param pos The source position at which to report the warning.
* @param warningKey The key for the localized warning message.
* @see MandatoryWarningHandler
*/
public JCDiagnostic warning(
LintCategory lc, DiagnosticSource source, DiagnosticPosition pos, Warning warningKey) {
return create(lc, EnumSet.noneOf(DiagnosticFlag.class), source, pos, warningKey);
DiagnosticSource source, DiagnosticPosition pos, Warning warningKey) {
return create(EnumSet.noneOf(DiagnosticFlag.class), source, pos, warningKey);
}
/**
@ -191,7 +188,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
* @see MandatoryWarningHandler
*/
public JCDiagnostic mandatoryNote(DiagnosticSource source, Note noteKey) {
return create(null, EnumSet.of(DiagnosticFlag.MANDATORY), source, null, noteKey);
return create(EnumSet.of(DiagnosticFlag.MANDATORY), source, null, noteKey);
}
/**
@ -212,7 +209,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic note(
DiagnosticSource source, DiagnosticPosition pos, Note noteKey) {
return create(null, EnumSet.noneOf(DiagnosticFlag.class), source, pos, noteKey);
return create(EnumSet.noneOf(DiagnosticFlag.class), source, pos, noteKey);
}
/**
@ -229,7 +226,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
* @param fragmentKey The key for the localized subdiagnostic message.
*/
public JCDiagnostic fragment(Fragment fragmentKey) {
return create(null, EnumSet.noneOf(DiagnosticFlag.class), null, null, fragmentKey);
return create(EnumSet.noneOf(DiagnosticFlag.class), null, null, fragmentKey);
}
/**
@ -243,7 +240,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic create(
DiagnosticType kind, DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(null, EnumSet.noneOf(DiagnosticFlag.class), source, pos, DiagnosticInfo.of(kind, prefix, key, args));
return create(EnumSet.noneOf(DiagnosticFlag.class), source, pos, DiagnosticInfo.of(kind, prefix, key, args));
}
/**
@ -258,7 +255,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic create(
DiagnosticType kind, DiagnosticSource source, DiagnosticPosition pos, String key, UnaryOperator<JCDiagnostic> rewriter, Object... args) {
return create(null, EnumSet.noneOf(DiagnosticFlag.class), source, pos, DiagnosticInfo.of(kind, prefix, key, args), rewriter);
return create(EnumSet.noneOf(DiagnosticFlag.class), source, pos, DiagnosticInfo.of(kind, prefix, key, args), rewriter);
}
/**
@ -270,7 +267,7 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic create(
DiagnosticSource source, DiagnosticPosition pos, DiagnosticInfo diagnosticInfo) {
return create(null, EnumSet.noneOf(DiagnosticFlag.class), source, pos, diagnosticInfo);
return create(EnumSet.noneOf(DiagnosticFlag.class), source, pos, diagnosticInfo);
}
/**
@ -285,30 +282,31 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
*/
public JCDiagnostic create(DiagnosticType kind,
LintCategory lc, Set<DiagnosticFlag> flags, DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(lc, flags, source, pos, DiagnosticInfo.of(kind, prefix, key, args));
return create(flags, source, pos, DiagnosticInfo.of(kind, lc, prefix, key, args));
}
/**
* Create a new diagnostic with given key.
* @param lc The lint category, if applicable, or null
* @param flags The set of flags for the diagnostic
* @param source The source of the compilation unit, if any, in which to report the message.
* @param pos The source position at which to report the message.
* @param diagnosticInfo The key for the localized message.
*/
public JCDiagnostic create(
LintCategory lc, Set<DiagnosticFlag> flags, DiagnosticSource source, DiagnosticPosition pos, DiagnosticInfo diagnosticInfo) {
return new JCDiagnostic(formatter, normalize(diagnosticInfo), lc, flags, source, pos);
Set<DiagnosticFlag> flags, DiagnosticSource source, DiagnosticPosition pos, DiagnosticInfo diagnosticInfo) {
return new JCDiagnostic(formatter, normalize(diagnosticInfo), flags, source, pos);
}
public JCDiagnostic create(
LintCategory lc, Set<DiagnosticFlag> flags, DiagnosticSource source, DiagnosticPosition pos, DiagnosticInfo diagnosticInfo, UnaryOperator<JCDiagnostic> rewriter) {
return new JCDiagnostic(formatter, normalize(diagnosticInfo), lc, flags, source, pos, rewriter);
Set<DiagnosticFlag> flags, DiagnosticSource source, DiagnosticPosition pos, DiagnosticInfo diagnosticInfo, UnaryOperator<JCDiagnostic> rewriter) {
return new JCDiagnostic(formatter, normalize(diagnosticInfo), flags, source, pos, rewriter);
}
//where
DiagnosticInfo normalize(DiagnosticInfo diagnosticInfo) {
//replace all nested FragmentKey with full-blown JCDiagnostic objects
return DiagnosticInfo.of(diagnosticInfo.type, diagnosticInfo.prefix, diagnosticInfo.code,
LintCategory category = diagnosticInfo instanceof LintWarning lintWarning ?
lintWarning.category : null;
return DiagnosticInfo.of(diagnosticInfo.type, category, diagnosticInfo.prefix, diagnosticInfo.code,
Stream.of(diagnosticInfo.args).map(o -> {
return (o instanceof Fragment frag) ?
fragment(frag) : o;
@ -325,8 +323,8 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
/**
* Create a new warning key.
*/
Warning warningKey(String code, Object... args) {
return (Warning)DiagnosticInfo.of(WARNING, prefix, code, args);
Warning warningKey(LintCategory lintCategory, String code, Object... args) {
return (Warning)DiagnosticInfo.of(WARNING, lintCategory, prefix, code, args);
}
/**
@ -356,10 +354,10 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
public static JCDiagnostic fragment(String key, Object... args) {
return new JCDiagnostic(getFragmentFormatter(),
DiagnosticInfo.of(FRAGMENT,
null,
"compiler",
key,
args),
null,
EnumSet.noneOf(DiagnosticFlag.class),
null,
null);
@ -464,7 +462,6 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
private final DiagnosticPosition position;
private final DiagnosticInfo diagnosticInfo;
private final Set<DiagnosticFlag> flags;
private final LintCategory lintCategory;
/** source line position (set lazily) */
private SourcePosition sourcePosition;
@ -537,11 +534,17 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
* Static factory method; build a custom diagnostic key using given kind, prefix, code and args.
*/
public static DiagnosticInfo of(DiagnosticType type, String prefix, String code, Object... args) {
return of(type, null, prefix, code, args);
}
public static DiagnosticInfo of(DiagnosticType type, LintCategory lc, String prefix, String code, Object... args) {
switch (type) {
case ERROR:
return new Error(prefix, code, args);
case WARNING:
return new Warning(prefix, code, args);
return lc == null ?
new Warning(prefix, code, args) :
new LintWarning(lc, prefix, code, args);
case NOTE:
return new Note(prefix, code, args);
case FRAGMENT:
@ -583,12 +586,28 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
/**
* Class representing warning diagnostic keys.
*/
public static final class Warning extends DiagnosticInfo {
public static sealed class Warning extends DiagnosticInfo {
public Warning(String prefix, String key, Object... args) {
super(DiagnosticType.WARNING, prefix, key, args);
}
}
/**
* Class representing lint warning diagnostic keys.
*/
public static final class LintWarning extends Warning {
final LintCategory category;
public LintWarning(LintCategory category, String prefix, String key, Object... args) {
super(prefix, key, args);
this.category = category;
}
public LintCategory getLintCategory() {
return category;
}
}
/**
* Class representing note diagnostic keys.
*/
@ -614,31 +633,27 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
* Create a diagnostic object.
* @param formatter the formatter to use for the diagnostic
* @param diagnosticInfo the diagnostic key
* @param lc the lint category for the diagnostic
* @param source the name of the source file, or null if none.
* @param pos the character offset within the source file, if given.
*/
protected JCDiagnostic(DiagnosticFormatter<JCDiagnostic> formatter,
DiagnosticInfo diagnosticInfo,
LintCategory lc,
Set<DiagnosticFlag> flags,
DiagnosticSource source,
DiagnosticPosition pos) {
this(formatter, diagnosticInfo, lc, flags, source, pos, null);
this(formatter, diagnosticInfo, flags, source, pos, null);
}
/**
* Create a diagnostic object.
* @param formatter the formatter to use for the diagnostic
* @param diagnosticInfo the diagnostic key
* @param lc the lint category for the diagnostic
* @param source the name of the source file, or null if none.
* @param pos the character offset within the source file, if given.
* @param rewriter the rewriter function used if this diagnostic needs to be rewritten
*/
protected JCDiagnostic(DiagnosticFormatter<JCDiagnostic> formatter,
DiagnosticInfo diagnosticInfo,
LintCategory lc,
Set<DiagnosticFlag> flags,
DiagnosticSource source,
DiagnosticPosition pos,
@ -648,7 +663,6 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
this.defaultFormatter = formatter;
this.diagnosticInfo = diagnosticInfo;
this.lintCategory = lc;
this.flags = flags;
this.source = source;
this.position = pos;
@ -687,14 +701,15 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
* Check whether this diagnostic has an associated lint category.
*/
public boolean hasLintCategory() {
return (lintCategory != null);
return getLintCategory() != null;
}
/**
* Get the associated lint category, or null if none.
*/
public LintCategory getLintCategory() {
return lintCategory;
return diagnosticInfo instanceof LintWarning lintWarning ?
lintWarning.category : null;
}
/**
@ -870,7 +885,6 @@ public class JCDiagnostic implements Diagnostic<JavaFileObject> {
public MultilineDiagnostic(JCDiagnostic other, List<JCDiagnostic> subdiagnostics) {
super(other.defaultFormatter,
other.diagnosticInfo,
other.getLintCategory(),
other.flags,
other.getDiagnosticSource(),
other.position);

View File

@ -33,6 +33,7 @@ import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.LintWarning;
import com.sun.tools.javac.util.JCDiagnostic.Note;
import com.sun.tools.javac.util.JCDiagnostic.Warning;
@ -126,8 +127,9 @@ public class MandatoryWarningHandler {
/**
* Report a mandatory warning.
*/
public void report(DiagnosticPosition pos, Warning warnKey) {
public void report(DiagnosticPosition pos, LintWarning warnKey) {
JavaFileObject currentSource = log.currentSourceFile();
Assert.check(warnKey.getLintCategory() == lintCategory);
if (verbose) {
if (sourcesWithReportedWarnings == null)
@ -259,9 +261,9 @@ public class MandatoryWarningHandler {
private void logMandatoryWarning(DiagnosticPosition pos, Warning warnKey) {
// Note: the following log methods are safe if lintCategory is null.
if (enforceMandatory)
log.mandatoryWarning(lintCategory, pos, warnKey);
log.mandatoryWarning(pos, warnKey);
else
log.warning(lintCategory, pos, warnKey);
log.warning(pos, warnKey);
}
/**

View File

@ -41,6 +41,7 @@ import javax.tools.SimpleJavaFileObject;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.parser.Parser;
import com.sun.tools.javac.parser.ParserFactory;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeScanner;
@ -51,7 +52,6 @@ import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.Factory;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
public class TestLog
{
@ -130,10 +130,10 @@ public class TestLog
log.error(tree.pos(), Errors.NotStmt);
log.error(nil, Errors.NotStmt);
log.warning(Warnings.DivZero);
log.warning(tree.pos, Warnings.DivZero);
log.warning(tree.pos(), Warnings.DivZero);
log.warning(nil, Warnings.DivZero);
log.warning(LintWarnings.DivZero);
log.warning(tree.pos, LintWarnings.DivZero);
log.warning(tree.pos(), LintWarnings.DivZero);
log.warning(nil, LintWarnings.DivZero);
}
private Log log;