Skip to content
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

Optional.toString() should throw error #2833

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* (c) Copyright 2024 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.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.Optional;

@AutoService(BugChecker.class)
@BugPattern(
link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks",
linkType = BugPattern.LinkType.CUSTOM,
severity = SeverityLevel.ERROR,
Priyadarshanvijay marked this conversation as resolved.
Show resolved Hide resolved
summary = "Optional.toString() does not stringifies the value contained by the Optional"
+ " object. Did you mean Optional.get().toString() instead?")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we want to suggest Optional.get().toString(). This is not always appropriate, as the optional may be empty.

Even if we do want to suggest a fix, the right way to do this is with Error Prone's suggested fixes, rather than in the description, so that the fixes can be applied automatically.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, but not sure how we can use Error Prone's suggested fixes here since like you highlighted, the actual fix depends on the context

public final class OptionalToString extends BugChecker implements BugChecker.MethodInvocationTreeMatcher {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want this, we need to devise a roll out plan, since there may be a lot of existing code that does this and we don't want Baseline upgrades to be blocked.

Typically we do this by automating the fix, but that seems more difficult here since the correct fix is context dependnent.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would changing SeverityLevel to WARNING instead of error unblock the upgrades? Or should we suggest people to add SuppressWarnings if this is the behavior they want?
I think if there are many places in existing codebases where people are using this then this probably points to some runtime error in their code and shouldn't it be better to fix it manually?


private static final Matcher<ExpressionTree> OPTIONAL_TO_STRING_METHOD = MethodMatchers.instanceMethod()
.onExactClassAny(Optional.class.getName(), com.google.common.base.Optional.class.getName())
.named("toString")
.withNoParameters();

@Override
public Description matchMethodInvocation(MethodInvocationTree methodInvocationTree, VisitorState visitorState) {
if (OPTIONAL_TO_STRING_METHOD.matches(methodInvocationTree, visitorState)) {
return describeMatch(methodInvocationTree);
}

return Description.NO_MATCH;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* (c) Copyright 2024 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.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class OptionalToStringUsageTest {

private CompilationTestHelper compilationHelper;

@BeforeEach
public void before() {
compilationHelper = CompilationTestHelper.newInstance(OptionalToString.class, getClass());
}

@Test
public void should_throw_error_if_to_string_is_invoked_on_java_optional() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Optional;",
"class Test {",
" String f() {",
" // BUG: Diagnostic contains: Optional.toString() does not stringifies the value",
" return Optional.of(\"This is an optional value\").toString();",
" }",
"}")
.doTest();
}

@Test
public void should_throw_error_if_to_string_is_invoked_on_guava_optional() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" String f() {",
" // BUG: Diagnostic contains: Optional.toString() does not stringifies the value",
" return Optional.of(\"This is an optional value\").toString();",
" }",
"}")
.doTest();
}

@Test
public void should_not_throw_error_if_to_string_is_invoked_on_optional_get() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Optional;",
"class Test {",
" String f() {",
" return Optional.of(\"This is an optional value\").get().toString();",
" }",
"}")
.doTest();
}
}
5 changes: 5 additions & 0 deletions changelog/@unreleased/pr-2833.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type: improvement
improvement:
description: Optional.toString() should throw error
links:
- https://github.com/palantir/gradle-baseline/pull/2833