-
Notifications
You must be signed in to change notification settings - Fork 135
Fix #831: Error Prone StringBuilderConstantParameters #832
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ae21601
Fix #831: Error Prone StringBuilderConstantParameters
a8be963
Add generated changelog entries
5a7225d
state.getSourceForNode
9af4f0b
handle ternary
68cedc4
Handle operators
c46ff9b
Merge branch 'develop' into ckozak/gh831
carterkozak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
164 changes: 164 additions & 0 deletions
164
...prone/src/main/java/com/palantir/baseline/errorprone/StringBuilderConstantParameters.java
This file contains hidden or 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,164 @@ | ||
| /* | ||
| * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.palantir.baseline.errorprone; | ||
|
|
||
| import com.google.auto.service.AutoService; | ||
| import com.google.common.base.Preconditions; | ||
| import com.google.common.collect.Streams; | ||
| import com.google.errorprone.BugPattern; | ||
| import com.google.errorprone.BugPattern.SeverityLevel; | ||
| import com.google.errorprone.VisitorState; | ||
| import com.google.errorprone.bugpatterns.BugChecker; | ||
| import com.google.errorprone.fixes.SuggestedFix; | ||
| import com.google.errorprone.matchers.Description; | ||
| import com.google.errorprone.matchers.Matcher; | ||
| import com.google.errorprone.matchers.Matchers; | ||
| import com.google.errorprone.matchers.method.MethodMatchers; | ||
| import com.google.errorprone.util.ASTHelpers; | ||
| import com.sun.source.tree.BinaryTree; | ||
| import com.sun.source.tree.ConditionalExpressionTree; | ||
| import com.sun.source.tree.ExpressionTree; | ||
| import com.sun.source.tree.MemberSelectTree; | ||
| import com.sun.source.tree.MethodInvocationTree; | ||
| import com.sun.source.tree.NewClassTree; | ||
| import com.sun.source.util.SimpleTreeVisitor; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.Stream; | ||
|
|
||
| @AutoService(BugChecker.class) | ||
| @BugPattern( | ||
| name = "StringBuilderConstantParameters", | ||
| severity = SeverityLevel.WARNING, | ||
| summary = "StringBuilder with a constant number of parameters should be replaced by simple concatenation") | ||
| public final class StringBuilderConstantParameters | ||
| extends BugChecker implements BugChecker.MethodInvocationTreeMatcher { | ||
| private static final String MESSAGE = | ||
| "StringBuilder with a constant number of parameters should be replaced by simple concatenation.\nThe Java " | ||
| + "compiler (jdk8) replaces concatenation of a constant number of arguments with a StringBuilder, " | ||
| + "while jdk 9+ take advantage of JEP 280 (https://openjdk.java.net/jeps/280) to efficiently " | ||
| + "pre-size the result for better performance than a StringBuilder."; | ||
|
|
||
| private static final long serialVersionUID = 1L; | ||
|
|
||
| private static final Matcher<ExpressionTree> STRING_BUILDER_TYPE_MATCHER = Matchers.isSameType(StringBuilder.class); | ||
| private static final Matcher<ExpressionTree> STRING_BUILDER_TO_STRING = | ||
| MethodMatchers.instanceMethod() | ||
| .onExactClass(StringBuilder.class.getName()) | ||
| .named("toString") | ||
| .withParameters(); | ||
|
|
||
| @Override | ||
| public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { | ||
| if (!STRING_BUILDER_TO_STRING.matches(tree, state)) { | ||
| return Description.NO_MATCH; | ||
| } | ||
| Optional<List<ExpressionTree>> result = tree.getMethodSelect().accept(StringBuilderVisitor.INSTANCE, state); | ||
| if (!result.isPresent()) { | ||
| return Description.NO_MATCH; | ||
| } | ||
| List<ExpressionTree> arguments = result.get(); | ||
| Stream<String> prefixStream = arguments.stream().findFirst() | ||
| .map(ASTHelpers::getType) | ||
| .filter(type -> | ||
| ASTHelpers.isSameType(type, state.getTypeFromString("java.lang.String"), state)) | ||
| .map(ignored -> Stream.<String>of()) | ||
| .orElseGet(() -> Stream.of("\"\"")); | ||
|
|
||
| return buildDescription(tree) | ||
| .setMessage(MESSAGE) | ||
| .addFix(SuggestedFix.builder() | ||
| .replace(tree, Streams.concat(prefixStream, arguments.stream() | ||
| .map(node -> getArgumentSourceString(state, node))) | ||
| .collect(Collectors.joining(" + "))) | ||
| .build()) | ||
| .build(); | ||
| } | ||
|
|
||
| private static String getArgumentSourceString(VisitorState state, ExpressionTree tree) { | ||
| String originalSource = state.getSourceForNode(tree); | ||
| // Ternary expressions must be parenthesized to avoid leaking into preceding or following expressions. | ||
| if (tree instanceof ConditionalExpressionTree || tree instanceof BinaryTree) { | ||
| return '(' + originalSource + ')'; | ||
| } | ||
| return originalSource; | ||
| } | ||
|
|
||
| /** | ||
| * {@link StringBuilderVisitor} checks if a {@link StringBuilder#toString()} invocation can be followed up | ||
| * a fluent invocation chain, therefore must have a constant number of arguments. | ||
| * If so, the visitor results in a present {@link Optional} of {@link ExpressionTree arguments} in the order | ||
| * they are {@link StringBuilder#append(Object) appended}, otherwise an {@link Optional#empty() empty optional} | ||
| * is returned. | ||
| * This allows us to maintain a single implementation for validation and building a {@link SuggestedFix} without | ||
| * sacrificing build time allocating objects for {@link StringBuilder builders} which don't fit our pattern. | ||
| */ | ||
| private static final class StringBuilderVisitor | ||
| extends SimpleTreeVisitor<Optional<List<ExpressionTree>>, VisitorState> { | ||
| private static final StringBuilderVisitor INSTANCE = new StringBuilderVisitor(); | ||
|
|
||
| private StringBuilderVisitor() { | ||
| super(Optional.empty()); | ||
| } | ||
|
|
||
| @Override | ||
| public Optional<List<ExpressionTree>> visitNewClass(NewClassTree node, VisitorState state) { | ||
| if (!STRING_BUILDER_TYPE_MATCHER.matches(node.getIdentifier(), state)) { | ||
| return defaultAction(node, state); | ||
| } | ||
| if (node.getArguments().isEmpty()) { | ||
| return Optional.of(new ArrayList<>()); | ||
| } | ||
| if (node.getArguments().size() == 1 | ||
| // We shouldn't replace pre-sized builders until we target java 11 across most libraries. | ||
| && (ASTHelpers.isSameType( | ||
| ASTHelpers.getType(node.getArguments().get(0)), | ||
| state.getTypeFromString("java.lang.String"), state) | ||
| || ASTHelpers.isSameType( | ||
| ASTHelpers.getType(node.getArguments().get(0)), | ||
| state.getTypeFromString("java.lang.CharSequence"), state))) { | ||
| List<ExpressionTree> resultList = new ArrayList<>(); | ||
| resultList.add(node.getArguments().get(0)); | ||
| return Optional.of(resultList); | ||
| } | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| @Override | ||
| public Optional<List<ExpressionTree>> visitMemberSelect(MemberSelectTree node, VisitorState state) { | ||
| if (node.getIdentifier().contentEquals("append") | ||
| || node.getIdentifier().contentEquals("toString")) { | ||
| return node.getExpression().accept(this, state); | ||
| } | ||
| return defaultAction(node, state); | ||
| } | ||
|
|
||
| @Override | ||
| public Optional<List<ExpressionTree>> visitMethodInvocation( | ||
| MethodInvocationTree node, | ||
| VisitorState state) { | ||
| Optional<List<ExpressionTree>> result = node.getMethodSelect().accept(this, state); | ||
| if (result.isPresent()) { | ||
| Preconditions.checkState(node.getArguments().size() == 1, "Expected a single argument to 'append'"); | ||
| result.get().add(node.getArguments().get(0)); | ||
| } | ||
| return result; | ||
| } | ||
| } | ||
| } | ||
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.
What is the semantic difference between an absent list and present empty list?
Uh oh!
There was an error while loading. Please reload this page.
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.
Documented here: https://github.com/palantir/gradle-baseline/pull/832/files#diff-515ce9d314ac0796483b739fc5035b83R104-R110
Optional of empty list will result from:
Which should be replaced with:
Where empty optional tells us this invocation doesn't match, and we should return
Description.NO_MATCH.