Skip to content

[java] Fix #6693: CloneMethodMustImplementCloneable false positive for local-var throw - #6885

Merged
UncleOwen merged 10 commits into
pmd:mainfrom
hexonal:fix-clone-method-throws-local-var
Sep 6, 2026
Merged

UncleOwen merged 10 commits into
pmd:mainfrom
hexonal:fix-clone-method-throws-local-var

Conversation

@hexonal

@hexonal hexonal commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Fixes #6693.

justThrowsCloneNotSupported() only exempts a clone() method whose body is the single statement throw new CloneNotSupportedException();. A body that instead assigns the exception to a local variable first and then throws it,

CloneNotSupportedException e = new CloneNotSupportedException();
throw e;

is semantically identical but has body.size() == 2, so the exemption check fails and the class is wrongly flagged for not implementing Cloneable.

Adds throwsLocalCloneNotSupported, checked when the body has exactly two statements: the first must be a local variable declaration of a single variable whose initializer is-a CloneNotSupportedException, and the second must be a throw of that same variable (matched by symbol equality). Added a regression test case matching the issue's second case.

…-var throw

justThrowsCloneNotSupported() only recognized the exemption when the
clone() body was the single statement "throw new
CloneNotSupportedException();". A clone() that assigns the exception to
a local variable first and then throws it,

    CloneNotSupportedException e = new CloneNotSupportedException();
    throw e;

is semantically identical but has a body of size 2, so the check failed
and the rule reported a violation even though the class still doesn't
implement Cloneable on purpose.

Add throwsLocalCloneNotSupported() to recognize this two-statement form:
the first statement must declare a single local variable of type
CloneNotSupportedException, and the second must throw that same
variable.

Fixes pmd#6693
@pmd-actions-helper

pmd-actions-helper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Documentation Preview

Compared to main:
This changeset changes 0 violations,
introduces 0 new violations, 0 new errors and 0 new configuration errors,
removes 0 violations, 16 errors and 9 configuration errors.
There are 0 changed duplications, 0 new duplications and 0 removed duplications.
There are 0 changed CPD errors, 0 new CPD errors and 0 removed CPD errors.

Regression Tester Report

(comment created at 2026-09-06 16:46:49+00:00 for 6b04e87)

…rows-local-var

# Conflicts:
#	docs/pages/release_notes.md

@zbynek zbynek left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the contribution. The implementation indeed fixes the specific case described in the linked issue, but I think we should first decide what the desired behavior of this rule is.

The rule description says

The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.

One interpretation of that is that doing anything more complex than a single throw statement is not applicable for the exception, in which case the issue is invalid.

Another way to interpret it is that implementations are allowed if they contain no return and all their throw statements throw an instance of CloneNotSupportedException. That would allow e.g. a logging statement added to that method.
I think adjusting the rule implementation to follow this interpretation would be useful. Allowing only the one special case mentioned in #6693 seems too specific, such code violates the VariableCanBeInlined rule.

Walk the whole clone() method body instead of pattern-matching one
specific two-statement shape. Exempt bodies with no return statement
where every throw is (a subtype of) CloneNotSupportedException and at
least one throw is present, so a no-op override isn't wrongly exempted.
@hexonal

hexonal commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — I agree with the second interpretation, and I've reworked the implementation to follow it.

Instead of pattern-matching the one specific two-statement shape from #6693, the check now walks the whole method body (without crossing into nested/anonymous classes or lambdas, since their control flow isn't the enclosing clone() method's) and requires:

  • no return statement anywhere in the body, and
  • every throw statement in the body throws (a subtype of) CloneNotSupportedException, and
  • at least one throw statement is actually present.

That last condition matters more than it looks: a naive "no return + all throws are CloneNotSupportedException" check is vacuously true for a body with zero throw statements, which would wrongly exempt a no-op clone() override that doesn't actually block cloning. I added a regression test for that case.

This now covers cases beyond the original issue too — e.g. a logging call before the throw, or the throw sitting inside a try/catch — while still flagging methods that mix a CloneNotSupportedException throw with some other exception type, or that also return on some path. I also added a test for a return inside a nested lambda to confirm it correctly doesn't leak into the enclosing method's check.

You're also right that the shape this PR originally special-cased would itself trip VariableCanBeInlined — good catch, and one more reason the narrower fix wasn't the right stopping point.

All 26 rule test cases (20 existing + 6 new) pass, and I confirmed the new ones actually exercise the change by checking they fail against the old narrow implementation before restoring the fix. Let me know if you'd like the exemption scoped any differently (e.g. excluding try/catch bodies specifically, or requiring the throw to be reachable unconditionally).

…ntCloneable

