Skip to content

Commit

Permalink
8170326: Inconsistencies between code, compiler.properties and comments
Browse files Browse the repository at this point in the history
Converting uses of Log and JCDiagnostic.Factory methods to use CompilerProperties instead of plain Strings, fixing inconsistencies, adding crules analyzer to ensure CompilerProperties are used whenever possible.

Reviewed-by: mcimadamore
  • Loading branch information
lahodaj committed Jun 15, 2017
1 parent e994de3 commit 75831b7
Show file tree
Hide file tree
Showing 68 changed files with 821 additions and 673 deletions.
3 changes: 2 additions & 1 deletion langtools/make/tools/crules/CodingRulesAnalyzerPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ public void init(JavacTask task, String... args) {
task.addTaskListener(new PostAnalyzeTaskListener(
new MutableFieldsAnalyzer(task),
new AssertCheckAnalyzer(task),
new DefinedByAnalyzer(task)
new DefinedByAnalyzer(task),
new LegacyLogMethodAnalyzer(task)
));
}

Expand Down
95 changes: 95 additions & 0 deletions langtools/make/tools/crules/LegacyLogMethodAnalyzer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

package crules;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import com.sun.source.util.JavacTask;
import com.sun.source.util.TaskEvent.Kind;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.Tag;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.AbstractLog;
import com.sun.tools.javac.util.JCDiagnostic;

