From c49f7a57148c64ae61cd9a4f1304d66e4e7fd5a1 Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Wed, 4 Dec 2024 16:58:49 +0000 Subject: [PATCH] Separate LintWarnings from Warnings in CompilerProperties Add Lint::logIfEnabled --- .../propertiesparser/gen/ClassGenerator.java | 26 ++- .../resources/templates.properties | 1 + .../com/sun/tools/javac/code/Lint.java | 15 ++ .../com/sun/tools/javac/code/Preview.java | 12 +- .../com/sun/tools/javac/comp/Attr.java | 25 ++- .../com/sun/tools/javac/comp/Check.java | 173 +++++++----------- .../com/sun/tools/javac/comp/Flow.java | 16 +- .../com/sun/tools/javac/comp/Modules.java | 11 +- .../tools/javac/comp/ThisEscapeAnalyzer.java | 5 +- .../sun/tools/javac/file/BaseFileManager.java | 3 +- .../com/sun/tools/javac/file/Locations.java | 16 +- .../com/sun/tools/javac/jvm/ClassReader.java | 11 +- .../com/sun/tools/javac/main/Arguments.java | 15 +- .../sun/tools/javac/parser/JavaTokenizer.java | 5 +- .../sun/tools/javac/parser/JavacParser.java | 3 +- .../tools/javac/processing/JavacFiler.java | 11 +- .../JavacProcessingEnvironment.java | 11 +- .../tools/javac/resources/compiler.properties | 5 + .../sun/tools/javac/util/JCDiagnostic.java | 33 ++-- .../javac/util/MandatoryWarningHandler.java | 15 +- .../tools/javac/6304921/TestLog.java | 10 +- 21 files changed, 225 insertions(+), 197 deletions(-) diff --git a/make/langtools/tools/propertiesparser/gen/ClassGenerator.java b/make/langtools/tools/propertiesparser/gen/ClassGenerator.java index 079d01cee1937..e869d60bbc569 100644 --- a/make/langtools/tools/propertiesparser/gen/ClassGenerator.java +++ b/make/langtools/tools/propertiesparser/gen/ClassGenerator.java @@ -48,6 +48,7 @@ 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; @@ -117,6 +118,7 @@ String format(Object... args) { 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); @@ -139,13 +141,24 @@ enum FactoryKind { /** * Utility method for parsing a factory kind from a resource key prefix. */ - static FactoryKind parseFrom(String prefix) { + static FactoryKind of(Entry 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; } } @@ -158,7 +171,7 @@ public void generateFactory(MessageFile messageFile, File outDir) { messageFile.messages.entrySet().stream() .collect( Collectors.groupingBy( - e -> FactoryKind.parseFrom(e.getKey().split("\\.")[1]), + FactoryKind::of, TreeMap::new, toList())); //generate nested classes @@ -168,7 +181,7 @@ public void generateFactory(MessageFile messageFile, File outDir) { 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 = @@ -233,7 +246,7 @@ List generateImports(Set importedTypes) { /** * Generate a list of factory methods/fields to be added to a given factory nested class. */ - List generateFactoryMethodsAndFields(String key, Message msg) { + List generateFactoryMethodsAndFields(FactoryKind k, String key, Message msg) { MessageInfo msgInfo = msg.getMessageInfo(); List lines = msg.getLines(false); String javadoc = lines.stream() @@ -241,7 +254,6 @@ List generateFactoryMethodsAndFields(String key, Message msg) { .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) diff --git a/make/langtools/tools/propertiesparser/resources/templates.properties b/make/langtools/tools/propertiesparser/resources/templates.properties index 44f6248cf0040..bb403238f804b 100644 --- a/make/langtools/tools/propertiesparser/resources/templates.properties +++ b/make/langtools/tools/propertiesparser/resources/templates.properties @@ -29,6 +29,7 @@ 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\ diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java index af2d98d6c11ae..e46b58b0954ea 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java @@ -33,7 +33,10 @@ 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; @@ -93,6 +96,7 @@ public Lint suppress(LintCategory... lc) { return l; } + private final Log log; private final AugmentVisitor augmentor; private final EnumSet values; @@ -146,12 +150,14 @@ protected Lint(Context context) { context.put(lintKey, this); augmentor = new AugmentVisitor(context); + log = Log.instance(context); } protected Lint(Lint other) { this.augmentor = other.augmentor; this.values = other.values.clone(); this.suppressedValues = other.suppressedValues.clone(); + this.log = other.log; } @Override @@ -385,6 +391,15 @@ public boolean isSuppressed(LintCategory lc) { return suppressedValues.contains(lc); } + /** + * Helper method. Log a lint warning if its lint category is enabled. + */ + public void logIfEnabled(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; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Preview.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Preview.java index baa0240365b80..5a684a1cc59bd 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Preview.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Preview.java @@ -30,11 +30,13 @@ 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; @@ -102,7 +104,7 @@ protected Preview(Context context) { lint = Lint.instance(context); source = Source.instance(context); this.previewHandler = - new MandatoryWarningHandler(log, source, lint.isEnabled(LintCategory.PREVIEW), true, "preview"); + new MandatoryWarningHandler(log, source, lint.isEnabled(LintCategory.PREVIEW), true, "preview", LintCategory.PREVIEW); forcePreview = options.isSet("forcePreview"); majorVersionToSource = initMajorVersionToSourceMap(); } @@ -175,8 +177,8 @@ public void warnPreview(DiagnosticPosition pos, Feature feature) { 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())); } } @@ -189,7 +191,7 @@ public void warnPreview(JavaFileObject classfile, int majorVersion) { Assert.check(isEnabled()); if (lint.isEnabled(LintCategory.PREVIEW)) { log.mandatoryWarning(null, - Warnings.PreviewFeatureUseClassfile(classfile, majorVersionToSource.get(majorVersion).name)); + LintWarnings.PreviewFeatureUseClassfile(classfile, majorVersionToSource.get(majorVersion).name)); } } @@ -197,7 +199,7 @@ public void markUsesPreview(DiagnosticPosition pos) { sourcesWithPreviewFeatures.add(log.currentSourceFile()); } - public void reportPreviewWarning(DiagnosticPosition pos, Warning warnKey) { + public void reportPreviewWarning(DiagnosticPosition pos, LintWarning warnKey) { previewHandler.report(pos, warnKey); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index a18f82613e0f8..b66e6525dc651 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -58,6 +58,7 @@ 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 @@ private Symbol enumConstant(JCTree tree, Type enumType) { 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(tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass); + if (isValueBased(tree.lock.type)) { + env.info.lint.logIfEnabled(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass); } attribStat(tree.body, env); result = null; @@ -2045,9 +2046,8 @@ void checkAutoCloseable(DiagnosticPosition pos, Env env, Type resou } 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(pos, Warnings.TryResourceThrowsInterruptedExc(resource)); + chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes())) { + env.info.lint.logIfEnabled(pos, LintWarnings.TryResourceThrowsInterruptedExc(resource)); } } } @@ -4441,9 +4441,8 @@ public void visitSelect(JCFieldAccess tree) { ((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(tree, Warnings.TryExplicitCloseCall); + sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true)) { + env.info.lint.logIfEnabled(tree, LintWarnings.TryExplicitCloseCall); } // Disallow selecting a type from an expression @@ -4470,9 +4469,9 @@ public void visitSelect(JCFieldAccess tree) { // 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)); + env.info.lint.logIfEnabled(tree, LintWarnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner)); } else { - chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName())); + env.info.lint.logIfEnabled(tree, LintWarnings.StaticNotQualifiedByType2(sym.kind.kindName())); } } @@ -4685,7 +4684,7 @@ else if (ownOuter.hasTag(CLASS) && site != ownOuter) { 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 @@ -4883,7 +4882,7 @@ public Type checkMethod(Type site, 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)); } } @@ -4933,7 +4932,7 @@ public Type checkMethod(Type site, 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)), diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index 84eb02d8a7f1d..8f91dcde16515 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -49,12 +49,14 @@ 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.LintWarning; import com.sun.tools.javac.util.JCDiagnostic.Warning; import com.sun.tools.javac.util.List; @@ -167,13 +169,13 @@ protected Check(Context context) { boolean enforceMandatoryWarnings = true; deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated, - enforceMandatoryWarnings, "deprecated"); + enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION); removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval, - enforceMandatoryWarnings, "removal"); + enforceMandatoryWarnings, "removal", LintCategory.REMOVAL); uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked, - enforceMandatoryWarnings, "unchecked"); + enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED); sunApiHandler = new MandatoryWarningHandler(log, null, false, - enforceMandatoryWarnings, "sunapi"); + enforceMandatoryWarnings, "sunapi", null); deferredLintHandler = DeferredLintHandler.instance(context); @@ -247,16 +249,16 @@ void warnDeprecated(DiagnosticPosition pos, Symbol sym) { 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())); } } } @@ -265,7 +267,7 @@ void warnDeprecated(DiagnosticPosition pos, Symbol sym) { * @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); } @@ -276,7 +278,7 @@ public void warnPreviewAPI(DiagnosticPosition pos, Warning warnKey) { */ 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. @@ -284,40 +286,18 @@ public void warnDeclaredUsingPreview(DiagnosticPosition pos, Symbol sym) { * @param msg A Warning describing the problem. */ public void warnRestrictedAPI(DiagnosticPosition pos, Symbol sym) { - if (lint.isEnabled(LintCategory.RESTRICTED)) - log.warning(pos, Warnings.RestrictedMethod(sym.enclClass(), sym)); + lint.logIfEnabled(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(pos, warnKey); - } - - public void warnStatic(DiagnosticPosition pos, Warning warnKey) { - if (lint.isEnabled(LintCategory.STATIC)) - log.warning(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(pos, Warnings.DivZero); - } - /** * Report any deferred diagnostics. */ @@ -670,9 +650,7 @@ public void checkRedundantCast(Env env, final JCTypeCast tree) { && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz)) && !is292targetTypeCast(tree)) { deferredLintHandler.report(_l -> { - if (lint.isEnabled(LintCategory.CAST)) - log.warning( - tree.pos(), Warnings.RedundantCast(tree.clazz.type)); + lint.logIfEnabled(tree.pos(), LintWarnings.RedundantCast(tree.clazz.type)); }); } } @@ -977,13 +955,13 @@ void checkVarargsMethodDecl(Env env, JCMethodDecl tree) { } } else if (hasTrustMeAnno && varargElemType != null && types.isReifiable(varargElemType)) { - warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno( + lint.logIfEnabled(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 @@ -1070,7 +1048,7 @@ Type checkMethod(final Type mtype, 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)); } @@ -1346,10 +1324,8 @@ && checkDisjoint(pos, flags, private void warnOnExplicitStrictfp(DiagnosticPosition pos) { DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos); try { - deferredLintHandler.report(_l -> { - if (lint.isEnabled(LintCategory.STRICTFP)) { - log.warning( - pos, Warnings.Strictfp); } + deferredLintHandler.report(_ -> { + lint.logIfEnabled(pos, LintWarnings.Strictfp); }); } finally { deferredLintHandler.setPos(prevLintPos); @@ -1565,13 +1541,11 @@ public void validateTrees(List trees, boolean checkRaw, boolea } void checkRaw(JCTree tree, Env 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( - tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type)); + lint.logIfEnabled(tree.pos(), LintWarnings.RawClassUse(tree.type, tree.type.tsym.type)); } } //where @@ -1873,7 +1847,7 @@ void checkOverride(JCTree tree, 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 @@ -1889,17 +1863,16 @@ void checkOverride(JCTree tree, } 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(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 ??) @@ -2244,7 +2217,7 @@ private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos, if (overridesEquals && !overridesHashCode) { log.warning(pos, - Warnings.OverrideEqualsButNotHashcode(someClass)); + LintWarnings.OverrideEqualsButNotHashcode(someClass)); } } } @@ -2306,7 +2279,7 @@ public void checkModuleName (JCModuleDecl tree) { String moduleNameComponentString = componentName.toString(); int nameLength = moduleNameComponentString.length(); if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) { - log.warning(pos, Warnings.PoorChoiceForModuleName(componentName)); + log.warning(pos, LintWarnings.PoorChoiceForModuleName(componentName)); } } } @@ -2778,7 +2751,7 @@ void checkPotentiallyAmbiguousOverloads(JCClassDecl tree, Type site) { // Log the warning log.warning(pos, - Warnings.PotentiallyAmbiguousOverload( + LintWarnings.PotentiallyAmbiguousOverload( m1.asMemberOf(site, types), m1.location(), m2.asMemberOf(site, types), m2.location())); @@ -3786,14 +3759,13 @@ void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) { (s.flags() & DEPRECATED) != 0 && !syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) == null) { - log.warning( - 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(pos, - Warnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s))); + LintWarnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s))); } } } @@ -3853,10 +3825,10 @@ void checkPreview(DiagnosticPosition pos, Symbol other, Type site, Symbol s) { 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)) { @@ -4121,7 +4093,7 @@ void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) { 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(pos, LintWarnings.DivZero)); } } } @@ -4134,10 +4106,8 @@ void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) { */ 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( - pos, Warnings.PossibleLossOfPrecision(found, req)); + deferredLintHandler.report(_ -> { + lint.logIfEnabled(pos, LintWarnings.PossibleLossOfPrecision(found, req)); }); } } @@ -4146,9 +4116,9 @@ void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) { * Check for empty statements after if */ void checkEmptyIf(JCIf tree) { - if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null && - lint.isEnabled(LintCategory.EMPTY)) - log.warning(tree.thenpart.pos(), Warnings.EmptyIf); + if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null) { + lint.logIfEnabled(tree.thenpart.pos(), LintWarnings.EmptyIf); + } } /** Check that symbol is unique in given scope. @@ -4290,13 +4260,12 @@ private boolean isCanonical(JCTree tree) { /** Check that an auxiliary class is not accessed from any other file than its own. */ void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env 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(pos, + LintWarnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile)); } } @@ -4338,11 +4307,9 @@ void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) { // 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( - pos, Warnings.MissingExplicitCtor(c, pkg, modle)); - }); + deferredLintHandler.report(_ -> { + lint.logIfEnabled(pos, LintWarnings.MissingExplicitCtor(c, pkg, modle)); + }); } else { return; } @@ -4371,14 +4338,14 @@ public void warn(LintCategory lint) { 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(pos(), LintWarnings.VarargsUnsafeUseVarargsParam(method.params.last())); } break; default: @@ -4633,7 +4600,7 @@ private boolean isAPISymbol(Symbol sym) { } private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) { if (!isAPISymbol(what) && !inSuperType) { //package private/private element - log.warning(pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle)); + log.warning(pos, LintWarnings.LeaksNotAccessible(kindName(what), what, what.packge().modle)); return ; } @@ -4642,13 +4609,13 @@ private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inP ExportsDirective inExport = findExport(inPackage); if (whatExport == null) { //package not exported: - log.warning(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(pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle)); + log.warning(pos, LintWarnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle)); } } @@ -4670,15 +4637,14 @@ private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inP } } - log.warning(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(pos, Warnings.ModuleNotFound(msym)); + deferredLintHandler.report(_ -> { + lint.logIfEnabled(pos, LintWarnings.ModuleNotFound(msym)); }); } } @@ -4686,20 +4652,19 @@ void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol 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(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(pos, LintWarnings.RequiresAutomatic); } }); } @@ -5303,13 +5268,13 @@ void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) { if ((flags & PRIVATE) == 0) { log.warning( TreeInfo.diagnosticPositionFor(method, tree), - Warnings.SerialMethodNotPrivate(method.getSimpleName())); + LintWarnings.SerialMethodNotPrivate(method.getSimpleName())); } if ((flags & STATIC) != 0) { log.warning( TreeInfo.diagnosticPositionFor(method, tree), - Warnings.SerialMethodStatic(method.getSimpleName())); + LintWarnings.SerialMethodStatic(method.getSimpleName())); } } @@ -5550,7 +5515,7 @@ void checkConcreteInstanceMethod(JCClassDecl tree, if ((method.flags() & (STATIC | ABSTRACT)) != 0) { log.warning( TreeInfo.diagnosticPositionFor(method, tree), - Warnings.SerialConcreteInstanceMethod(method.getSimpleName())); + LintWarnings.SerialConcreteInstanceMethod(method.getSimpleName())); } } @@ -5567,7 +5532,7 @@ private void checkReturnType(JCClassDecl tree, if (!types.isSameType(expectedReturnType, rtype)) { log.warning( TreeInfo.diagnosticPositionFor(method, tree), - Warnings.SerialMethodUnexpectedReturnType(method.getSimpleName(), + LintWarnings.SerialMethodUnexpectedReturnType(method.getSimpleName(), rtype, expectedReturnType)); } } @@ -5583,7 +5548,7 @@ private void checkOneArg(JCClassDecl tree, if (parameters.size() != 1) { log.warning( TreeInfo.diagnosticPositionFor(method, tree), - Warnings.SerialMethodOneArg(method.getSimpleName(), parameters.size())); + LintWarnings.SerialMethodOneArg(method.getSimpleName(), parameters.size())); return; } @@ -5591,7 +5556,7 @@ private void checkOneArg(JCClassDecl tree, if (!types.isSameType(parameterType, expectedType)) { log.warning( TreeInfo.diagnosticPositionFor(method, tree), - Warnings.SerialMethodParameterType(method.getSimpleName(), + LintWarnings.SerialMethodParameterType(method.getSimpleName(), expectedType, parameterType)); } @@ -5612,7 +5577,7 @@ private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol metho if (!parameters.isEmpty()) { log.warning( TreeInfo.diagnosticPositionFor(parameters.get(0), tree), - Warnings.SerialMethodNoArgs(method.getSimpleName())); + LintWarnings.SerialMethodNoArgs(method.getSimpleName())); } } @@ -5650,7 +5615,7 @@ private void checkExceptions(JCClassDecl tree, if (!declared) { log.warning( TreeInfo.diagnosticPositionFor(method, tree), - Warnings.SerialMethodUnexpectedException(method.getSimpleName(), + LintWarnings.SerialMethodUnexpectedException(method.getSimpleName(), thrownType)); } } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java index 8a90dc88fa90d..abcca6fe3aea2 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java @@ -38,6 +38,7 @@ 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.*; @@ -723,11 +724,9 @@ public void visitSwitch(JCSwitch tree) { } // 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( - l.tail.head.pos(), - Warnings.PossibleFallThroughIntoCase); + lint.logIfEnabled(l.tail.head.pos(), + LintWarnings.PossibleFallThroughIntoCase); } tree.isExhaustive = tree.hasUnconditionalPattern || TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases); @@ -1234,11 +1233,8 @@ public void visitTry(JCTry tree) { scanStat(tree.finalizer); tree.finallyCanCompleteNormally = alive != Liveness.DEAD; if (alive == Liveness.DEAD) { - if (lint.isEnabled(Lint.LintCategory.FINALLY)) { - log.warning( - TreeInfo.diagEndPos(tree.finalizer), - Warnings.FinallyCannotComplete); - } + lint.logIfEnabled(TreeInfo.diagEndPos(tree.finalizer), + LintWarnings.FinallyCannotComplete); } else { while (exits.nonEmpty()) { pendingExits.append(exits.next()); @@ -2861,7 +2857,7 @@ public void visitTry(JCTry tree) { for (JCVariableDecl resVar : resourceVarDecls) { if (unrefdResources.includes(resVar.sym) && !resVar.sym.isUnnamedVariable()) { log.warning(resVar.pos(), - Warnings.TryResourceNotReferenced(resVar.sym)); + LintWarnings.TryResourceNotReferenced(resVar.sym)); unrefdResources.remove(resVar.sym); } } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java index d0ed3abcaaf5b..97f961f09bf48 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java @@ -87,6 +87,7 @@ 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,7 +1276,7 @@ private void setupAllModules() { for (ModuleSymbol msym : limitMods) { if (!observable.contains(msym)) { log.warning( - Warnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym)); + LintWarnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym)); } } } @@ -1380,7 +1381,7 @@ private void setupAllModules() { .collect(Collectors.joining(",")); if (!incubatingModules.isEmpty()) { - log.warning(Warnings.IncubatingModules(incubatingModules)); + log.warning(LintWarnings.IncubatingModules(incubatingModules)); } } @@ -1731,7 +1732,7 @@ private boolean isKnownModule(ModuleSymbol msym, Set unknownModule if (!unknownModules.contains(msym)) { if (lintOptions) { log.warning( - Warnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym)); + LintWarnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym)); } unknownModules.add(msym); } @@ -1769,7 +1770,7 @@ private void initAddReads() { 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; } @@ -1789,7 +1790,7 @@ private void initAddReads() { targetModule = syms.enterModule(names.fromString(targetName)); if (!allModules.contains(targetModule)) { if (lintOptions) { - log.warning(Warnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule)); + log.warning(LintWarnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule)); } continue; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ThisEscapeAnalyzer.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ThisEscapeAnalyzer.java index 35b0e89c8a4dd..67486dbe4bf3e 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ThisEscapeAnalyzer.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ThisEscapeAnalyzer.java @@ -51,6 +51,7 @@ 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.*; @@ -421,12 +422,12 @@ private boolean currentClassIsExternallyExtendable() { 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(pos, key); - key = Warnings.PossibleThisEscapeLocation; + key = LintWarnings.PossibleThisEscapeLocation; } while (remain > 0); } warningList.clear(); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java index 9b2d4e9f2a35b..f2f8eb0f0df42 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java @@ -57,6 +57,7 @@ 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.Context; import com.sun.tools.javac.util.DefinedBy; @@ -524,6 +525,6 @@ synchronized void newOutputToPath(Path path) throws IOException { // Check whether we've already opened this file for output if (!outputFilesWritten.add(realPath)) - log.warning(Warnings.OutputFileClash(path)); + log.warning(LintWarnings.OutputFileClash(path)); // @@@: shouldn't we check for suppression? } } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java index 98bc53b57fa2d..3a6ed52cc79e7 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java @@ -77,6 +77,8 @@ 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.main.Option; @@ -222,7 +224,7 @@ private Iterable getPathEntries(String searchPath, Path emptyPathDefault) entries.add(getPath(s)); } catch (IllegalArgumentException e) { if (warn) { - log.warning(Warnings.InvalidPath(s)); + log.warning(LintWarnings.InvalidPath(s)); } } } @@ -318,7 +320,7 @@ private void addDirectory(Path dir, boolean warn) { if (!Files.isDirectory(dir)) { if (warn) { log.warning( - Warnings.DirPathElementNotFound(dir)); + LintWarnings.DirPathElementNotFound(dir)); } return; } @@ -364,7 +366,7 @@ public void addFile(Path file, boolean warn) { /* No such file or directory exists */ if (warn) { log.warning( - Warnings.PathElementNotFound(file)); + LintWarnings.PathElementNotFound(file)); } super.add(file); return; @@ -387,13 +389,13 @@ public void addFile(Path file, boolean warn) { FileSystems.newFileSystem(file, (ClassLoader)null).close(); if (warn) { log.warning( - Warnings.UnexpectedArchiveFile(file)); + LintWarnings.UnexpectedArchiveFile(file)); } } catch (IOException | ProviderNotFoundException e) { // FIXME: include e.getLocalizedMessage in warning if (warn) { log.warning( - Warnings.InvalidArchiveFile(file)); + LintWarnings.InvalidArchiveFile(file)); } return; } @@ -1658,8 +1660,8 @@ void add(Map> map, Path prefix, Path suffix) { if (!Files.isDirectory(prefix)) { if (warn) { Warning key = Files.exists(prefix) - ? Warnings.DirPathElementNotDirectory(prefix) - : Warnings.DirPathElementNotFound(prefix); + ? LintWarnings.DirPathElementNotDirectory(prefix) + : LintWarnings.DirPathElementNotFound(prefix); log.warning(key); } return; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java index ca620219ce015..7147e97289853 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java @@ -64,6 +64,7 @@ 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; @@ -856,7 +857,7 @@ protected boolean accepts(AttributeKind kind) { JavaFileObject prev = log.useSource(currentClassFile); try { log.warning((DiagnosticPosition) null, - Warnings.FutureAttr(name, version.major, version.minor, majorVersion, minorVersion)); + LintWarnings.FutureAttr(name, version.major, version.minor, majorVersion, minorVersion)); } finally { log.useSource(prev); } @@ -1610,7 +1611,7 @@ void readParameterAnnotations(Symbol meth) { //the RuntimeVisibleParameterAnnotations and RuntimeInvisibleParameterAnnotations //provide annotations for a different number of parameters, ignore: if (lintClassfile) { - log.warning(Warnings.RuntimeVisibleInvisibleParamAnnotationsMismatch(currentClassFile)); + log.warning(LintWarnings.RuntimeVisibleInvisibleParamAnnotationsMismatch(currentClassFile)); } for (int pnum = 0; pnum < numParameters; pnum++) { readAnnotations(); @@ -2078,9 +2079,9 @@ MethodSymbol findAccessMethod(Type container, Name name) { 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 @@ void adjustParameterAnnotations(MethodSymbol sym, Type methodDescriptor, private void dropParameterAnnotations() { parameterAnnotations = null; if (lintClassfile) { - log.warning(Warnings.RuntimeInvisibleParameterAnnotations(currentClassFile)); + log.warning(LintWarnings.RuntimeInvisibleParameterAnnotations(currentClassFile)); } } /** diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java index de81ddf58577e..1e8b85eb1437f 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java @@ -63,6 +63,7 @@ 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 boolean validate() { if (lintPaths) { Path outDirParent = outDir.getParent(); if (outDirParent != null && Files.exists(outDirParent.resolve("module-info.class"))) { - log.warning(Warnings.OutdirIsInExplodedModule(outDir)); + log.warning(LintWarnings.OutdirIsInExplodedModule(outDir)); } } } @@ -571,10 +572,10 @@ public boolean validate() { if (fm instanceof BaseFileManager baseFileManager) { if (source.compareTo(Source.JDK8) <= 0) { if (baseFileManager.isDefaultBootClassPath()) - log.warning(Warnings.SourceNoBootclasspath(source.name, releaseNote(source, targetString))); + log.warning(LintWarnings.SourceNoBootclasspath(source.name, releaseNote(source, targetString))); } else { if (baseFileManager.isDefaultSystemModulesPath()) - log.warning(Warnings.SourceNoSystemModulesPath(source.name, releaseNote(source, targetString))); + log.warning(LintWarnings.SourceNoSystemModulesPath(source.name, releaseNote(source, targetString))); } } } @@ -584,14 +585,14 @@ public boolean validate() { if (source.compareTo(Source.MIN) < 0) { log.error(Errors.OptionRemovedSource(source.name, Source.MIN.name)); } else if (source == Source.MIN && lintOptions) { - log.warning(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(Warnings.OptionObsoleteTarget(target)); + log.warning(LintWarnings.OptionObsoleteTarget(target)); obsoleteOptionFound = true; } @@ -625,7 +626,7 @@ public boolean validate() { } if (obsoleteOptionFound && lintOptions) { - log.warning(Warnings.OptionObsoleteSuppression); + log.warning(LintWarnings.OptionObsoleteSuppression); } SourceVersion sv = Source.toSourceVersion(source); @@ -636,7 +637,7 @@ public boolean validate() { validateDefaultModuleForCreatedFiles(sv); if (lintOptions && options.isSet(Option.ADD_OPENS)) { - log.warning(Warnings.AddopensIgnored); + log.warning(LintWarnings.AddopensIgnored); } return !errors && (log.nerrors == 0); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavaTokenizer.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavaTokenizer.java index a09d82aa70e1c..b25ca99eb88f7 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavaTokenizer.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavaTokenizer.java @@ -33,6 +33,7 @@ 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.util.*; @@ -1073,11 +1074,11 @@ public Token readToken() { TextBlockSupport.checkWhitespace(string); if (checks.contains(TextBlockSupport.WhitespaceChecks.INCONSISTENT)) { lexWarning(pos, - Warnings.InconsistentWhiteSpaceIndentation); + LintWarnings.InconsistentWhiteSpaceIndentation); } if (checks.contains(TextBlockSupport.WhitespaceChecks.TRAILING)) { lexWarning(pos, - Warnings.TrailingWhiteSpaceWillBeRemoved); + LintWarnings.TrailingWhiteSpaceWillBeRemoved); } } // Remove incidental indentation. diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java index 43b99f52e57bf..1413c51191378 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java @@ -42,6 +42,7 @@ 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.*; @@ -670,7 +671,7 @@ void reportDanglingDocComment(Comment c) { if (lint.isEnabled(Lint.LintCategory.DANGLING_DOC_COMMENTS) && !shebang(c, pos)) { log.warning( - pos, Warnings.DanglingDocComment); + pos, LintWarnings.DanglingDocComment); } }); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacFiler.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacFiler.java index 1c3f8ba96f882..3f30bee31f935 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacFiler.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacFiler.java @@ -57,6 +57,7 @@ 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 @@ private JavaFileObject createSourceOrClassFile(ModuleSymbol mod, boolean isSourc 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 @@ private void checkName(String name) throws FilerException { 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 @@ private void checkNameAndExistence(ModuleSymbol mod, String typename, boolean al 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 @@ private boolean containedInInitialInputs(String typename) { 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) diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java index 1870d487c5900..569e1f64a514a 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java @@ -70,6 +70,7 @@ 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.*; @@ -714,7 +715,7 @@ static class ProcessorState { add(importStringToPattern(allowModules, annotationPattern, processor, log, lint)); if (lint && !patternAdded) { - log.warning(Warnings.ProcDuplicateSupportedAnnotation(annotationPattern, + log.warning(LintWarnings.ProcDuplicateSupportedAnnotation(annotationPattern, p.getClass().getName())); } } @@ -728,7 +729,7 @@ static class ProcessorState { 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<>(); @@ -736,7 +737,7 @@ static class ProcessorState { 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())); } } @@ -957,7 +958,7 @@ private void discoverAndRunProcs(Set annotationsPresent, // 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())); } } @@ -1780,7 +1781,7 @@ private static Pattern importStringToPattern(boolean allowModules, String s, Pro 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 } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties index 8efce29d474a4..866bc30f3d569 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties @@ -1930,6 +1930,7 @@ 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. @@ -1939,6 +1940,7 @@ 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. @@ -3149,11 +3151,13 @@ 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} @@ -4214,6 +4218,7 @@ 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. diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/JCDiagnostic.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/JCDiagnostic.java index a8de786e1afbc..3e07751009b4d 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/JCDiagnostic.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/JCDiagnostic.java @@ -304,8 +304,8 @@ public JCDiagnostic create( //where DiagnosticInfo normalize(DiagnosticInfo diagnosticInfo) { //replace all nested FragmentKey with full-blown JCDiagnostic objects - LintCategory category = diagnosticInfo instanceof Warning warning ? - warning.category : null; + 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) ? @@ -542,7 +542,9 @@ public static DiagnosticInfo of(DiagnosticType type, LintCategory lc, String pre case ERROR: return new Error(prefix, code, args); case WARNING: - return new Warning(lc, 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: @@ -584,17 +586,26 @@ public Error(String prefix, String key, Object... args) { /** * Class representing warning diagnostic keys. */ - public static final class Warning extends DiagnosticInfo { - final LintCategory category; - + public static sealed class Warning extends DiagnosticInfo { public Warning(String prefix, String key, Object... args) { - this(null, prefix, key, args); + super(DiagnosticType.WARNING, prefix, key, args); } + } - public Warning(LintCategory category, String prefix, String key, Object... args) { - super(DiagnosticType.WARNING, prefix, key, args); + /** + * Class representing 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; + } } /** @@ -697,8 +708,8 @@ public boolean hasLintCategory() { * Get the associated lint category, or null if none. */ public LintCategory getLintCategory() { - return diagnosticInfo instanceof Warning warning ? - warning.category : null; + return diagnosticInfo instanceof LintWarning lintWarning ? + lintWarning.category : null; } /** diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/MandatoryWarningHandler.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/MandatoryWarningHandler.java index 463819afa698d..636563621a4a6 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/MandatoryWarningHandler.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/MandatoryWarningHandler.java @@ -33,6 +33,7 @@ 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; @@ -110,21 +111,25 @@ private enum DeferredDiagnosticKind { * True if mandatory warnings and notes are being enforced. * @param prefix A common prefix for the set of message keys for * the messages that may be generated. + * @param lc An associated lint category for the warnings, or null if none. */ public MandatoryWarningHandler(Log log, Source source, boolean verbose, - boolean enforceMandatory, String prefix) { + boolean enforceMandatory, String prefix, + LintCategory lc) { this.log = log; this.source = source; this.verbose = verbose; this.prefix = prefix; this.enforceMandatory = enforceMandatory; + this.lintCategory = lc; } /** * 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) @@ -243,6 +248,12 @@ public void reportDeferredDiagnostic() { */ private final boolean enforceMandatory; + /** + * A LintCategory to be included in point-of-use diagnostics to indicate + * how messages might be suppressed (i.e. with @SuppressWarnings). + */ + private final LintCategory lintCategory; + /** * Reports a mandatory warning to the log. If mandatory warnings * are not being enforced, treat this as an ordinary warning. diff --git a/test/langtools/tools/javac/6304921/TestLog.java b/test/langtools/tools/javac/6304921/TestLog.java index 3d88aa6fdfd65..41695554a8800 100644 --- a/test/langtools/tools/javac/6304921/TestLog.java +++ b/test/langtools/tools/javac/6304921/TestLog.java @@ -41,6 +41,7 @@ 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.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 void visitIf(JCTree.JCIf tree) { 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;