Covers a clone() body where an if/else has a CloneNotSupportedException
throw in each branch (no fall-through, no single unconditional throw),
exercising the "every throw statement" part of the broadened exemption
in a shape not covered by the existing tests.
@hexonal

hexonal commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed feedback, @zbynek. I agree the broader interpretation is the right one. Gating on the one specific pattern from #6693 was too narrow, and as you point out, that pattern is arguably something VariableCanBeInlined should be nudging people away from anyway.

I reworked justThrowsCloneNotSupported: a clone() body is now exempt when it contains no return statement anywhere, and at least one throw statement, with every throw statement throwing a CloneNotSupportedException. This replaces the old single-statement and local-var-then-throw special cases entirely, since both are just instances of the new, more general check, and the method ended up smaller than before.

It's implemented with ASTBlock#descendants(...), which doesn't cross "find boundaries" (nested types, anonymous classes, local classes, lambdas). So a return or throw inside a nested class or lambda doesn't count against the enclosing clone() method's own control flow, e.g. a Runnable with a return inside it stays exempt.

Test coverage now includes the newly-permitted cases:

  • a statement (logging) before the throw
  • the throw reached via a try/catch around other code
  • multiple branches (if/else) that each throw CloneNotSupportedException
  • a return inside a nested lambda not counting against the method

and cases that must still be flagged:

  • no throw statement at all (an empty/no-op override)
  • a throw of some other exception type mixed in with a CloneNotSupportedException throw
  • a return statement present anywhere in the body, even alongside a throw

All 27 tests for this rule pass, and I ran the full errorprone package test suite (1108 tests) as a broader regression check with no failures. I also reverted just the implementation while keeping the tests, to confirm they exercise real behavior: exactly the 3 tests covering genuinely new cases (statement-before-throw, try/catch, nested-lambda-return) fail without the fix.

One thing worth flagging rather than leaving for you to find later: this check is syntactic, not a full JLS reachability analysis. It handles the cases above correctly, but there's a case it under-reports: a void clone() whose only throw sits inside an if with no else, followed by other code, so the method can fall off the end normally on the untaken branch:

void clone() {
    if (someCondition) {
        throw new CloneNotSupportedException();
    }
    System.out.println("done");
}

The body has no return and its one throw is a CloneNotSupportedException, so this is currently treated as exempt, even though the method can complete normally without throwing anything when someCondition is false. I confirmed this by testing it directly against the pushed code. That's a missed violation, not a false positive, so it doesn't bring back the original #6693 bug. It also matches an existing simplification in this codebase: LambdaMirrorImpl#isLambdaBodyCompatible uses the same "no return, throw exists" approximation for lambda bodies instead of full reachability analysis, and says so in a comment.

There's already a proper JLS 14.21-style reachability analysis in the codebase, AbruptCompletionAnalysis#canCompleteNormally under symbols.table.internal, currently used only for pattern-variable scoping. It could answer this precisely, but it's package-private and not meant for rule authors, so using it here would mean widening that package's public surface. That felt like a bigger call than this fix should make on its own, so I left it out. Happy to wire it up as a follow-up if you want the fully rigorous version. Otherwise I think the current check is a reasonable match for the interpretation you described and consistent with how the codebase already handles the same tradeoff elsewhere.

Pushed as two commits on the same branch: the reimplementation, plus one small commit adding the if/else multi-branch test.

@UncleOwen

Copy link
Copy Markdown
Member

The rule description says

The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.

One interpretation of that is that doing anything more complex than a single throw statement is not applicable for the exception, in which case the issue is invalid.

That's how I always understood that sentence.

Another way to interpret it is that implementations are allowed if they contain no return and all their throw statements throw an instance of CloneNotSupportedException. That would allow e.g. a logging statement added to that method. I think adjusting the rule implementation to follow this interpretation would be useful. Allowing only the one special case mentioned in #6693 seems too specific, such code violates the VariableCanBeInlined rule.

I agree that allowing logging statements is a good thing. But your definition would allow an arbitrary combination of loops and other control statements, variable assignments and function calls. Is that really what we want? Where should we draw the line?

@zbynek

zbynek commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

@UncleOwen

Where should we draw the line?

I think the line should not be based on the content of the method, but on the possible outcome.

  • methods that might return something (contain a return statement in any branch/loop) -- only allowed in Cloneable classes, as they are now
  • methods that do not contain a return, so they always throw
    • if all the explicit throw statements throw CloneNotSupportedException, allow them.
    • if an explicit throw might throw something else -- report them, unless they are in Cloneable class

I'm mentioning explicit throw statements, because this was considered valid before and should still be valid (for this rule):

protected Object clone() throws CloneNotSupportedException { // actually always throws IOOBE
  throw new CloneNotSupportedException(List.of("fail").get(7));
}

@hexonal