/**This analyzer guards against legacy Log.error/warning/note methods that don't use the typed keys.*/
public class LegacyLogMethodAnalyzer extends AbstractCodingRulesAnalyzer {

public LegacyLogMethodAnalyzer(JavacTask task) {
super(task);
treeVisitor = new LegacyLogMethodVisitor();
eventKind = Kind.ANALYZE;
}

private static final Set<String> LEGACY_METHOD_NAMES = new HashSet<>(
Arrays.asList("error", "mandatoryWarning", "warning", "mandatoryNote", "note", "fragment"));

class LegacyLogMethodVisitor extends TreeScanner {

@Override
public void visitClassDef(JCClassDecl tree) {
if (!tree.sym.packge().fullname.toString().startsWith("com.sun.tools.javac."))
return ;
super.visitClassDef(tree);
}

@Override
public void visitApply(JCMethodInvocation tree) {
checkLegacyLogMethod(tree);
super.visitApply(tree);
}

void checkLegacyLogMethod(JCMethodInvocation tree) {
Symbol method = TreeInfo.symbolFor(tree);
if (method == null ||
method.kind != Kinds.Kind.MTH ||
!typeToCheck(method.owner.type) ||
!LEGACY_METHOD_NAMES.contains(method.name.toString()) ||
!((MethodSymbol) method).isVarArgs() ||
method.type.getParameterTypes().size() < 2) {
return ;
}
JCExpression key = tree.args.get(method.type.getParameterTypes().size() - 2);
if (key.hasTag(Tag.LITERAL)) {
messages.error(tree, "crules.use.of.legacy.log.method", tree);
}
}

boolean typeToCheck(Type type) {
Symbol abstractLog = elements.getTypeElement(AbstractLog.class.getName());
Symbol diagnosticFactory = elements.getTypeElement(JCDiagnostic.Factory.class.getName().replace('$', '.'));
return types.isSubtype(type, abstractLog.type) ||
types.isSubtype(type, diagnosticFactory.type);
}
}
}
2 changes: 2 additions & 0 deletions langtools/make/tools/crules/resources/crules.properties
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,5 @@ crules.wrong.defined.by=\
This method implements a public API method, and is marked with incorrect @DefinedBy.
crules.defined.by.no.api=\
This method does not implement a public API method, and should not be marked with @DefinedBy.
crules.use.of.legacy.log.method=\
Should not use legacy Log or JCDiagnostic.Factory methods when methods accepting an Error/Warning/Note/Fragment key can be used.
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ final void read(File in) throws IOException {
if (line.startsWith(keyPrefix + ".")) {
int eq = line.indexOf("=");
if (eq > 0)
messages.put(line.substring(0, eq), new Message(currLine));
messages.put(line.substring(0, eq).trim(), new Message(currLine));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
public class MessageLine {

static final Pattern emptyOrCommentPattern = Pattern.compile("( *#.*)?");
static final Pattern typePattern = Pattern.compile("[-\\\\'A-Z\\.a-z ]+( \\([A-Za-z 0-9]+\\))?");
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()));

Expand Down
8 changes: 6 additions & 2 deletions langtools/make/tools/propertiesparser/parser/MessageType.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ public <R, A> R accept(Visitor<R, A> v, A a) {
*/
public enum SimpleType implements MessageType {

ANNOTATION("annotation", "Compound", "com.sun.tools.javac.code.Attribute"),
BOOLEAN("boolean", "boolean", null),
COLLECTION("collection", "Collection", "java.util"),
FLAG("flag", "Flag", "com.sun.tools.javac.code.Flags"),
FRAGMENT("fragment", "Fragment", null),
DIAGNOSTIC("diagnostic", "JCDiagnostic", "com.sun.tools.javac.util"),
MODIFIER("modifier", "Modifier", "javax.lang.model.element"),
Expand All @@ -81,7 +84,7 @@ public enum SimpleType implements MessageType {
NAME("name", "Name", "com.sun.tools.javac.util"),
NUMBER("number", "int", null),
OPTION_NAME("option name", "Option", "com.sun.tools.javac.main"),
SOURCE_VERSION("source version", "Source", "com.sun.tools.javac.code"),
SOURCE_VERSION("source version", "SourceVersion", "javax.lang.model"),
STRING("string", "String", null),
SYMBOL("symbol", "Symbol", "com.sun.tools.javac.code"),
SYMBOL_KIND("symbol kind", "Kind", "com.sun.tools.javac.code.Kinds"),
Expand Down Expand Up @@ -131,6 +134,7 @@ public static class CompoundType implements MessageType {
* Compound type kind.
*/
public enum Kind {
COLLECTION("collection of", SimpleType.COLLECTION),
LIST("list of", SimpleType.LIST),
SET("set of", SimpleType.SET);

Expand Down Expand Up @@ -180,7 +184,7 @@ public static class UnionType implements MessageType {
*/
public enum Kind {
MESSAGE_SEGMENT("message segment", SimpleType.DIAGNOSTIC, SimpleType.FRAGMENT),
FILE_NAME("file name", SimpleType.FILE, SimpleType.FILE_OBJECT);
FILE_NAME("file name", SimpleType.FILE, SimpleType.FILE_OBJECT, SimpleType.PATH);

final String kindName;
final SimpleType[] choices;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import com.sun.tools.javac.platform.PlatformDescription;
import com.sun.tools.javac.platform.PlatformDescription.PluginInfo;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.DefinedBy;
Expand Down Expand Up @@ -219,7 +220,7 @@ public void initPlugins(Set<List<String>> pluginOpts) {
}
}
for (List<String> p: pluginsToCall) {
Log.instance(context).error("plugin.not.found", p.head);
Log.instance(context).error(Errors.PluginNotFound(p.head));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@
import com.sun.tools.javac.parser.Tokens.Comment;
import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Notes;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.DCTree;
import com.sun.tools.javac.tree.DCTree.DCBlockTag;
import com.sun.tools.javac.tree.DCTree.DCDocComment;
Expand Down Expand Up @@ -1129,19 +1132,19 @@ private void printMessage(Diagnostic.Kind kind, CharSequence msg,
try {
switch (kind) {
case ERROR:
log.error(DiagnosticFlag.MULTIPLE, pos, "proc.messager", msg.toString());
log.error(DiagnosticFlag.MULTIPLE, pos, Errors.ProcMessager(msg.toString()));
break;

case WARNING:
log.warning(pos, "proc.messager", msg.toString());
log.warning(pos, Warnings.ProcMessager(msg.toString()));
break;

case MANDATORY_WARNING:
log.mandatoryWarning(pos, "proc.messager", msg.toString());
log.mandatoryWarning(pos, Warnings.ProcMessager(msg.toString()));
break;

default:
log.note(pos, "proc.messager", msg.toString());
log.note(pos, Notes.ProcMessager(msg.toString()));
}
} finally {
if (oldSource != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import com.sun.tools.javac.jvm.Profile;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.platform.PlatformDescription;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.util.*;

import static javax.tools.StandardLocation.*;
Expand Down Expand Up @@ -292,7 +293,9 @@ private void complete(Symbol sym) throws CompletionFailure {
try {
fillIn(p);
} catch (IOException ex) {
throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
JCDiagnostic msg =
diagFactory.fragment(Fragments.ExceptionMessage(ex.getLocalizedMessage()));
throw new CompletionFailure(sym, msg).initCause(ex);
}
}
if (!reader.filling)
Expand Down Expand Up @@ -329,7 +332,9 @@ private void completeEnclosing(ClassSymbol c) {
*/
void fillIn(ClassSymbol c) {
if (completionFailureName == c.fullname) {
throw new CompletionFailure(c, "user-selected completion failure by class name");
JCDiagnostic msg =
diagFactory.fragment(Fragments.UserSelectedCompletionFailure);
throw new CompletionFailure(c, msg);
}
currentOwner = c;
JavaFileObject classfile = c.classfile;
Expand Down Expand Up @@ -365,7 +370,7 @@ void fillIn(ClassSymbol c) {
// where
private CompletionFailure classFileNotFound(ClassSymbol c) {
JCDiagnostic diag =
diagFactory.fragment("class.file.not.found", c.flatname);
diagFactory.fragment(Fragments.ClassFileNotFound(c.flatname));
return newCompletionFailure(c, diag);
}
/** Static factory for CompletionFailure objects.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ private ModuleSymbol readModule(JavaFileObject fo) throws IOException {
name = moduleNameFromSourceReader.readModuleName(fo);
if (name == null) {
JCDiagnostic diag =
diags.fragment("file.does.not.contain.module");
diags.fragment(Fragments.FileDoesNotContainModule);
ClassSymbol errModuleInfo = syms.defineClass(names.module_info, syms.errModule);
throw new ClassFinder.BadClassFile(errModuleInfo, fo, diag, diags);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2148,18 +2148,6 @@ public static class CompletionFailure extends RuntimeException {
*/
public JCDiagnostic diag;

/** A localized string describing the failure.
* @deprecated Use {@code getDetail()} or {@code getMessage()}
*/
@Deprecated
public String errmsg;

public CompletionFailure(Symbol sym, String errmsg) {
this.sym = sym;
this.errmsg = errmsg;
// this.printStackTrace();//DEBUG
}

public CompletionFailure(Symbol sym, JCDiagnostic diag) {
this.sym = sym;
this.diag = diag;
Expand All @@ -2172,14 +2160,11 @@ public JCDiagnostic getDiagnostic() {

@Override
public String getMessage() {
if (diag != null)
return diag.getMessage(null);
else
return errmsg;
return diag.getMessage(null);
}

public Object getDetailValue() {
return (diag != null ? diag : errmsg);
public JCDiagnostic getDetailValue() {
return diag;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
import com.sun.tools.javac.comp.Attr;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.JCTree.JCBlock;
Expand Down Expand Up @@ -480,12 +481,12 @@ private Type typeWithAnnotations(final JCTree typetree, final Type type,
// The normal declaration annotation checks make sure that the use is valid.
break;
case 1:
log.error(typetree.pos(), "cant.type.annotate.scoping.1",
onlyTypeAnnotations);
log.error(typetree.pos(),
Errors.CantTypeAnnotateScoping1(onlyTypeAnnotations.head));
break;
default:
log.error(typetree.pos(), "cant.type.annotate.scoping",
onlyTypeAnnotations);
log.error(typetree.pos(),
Errors.CantTypeAnnotateScoping(onlyTypeAnnotations));
}
return type;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import static com.sun.tools.javac.code.Type.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.jvm.ClassFile.externalize;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;

/**
* Utility class containing various operations on types.
Expand Down Expand Up @@ -374,7 +375,7 @@ public Type getType(Type site) {
if (!chk.checkValidGenericType(site)) {
//if the inferred functional interface type is not well-formed,
//or if it's not a subtype of the original target, issue an error
throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
}
return memberType(site, descSym);
}
Expand Down Expand Up @@ -434,13 +435,13 @@ public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
} else {
//the target method(s) should be the only abstract members of t
throw failure("not.a.functional.intf.1", origin,
diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
diags.fragment(Fragments.IncompatibleAbstracts(Kinds.kindName(origin), origin)));
}
}
if (abstracts.isEmpty()) {
//t must define a suitable non-generic method
throw failure("not.a.functional.intf.1", origin,
diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
diags.fragment(Fragments.NoAbstracts(Kinds.kindName(origin), origin)));
} else if (abstracts.size() == 1) {
return new FunctionDescriptor(abstracts.first());
} else { // size > 1
Expand All @@ -456,9 +457,11 @@ public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
desc.type.getReturnType(),
desc.type.getThrownTypes()));
}
JCDiagnostic msg =
diags.fragment(Fragments.IncompatibleDescsInFunctionalIntf(Kinds.kindName(origin),
origin));
JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
Kinds.kindName(origin), origin), descriptors.toList());
new JCDiagnostic.MultilineDiagnostic(msg, descriptors.toList());
throw failure(incompatibleDescriptors);
}
return descRes;
Expand Down
Loading

0 comments on commit 75831b7

Please sign in to comment.