Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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,44 @@
/*
* Copyright 2026 The Error Prone Authors.
*
* 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.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.suppliers.Supplier;
import com.sun.source.tree.ExpressionTree;
import com.sun.tools.javac.code.Type;

/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(summary = "Do not compare MemorySegments using reference equality.", severity = ERROR)
public final class MemorySegmentReferenceEquality extends AbstractReferenceEquality {

private static final Supplier<Type> MEMORY_SEGMENT_TYPE =
VisitorState.memoize(state -> state.getTypeFromString("java.lang.foreign.MemorySegment"));

@Override
protected boolean matchArgument(ExpressionTree tree, VisitorState state) {
Type type = getType(tree);
Type memorySegmentType = MEMORY_SEGMENT_TYPE.get(state);
return (type == null || memorySegmentType == null)
? false
: isSubtype(type, memorySegmentType, state);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@
import com.google.errorprone.bugpatterns.MathAbsoluteNegative;
import com.google.errorprone.bugpatterns.MathRoundIntLong;
import com.google.errorprone.bugpatterns.MemoizeConstantVisitorStateLookups;
import com.google.errorprone.bugpatterns.MemorySegmentReferenceEquality;
import com.google.errorprone.bugpatterns.MethodCanBeStatic;
import com.google.errorprone.bugpatterns.MisformattedTestData;
import com.google.errorprone.bugpatterns.MisleadingEmptyVarargs;
Expand Down Expand Up @@ -808,6 +809,7 @@ public static ScannerSupplier warningChecks() {
LoopConditionChecker.class,
LossyPrimitiveCompare.class,
MathRoundIntLong.class,
MemorySegmentReferenceEquality.class,
MislabeledAndroidString.class,
MisleadingEmptyVarargs.class,
MisleadingEscapedSpace.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/*
* Copyright 2026 The Error Prone Authors.
*
* 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.google.errorprone.bugpatterns;

import static com.google.common.truth.TruthJUnit.assume;

import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
* @author kak@google.com (Kurt Alfred Kluever)
*/
@RunWith(JUnit4.class)
public class MemorySegmentReferenceEqualityTest {

private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(MemorySegmentReferenceEquality.class, getClass());

@Before
public void setUp() {
assume().that(Runtime.version().feature()).isAtLeast(22);
}

@Test
public void positiveCase_equal() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;

class Test {
boolean f(MemorySegment a, MemorySegment b) {
return a == b;
}
}
""")
.addOutputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;
import java.util.Objects;

class Test {
boolean f(MemorySegment a, MemorySegment b) {
return Objects.equals(a, b);
}
}
""")
.doTest();
}

@Test
public void positiveCase_notEqual() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;

class Test {
boolean f(MemorySegment a, MemorySegment b) {
return a != b;
}
}
""")
.addOutputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;
import java.util.Objects;

class Test {
boolean f(MemorySegment a, MemorySegment b) {
return !Objects.equals(a, b);
}
}
""")
.doTest();
}

@Test
public void negativeCase_null() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;

class Test {
boolean f(MemorySegment b) {
return b == null;
}

boolean g(MemorySegment b) {
return b != null;
}

boolean h(MemorySegment b) {
return null == b;
}

boolean i(MemorySegment b) {
return null != b;
}
}
""")
.expectUnchanged()
.doTest();
}

@Test
public void compareToNullConstant() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;

class Test {
boolean f(MemorySegment a) {
return a == MemorySegment.NULL;
}

boolean g(MemorySegment a) {
return a != MemorySegment.NULL;
}

boolean h(MemorySegment a) {
return MemorySegment.NULL == a;
}

boolean i(MemorySegment a) {
return MemorySegment.NULL != a;
}
}
""")
.addOutputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;
import java.util.Objects;

class Test {
boolean f(MemorySegment a) {
return Objects.equals(a, MemorySegment.NULL);
}

boolean g(MemorySegment a) {
return !Objects.equals(a, MemorySegment.NULL);
}

boolean h(MemorySegment a) {
return Objects.equals(MemorySegment.NULL, a);
}

boolean i(MemorySegment a) {
return !Objects.equals(MemorySegment.NULL, a);
}
}
""")
.doTest();
}

@Test
public void compareToNullConstant_notEqual() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;

class Test {
boolean f(MemorySegment a) {
return a != MemorySegment.NULL;
}

boolean g(MemorySegment a) {
return MemorySegment.NULL != a;
}
}
""")
.addOutputLines(
"Test.java",
"""
import java.lang.foreign.MemorySegment;
import java.util.Objects;

class Test {
boolean f(MemorySegment a) {
return !Objects.equals(a, MemorySegment.NULL);
}

boolean g(MemorySegment a) {
return !Objects.equals(MemorySegment.NULL, a);
}
}
""")
.doTest();
}
}
27 changes: 27 additions & 0 deletions docs/bugpattern/MemorySegmentReferenceEquality.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
`MemorySegment` is a value-based class. Comparing `MemorySegment` instances
using `==` or `!=` is bug-prone because `MemorySegment` implementations may not
be unique for the same underlying memory. Use `Objects.equals()` (or `.equals()`
if the receiver is known to be non-null) instead.

For example:

```java
MemorySegment seg = ...;
if (seg == MemorySegment.NULL) { // reference equality
...
}
```

should be:

```java
MemorySegment seg = ...;
if (Objects.equals(seg, MemorySegment.NULL)) { // value equality
...
}
```

Reference equality between any two `MemorySegment` instances (e.g., `a == b`) is
flagged by this check, and `Objects.equals(a, b)` is the preferred alternative.

See also https://bugs.openjdk.org/browse/JDK-8381012
Loading