there's a case it under-reports: a void clone() whose only throw sits inside an if with no else,

That code would not compile. Method called clone() with no parameters must return an Object. So counting return statements is sufficient to decide if the method always throws or not.
I noticed that several old testcases violate this, maybe you could update them here (or it can be done in a separate PR).

@UncleOwen

Copy link
Copy Markdown
Member

@UncleOwen

Where should we draw the line?

I think the line should not be based on the content of the method, but on the possible outcome.

But outcome includes side-effects. For example:

public class Foo {
    public static int count = 0;

    public Foo clone() {
        count++;
        throw new CloneNotSupportedException();
    }
}

That's not "only throws CloneNotSupportedException", is it?

@zbynek

zbynek commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Well, side-effects are ignored in current implementation too 🤷

public class Foo {
    public static AtomicInteger count = new AtomicInteger(0);

    public Foo clone() {
        throw new CloneNotSupportedException(count.incrementAndGet() + "");
    }
}

@UncleOwen

Copy link
Copy Markdown
Member

I'd argue that that's a bug that should be fixed.

@hexonal

hexonal commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

@zbynek good catch, and you're right -- I checked it directly rather than taking my own word for it:

$ javac Foo.java
Foo.java:2: error: clone() in Foo cannot override clone() in Object
    public void clone() {
                ^
  return type void is incompatible with Object

So a no-parameter clone() can never legally have a void return type in any class (it always collides with Object#clone()'s signature) -- my "falls off the end of a void clone()" example wasn't just an edge case the rule under-reports, it isn't reachable in real code at all. That's good news for the implementation: it means checking for the absence of a return statement really is sufficient to know the method always throws, not just a convenient approximation the way it is for lambda bodies. I'll drop that caveat from my writeup here rather than leave a stale concern in the thread.

On the old void clone() {} cases in the test XML -- confirmed those predate this PR (they're present on main, not something I introduced). I'll take the separate-PR option you offered rather than fold that cleanup into this one, so this PR's diff stays scoped to the behavior change you and UncleOwen are still working out above. Happy to send that once I know it won't collide with anything -- let me know if you'd rather I just do it here instead.

@UncleOwen

Copy link
Copy Markdown
Member

I'm still concerned that this change will allow too much and introduce a bunch of false negatives. How about something like this:

A clone method must...

  • have no return statement
  • no control structures (if, switch, loops)
  • no function calls (except for logging.)
  • all throws must throw an instance of CloneNotSupportedException
  • all variables declared must be of type CloneNotSupportedException
  • all assignments must be to variables declared inside the method

@zbynek

zbynek commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

I think the main purpose of the rule is to enforce that "every clone() method should be in a class implementing Cloneable interface, unless it prevents the object from being cloned". To implement that, it would be enough to check that the method is final and contains no returns OR its declaring class implements Cloneable.

I agree with your point that clone should not have side effects, but I don't think that should be part of this rule, since it would imply that users should change

class A {

@Override
protected final Object clone() {
   System.setErr(System.out); // bad
   throw new CloneNotSupportedException();
}

to

class A implements Cloneable {

@Override
protected final Object clone() {
   System.setErr(System.out); // good, we're Cloneable now, rule name says ...MustImplementCloneable
   throw new CloneNotSupportedException();
}

which does not seem helpful.

Technically even insisting that the method's throw statements all throw CloneNotSupportedException has this issue (is only enforcef when interface not present), but I think that's a reasonable trade-off.

@UncleOwen

Copy link
Copy Markdown
Member

Yeah, ok. I think you're right.

Just to explain where I was coming from. I consider the Cloneable interface to be fundamentally broken. If you've got the 3rd edition of "Effective Java" lying around, see Item 13. That's why I insisted so much on a literal interpretation of the exceptional part of the rule. But I guess I shouldn't shoehorn my opinion into a rule that is fundamentally about something else.

@hexonal

hexonal commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @UncleOwen — and to be explicit about it, I'm not going to implement the six-bullet version, since you've withdrawn it.

That leaves one thing I'd rather ask about than guess at, because I measured it and it cuts against the obvious reading.

@zbynek, your 07-25 summary was:

it would be enough to check that the method is final and contains no returns OR its declaring class implements Cloneable

I built that gate and ran it. It reports the snippet you posted on 07-23 — the one you said "was considered valid before and should still be valid (for this rule)":

public class Foo {
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException(List.of("fail").get(7));
    }
}

Current head: 0 violations. With the finality gate: 1. The method is protected, not final, and the class isn't Cloneable, so the gate rejects the exemption and the class check then fires. Your 07-25 examples all write protected final Object clone(), which is presumably why the tension didn't show up there — those stay at 0 either way.

The part I think neither of you has had reason to look at: the finality condition in the rule's description has never actually been implemented. The pre-PR body of the check was

body.size() == 1 && body.getChild(0)...filter(it -> TypeTestUtil.isA(CloneNotSupportedException.class, it)).nonEmpty()

with no modifier inspection anywhere in the file — JModifier has never appeared in it in the rule's history. So "check that the method is final" wouldn't be restoring documented behavior; it'd be a new restriction that reports strictly more code than today. That's a bigger change than the #6693 false positive this PR was opened for, which is why I'd rather have it be a decision than an inference on my part.

So, concretely: add the finality gate in this PR (with a Changed Rules release note), or keep this PR scoped to the #6693 false positive and treat finality separately?

Some measurements, so it's answerable in one round either way:

  • The gate is a no-op on all 27 of this rule's existing test cases — every one reports identically with and without it. So the existing suite can't validate it; the entire effect lands on real-world code and the regression tester. I'd add tests pinning it if you want it.
  • It has to test the enclosing class's finality, not just the method's. PMD doesn't propagate a class's final to its methods, so a method-only check regresses an existing test: Bug 1698550, nr 2 (xml:235) is public final class Foo with a non-final public Object clone(), and a method-only gate flips it from 0 to 1. ProperCloneImplementationRule has the enclosing-type form already.
  • Current head implements your explicit 07-22 ask ("no return and all their throw statements throw an instance of CloneNotSupportedException") and your 07-23 four-bullet outcome-based spec as written — neither mentions finality, which is the other reason I stopped rather than extending.

Two smaller things while you're here:

My 07-23 question is still open — the pre-existing non-compilable void clone() cases in the test XML: fold the cleanup in here, or separate PR? Happy either way, just don't want to widen this diff without asking. (Separately, one of those non-compilable snippets is mine, from this PR, so I'll make that one compile regardless.)

And a note rather than a request: every workflow run on this branch has sat at action_required since 07-18, so no CI has run against the current head. A run whenever it's convenient would be useful before this goes anywhere.

The snippet added for "no throw statement at all is not exempted" didn't
compile, on two counts: the method was package-private, which assigns weaker
access than the inherited protected Object.clone(), and the body fell off the
end of a method declared to return Object.

`protected final Object clone()` with a `while (true)` body fixes both while
keeping the case exactly as pointed: no return statement, no throw statement,
non-Cloneable class, so the exemption's "at least one throw" condition is what
decides it. Still reports 1.

Leaves the pre-existing `void clone()` cases alone -- those predate this PR and
zbynek offered to handle them separately.
@UncleOwen

Copy link
Copy Markdown
Member

@zbynek I'll leave this one to you.

@adangel adangel changed the title [java] Fix CloneMethodMustImplementCloneable false positive for local-var throw [java] Fix #6693: CloneMethodMustImplementCloneable false positive for local-var throw Aug 14, 2026
…rows-local-var

Resolves the release-notes conflict: re-adds the pmd#6693 bullet under the
current unreleased java-errorprone section, in issue-number order. The
rule and test files are unchanged upstream since the merge base.
@hexonal

hexonal commented Aug 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the approval @zbynek — the branch had gone stale in the meantime, so I've merged current main in.

The only conflict was docs/pages/release_notes.md: the unreleased section had moved on, so the #6693 bullet is re-added under the current java-errorprone heading, in issue-number order. CloneMethodMustImplementCloneableRule.java and the rule's test XML are untouched upstream since the merge base, so the reviewed diff is unchanged — still 17+/7- and 122+/0- on exactly those two files, byte for byte.

Merged rather than rebased so the approval isn't dismissed. Ready when you are.

@hexonal

hexonal commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Merged current main in — this had gone into conflict after the 7.27.0 release reset docs/pages/release_notes.md.

The conflict was only in that file: my one entry was sitting in the old accumulated list, so I took the fresh post-release file and re-added the #6693 line under java-errorprone. The rule and its test data merged cleanly, and main has not touched either file since the branch point, so the reviewed diff is unchanged (+1, +17-7, +122).

Used a merge rather than a rebase so the existing approval is not dismissed.

CloneMethodMustImplementCloneableTest passes on the merged tree: 27 tests, 0 failures.

@UncleOwen UncleOwen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks.

I moved your tests to the end and removed one I found misleading. It was kind-of implying we're handling

try {
    throw new Foo();
 } catch (Foo ex) {
    throw new CloneNotSupportedException();
}

correctly, which we don't. But I think this is good enough for now.

@UncleOwen UncleOwen added this to the 7.28.0 milestone Sep 6, 2026
@UncleOwen
UncleOwen merged commit 305b820 into pmd:main Sep 6, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[java] CloneMethodMustImplementCloneable: False positive with throw-via-local

3 participants