New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refactor for Error Message class use #284
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
287 changes: 287 additions & 0 deletions
287
nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,287 @@ | ||
package com.uber.nullaway; | ||
|
||
import static com.uber.nullaway.ErrorMessage.MessageTypes.FIELD_NO_INIT; | ||
import static com.uber.nullaway.ErrorMessage.MessageTypes.METHOD_NO_INIT; | ||
import static com.uber.nullaway.NullAway.INITIALIZATION_CHECK_NAME; | ||
import static com.uber.nullaway.NullAway.getTreesInstance; | ||
|
||
import com.google.common.base.Joiner; | ||
import com.google.common.collect.Iterables; | ||
import com.google.common.collect.Lists; | ||
import com.google.errorprone.VisitorState; | ||
import com.google.errorprone.fixes.SuggestedFix; | ||
import com.google.errorprone.matchers.Description; | ||
import com.google.errorprone.util.ASTHelpers; | ||
import com.sun.source.tree.AnnotationTree; | ||
import com.sun.source.tree.ClassTree; | ||
import com.sun.source.tree.MethodInvocationTree; | ||
import com.sun.source.tree.MethodTree; | ||
import com.sun.source.tree.ModifiersTree; | ||
import com.sun.source.tree.Tree; | ||
import com.sun.source.tree.VariableTree; | ||
import com.sun.source.util.TreePath; | ||
import com.sun.tools.javac.code.Symbol; | ||
import java.util.List; | ||
import java.util.Set; | ||
import java.util.stream.StreamSupport; | ||
import javax.annotation.Nullable; | ||
import javax.lang.model.element.Element; | ||
|
||
public class ErrorBuilder { | ||
|
||
private final Config config; | ||
private final String checkerName; | ||
private final Set<String> allNames; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What is this field? Pls document There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍Done |
||
|
||
ErrorBuilder(Config config, String checkerName, Set<String> allNames) { | ||
this.config = config; | ||
this.checkerName = checkerName; | ||
this.allNames = allNames; | ||
} | ||
|
||
/** | ||
* create an error description for a nullability warning | ||
* | ||
* @param errorMessage the error message object. | ||
* @param path the TreePath to the error location. Used to compute a suggested fix at the | ||
* enclosing method for the error location | ||
* @param descriptionBuilder the description builder for the error. | ||
* @return the error description | ||
*/ | ||
Description createErrorDescription( | ||
ErrorMessage errorMessage, TreePath path, Description.Builder descriptionBuilder) { | ||
Tree enclosingSuppressTree = suppressibleNode(path); | ||
return createErrorDescription(errorMessage, enclosingSuppressTree, descriptionBuilder); | ||
} | ||
|
||
/** | ||
* create an error description for a nullability warning | ||
* | ||
* @param errorMessage the error message object. | ||
* @param suggestTree the location at which a fix suggestion should be made | ||
* @param descriptionBuilder the description builder for the error. | ||
* @return the error description | ||
*/ | ||
public Description createErrorDescription( | ||
ErrorMessage errorMessage, | ||
@Nullable Tree suggestTree, | ||
Description.Builder descriptionBuilder) { | ||
Description.Builder builder = descriptionBuilder.setMessage(errorMessage.message); | ||
if (config.suggestSuppressions() && suggestTree != null) { | ||
switch (errorMessage.messageType) { | ||
case DEREFERENCE_NULLABLE: | ||
case RETURN_NULLABLE: | ||
case PASS_NULLABLE: | ||
case ASSIGN_FIELD_NULLABLE: | ||
if (config.getCastToNonNullMethod() != null) { | ||
builder = addCastToNonNullFix(suggestTree, builder); | ||
} else { | ||
builder = addSuppressWarningsFix(suggestTree, builder, checkerName); | ||
} | ||
break; | ||
case CAST_TO_NONNULL_ARG_NONNULL: | ||
builder = removeCastToNonNullFix(suggestTree, builder); | ||
break; | ||
case WRONG_OVERRIDE_RETURN: | ||
builder = addSuppressWarningsFix(suggestTree, builder, checkerName); | ||
break; | ||
case WRONG_OVERRIDE_PARAM: | ||
builder = addSuppressWarningsFix(suggestTree, builder, checkerName); | ||
break; | ||
case METHOD_NO_INIT: | ||
case FIELD_NO_INIT: | ||
builder = addSuppressWarningsFix(suggestTree, builder, INITIALIZATION_CHECK_NAME); | ||
break; | ||
case ANNOTATION_VALUE_INVALID: | ||
break; | ||
default: | ||
builder = addSuppressWarningsFix(suggestTree, builder, checkerName); | ||
} | ||
} | ||
// #letbuildersbuild | ||
return builder.build(); | ||
} | ||
|
||
/** | ||
* create an error description for a generalized @Nullable value to @NonNull location assignment. | ||
* | ||
* <p>This includes: field assignments, method arguments and method returns | ||
* | ||
* @param errorMessage the error message object. | ||
* @param suggestTreeIfCastToNonNull the location at which a fix suggestion should be made if a | ||
* castToNonNull method is available (usually the expression to cast) | ||
* @param suggestTreePathIfSuppression the location at which a fix suggestion should be made if a | ||
* castToNonNull method is not available (usually the enclosing method, or any place | ||
* where @SuppressWarnings can be added). | ||
* @param descriptionBuilder the description builder for the error. | ||
* @return the error description. | ||
*/ | ||
Description createErrorDescriptionForNullAssignment( | ||
ErrorMessage errorMessage, | ||
@Nullable Tree suggestTreeIfCastToNonNull, | ||
@Nullable TreePath suggestTreePathIfSuppression, | ||
Description.Builder descriptionBuilder) { | ||
final Tree enclosingSuppressTree = suppressibleNode(suggestTreePathIfSuppression); | ||
if (config.getCastToNonNullMethod() != null) { | ||
return createErrorDescription(errorMessage, suggestTreeIfCastToNonNull, descriptionBuilder); | ||
} else { | ||
return createErrorDescription(errorMessage, enclosingSuppressTree, descriptionBuilder); | ||
} | ||
} | ||
|
||
Description.Builder addSuppressWarningsFix( | ||
Tree suggestTree, Description.Builder builder, String checkerName) { | ||
SuppressWarnings extantSuppressWarnings = | ||
ASTHelpers.getAnnotation(suggestTree, SuppressWarnings.class); | ||
SuggestedFix fix; | ||
if (extantSuppressWarnings == null) { | ||
fix = | ||
SuggestedFix.prefixWith( | ||
suggestTree, | ||
"@SuppressWarnings(\"" | ||
+ checkerName | ||
+ "\") " | ||
+ config.getAutofixSuppressionComment()); | ||
} else { | ||
// need to update the existing list of warnings | ||
final List<String> suppressions = Lists.newArrayList(extantSuppressWarnings.value()); | ||
suppressions.add(checkerName); | ||
// find the existing annotation, so we can replace it | ||
final ModifiersTree modifiers = | ||
(suggestTree instanceof MethodTree) | ||
? ((MethodTree) suggestTree).getModifiers() | ||
: ((VariableTree) suggestTree).getModifiers(); | ||
final List<? extends AnnotationTree> annotations = modifiers.getAnnotations(); | ||
// noinspection ConstantConditions | ||
com.google.common.base.Optional<? extends AnnotationTree> suppressWarningsAnnot = | ||
Iterables.tryFind( | ||
annotations, | ||
annot -> annot.getAnnotationType().toString().endsWith("SuppressWarnings")); | ||
if (!suppressWarningsAnnot.isPresent()) { | ||
throw new AssertionError("something went horribly wrong"); | ||
} | ||
final String replacement = | ||
"@SuppressWarnings({" | ||
+ Joiner.on(',').join(Iterables.transform(suppressions, s -> '"' + s + '"')) | ||
+ "}) " | ||
+ config.getAutofixSuppressionComment(); | ||
fix = SuggestedFix.replace(suppressWarningsAnnot.get(), replacement); | ||
} | ||
return builder.addFix(fix); | ||
} | ||
|
||
/** | ||
* Adapted from {@link com.google.errorprone.fixes.SuggestedFixes}. | ||
* | ||
* <p>TODO: actually use {@link | ||
* com.google.errorprone.fixes.SuggestedFixes#addSuppressWarnings(VisitorState, String)} instead | ||
*/ | ||
@Nullable | ||
private Tree suppressibleNode(@Nullable TreePath path) { | ||
if (path == null) { | ||
return null; | ||
} | ||
return StreamSupport.stream(path.spliterator(), false) | ||
.filter( | ||
tree -> | ||
tree instanceof MethodTree | ||
|| (tree instanceof ClassTree | ||
&& ((ClassTree) tree).getSimpleName().length() != 0) | ||
|| tree instanceof VariableTree) | ||
.findFirst() | ||
.orElse(null); | ||
} | ||
|
||
private Description.Builder addCastToNonNullFix(Tree suggestTree, Description.Builder builder) { | ||
final String fullMethodName = config.getCastToNonNullMethod(); | ||
assert fullMethodName != null; | ||
// Add a call to castToNonNull around suggestTree: | ||
final String[] parts = fullMethodName.split("\\."); | ||
final String shortMethodName = parts[parts.length - 1]; | ||
final String replacement = shortMethodName + "(" + suggestTree.toString() + ")"; | ||
final SuggestedFix fix = | ||
SuggestedFix.builder() | ||
.replace(suggestTree, replacement) | ||
.addStaticImport(fullMethodName) // ensure castToNonNull static import | ||
.build(); | ||
return builder.addFix(fix); | ||
} | ||
|
||
private Description.Builder removeCastToNonNullFix( | ||
Tree suggestTree, Description.Builder builder) { | ||
assert suggestTree.getKind() == Tree.Kind.METHOD_INVOCATION; | ||
final MethodInvocationTree invTree = (MethodInvocationTree) suggestTree; | ||
final Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(invTree); | ||
final String qualifiedName = | ||
ASTHelpers.enclosingClass(methodSymbol) + "." + methodSymbol.getSimpleName().toString(); | ||
if (!qualifiedName.equals(config.getCastToNonNullMethod())) { | ||
throw new RuntimeException("suggestTree should point to the castToNonNull invocation."); | ||
} | ||
// Remove the call to castToNonNull: | ||
final SuggestedFix fix = | ||
SuggestedFix.builder() | ||
.replace(suggestTree, invTree.getArguments().get(0).toString()) | ||
.build(); | ||
return builder.addFix(fix); | ||
} | ||
|
||
void reportInitializerError( | ||
Symbol.MethodSymbol methodSymbol, | ||
String message, | ||
VisitorState state, | ||
Description.Builder descriptionBuilder) { | ||
if (symbolHasSuppressInitializationWarningsAnnotation(methodSymbol)) { | ||
return; | ||
} | ||
Tree methodTree = getTreesInstance(state).getTree(methodSymbol); | ||
state.reportMatch( | ||
createErrorDescription( | ||
new ErrorMessage(METHOD_NO_INIT, message), methodTree, descriptionBuilder)); | ||
} | ||
|
||
boolean symbolHasSuppressInitializationWarningsAnnotation(Symbol symbol) { | ||
SuppressWarnings annotation = symbol.getAnnotation(SuppressWarnings.class); | ||
if (annotation != null) { | ||
for (String s : annotation.value()) { | ||
// we need to check for standard suppressions here also since we may report initialization | ||
// errors outside the normal ErrorProne match* methods | ||
if (s.equals(INITIALIZATION_CHECK_NAME) || allNames.stream().anyMatch(s::equals)) { | ||
return true; | ||
} | ||
} | ||
} | ||
return false; | ||
} | ||
|
||
static String errMsgForInitializer(Set<Element> uninitFields) { | ||
String message = "initializer method does not guarantee @NonNull "; | ||
if (uninitFields.size() == 1) { | ||
message += "field " + uninitFields.iterator().next().toString() + " is initialized"; | ||
} else { | ||
message += "fields " + Joiner.on(", ").join(uninitFields) + " are initialized"; | ||
} | ||
message += " along all control-flow paths (remember to check for exceptions or early returns)."; | ||
return message; | ||
} | ||
|
||
void reportInitErrorOnField(Symbol symbol, VisitorState state, Description.Builder builder) { | ||
if (symbolHasSuppressInitializationWarningsAnnotation(symbol)) { | ||
return; | ||
} | ||
Tree tree = getTreesInstance(state).getTree(symbol); | ||
if (symbol.isStatic()) { | ||
state.reportMatch( | ||
createErrorDescription( | ||
new ErrorMessage( | ||
FIELD_NO_INIT, "@NonNull static field " + symbol + " not initialized"), | ||
tree, | ||
builder)); | ||
} else { | ||
state.reportMatch( | ||
createErrorDescription( | ||
new ErrorMessage(FIELD_NO_INIT, "@NonNull field " + symbol + " not initialized"), | ||
tree, | ||
builder)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this be maybe
suppressionName
? Looks like it's just used when generating a@SuppressWarnings
. Pls also add docsThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍Done