Skip to content

JAVA-7404 Derive redundant cast and unreachable catch warnings - #6581

Open
rombirli wants to merge 2 commits into
rombirli/semsitter-unused-import-warningsfrom
rombirli/semsitter-cast-catch-warnings
Open

rombirli wants to merge 2 commits into
rombirli/semsitter-unused-import-warningsfrom
rombirli/semsitter-cast-catch-warnings

Conversation

@rombirli

@rombirli rombirli commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Part 14 of 17 of JAVA-7392. Ticket: JAVA-7404.

Intent

Add the two remaining warning kinds the checks read: redundant casts and unreachable catch blocks.

flowchart LR
  W[CompilerWarnings] --> C[CastChecks: widening, identity, assignment context, binary promotion]
  W --> T[ThrownTypes: what a try body can throw]
  C --> RC[REDUNDANT_CAST]
  T --> MC[MASKED_CATCH]
Loading

From Warnings.expected.txt and CastContexts.expected.txt, identical to ECJ:

+WARNING REDUNDANT_CAST TYPE_CAST @21:21 Unnecessary cast from int to long
+WARNING MASKED_CATCH IDENTIFIER @87:14 Unreachable catch block for IOException. Only more specific exceptions are thrown and they are handled by previous catch block(s).

Test plan

  • CastChecksTest, ThrownTypesTest
  • same_warnings_as_ecj now compares all four kinds

Summary by Gitar

  • Redundant cast detection:
    • Added REDUNDANT_CAST derivation for widening, identity, assignment-context, and binary promotion casts via CastChecks
    • Added MASKED_CATCH derivation for unreachable checked catch blocks via ThrownTypes
  • Substitution:
    • Added preservesArguments to Substitution for generic argument checks

This will update automatically on new commits.

@hashicorp-vault-sonar-prod

hashicorp-vault-sonar-prod Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

JAVA-7404

@rombirli
rombirli added this pull request to stack #6570 November 25, 2026 11:48
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from bbb6daa to eefc450 Compare November 25, 2026 12:00
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from eefc450 to bb822e7 Compare November 25, 2026 12:03
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from bb822e7 to 2a830b6 Compare November 25, 2026 13:08
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch 2 times, most recently from 5498a07 to 282b42b Compare November 25, 2026 14:14
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 282b42b to d13a3f2 Compare November 25, 2026 14:55
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from d13a3f2 to a84e7b0 Compare November 25, 2026 15:32
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from a84e7b0 to a0d49f6 Compare November 25, 2026 16:31
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from a0d49f6 to 45c559b Compare November 25, 2026 17:16
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 45c559b to 523956b Compare November 25, 2026 18:03
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from b6c0a16 to edd8ae3 Compare November 30, 2026 15:51
@rombirli
rombirli removed this pull request from stack #6589 December 1, 2026 11:07
@rombirli
rombirli added this pull request to stack #6607 December 1, 2026 11:08
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from edd8ae3 to c0f56c2 Compare December 2, 2026 13:51
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from c0f56c2 to 2253d6a Compare December 2, 2026 14:21
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 2253d6a to 9eff99e Compare December 2, 2026 14:45
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 9eff99e to 4bf6d09 Compare December 2, 2026 15:04
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 4bf6d09 to 11ece98 Compare December 2, 2026 15:20
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 11ece98 to ddb53a3 Compare December 2, 2026 15:31
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from ddb53a3 to 932ddf2 Compare December 2, 2026 16:15
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 932ddf2 to b9ee141 Compare December 2, 2026 16:42
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from b9ee141 to 6653bda Compare December 2, 2026 16:50
@gitar-bot

gitar-bot Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved 🟡 Medium risk 11 closed / 11 findings

Adding cast and catch-flow warning derivation changes Java analysis diagnostics; incorrect type-flow inference could emit or suppress warnings in affected code.

Derives REDUNDANT_CAST for widening, identity, assignment-context, and binary promotion casts via CastChecks, and MASKED_CATCH for unreachable checked catch blocks via ThrownTypes, with preservesArguments added to Substitution. Seven earlier findings were resolved, and three were closed without a fix in this PR.

  • Open (minor): the test sample in CastChecksTest.java passes lambdas to take(Object), which is not a functional interface, so the code does not compile and the argument-lambda path is not actually exercised. Switching to a functional-interface parameter such as Supplier<Object> would fix it.
✅ 11 closed
✅ Bug: Overload check misses inherited methods, so casts get falsely flagged

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CastChecks.java:69-79 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CompilerWarnings.java:138-143
soleParameterType decides that no other overload could take the call by counting owner.membersNamed(name). JTypeSymbol.membersNamed only returns members declared on that type, not inherited ones. Take class A { void take(String s) {} } and class B extends A { void take(Object o) {} void m(String s) { take((Object) s); } }. The call resolves to B.take(Object), and B declares one take with arity 1, so assignedTo returns Object. isAssignable(String, Object) holds, so visitTypeCast emits REDUNDANT_CAST. But removing the cast makes the call pick A.take(String), so the cast is needed and ECJ does not warn here. lambdaResult also calls soleParameterType, so the same false positive applies to lambdas passed as arguments. Fix: count overloads with the same name and arity across the whole supertype hierarchy, and treat any second candidate as not sole.

✅ Quality: assignedTo test passes for argument casts only because ECJ symbols are used

📄 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/CastChecksTest.java:149-153
The test parses SOURCE with ECJ, so method.owner() is an ECJ symbol rather than the SemSitter JTypeSymbol. soleParameterType therefore always returns empty. As a result, assignedTo(8) (take((String) o), where take(Object) is the only overload) and assignedTo(9) (a lambda passed to the non-generic take) are asserted isEmpty(). In production, assignedTo returns Object for both, which is why CastContexts.expected.txt reports take((Object) s) at 51:10. So the test asserts the opposite of the real behaviour and never runs the overload-counting path. Fix: build these cases with SemSitter-translated trees, or assert the parameter type with a sema where the owner is a JTypeSymbol.

✅ Bug: Widening primitive cast into a reference target is flagged as redundant

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CompilerWarnings.java:157-159 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CastChecks.java:138-152
Take Object o = (long) i; with i an int, or take((long) i) where take(Object) is the only overload, or return (long) i; in a method returning Object. In each case acceptedAsIs is true:

  • castKeepsValue(int, long) holds because the cast widens.
  • assignedTo returns Object.
  • isAssignable(int, Object) holds because the boxed Integer is a subtype of Object.

The code then reports "Unnecessary cast from int to long". Removing the cast is not safe: the value would box to Integer instead of Long, so o.equals(5L) and similar calls behave differently. ECJ does not warn here, because isIndirectlyUsed treats a base-type cast that is not compatible with a reference expected type as boxing. So this is both a wrong suggestion and a mismatch with the replay goldens. Number n = (int) s with a short s is affected the same way (Short vs Integer).

Fix: for a primitive cast, only accept the target when the target is itself primitive.

✅ Bug: Intersection casts flagged redundant using only the first bound

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CompilerWarnings.java:155-169
visitTypeCast takes cast = tree.type().symbolType(), which is only the first bound of an intersection cast. widening and identity never check tree.bounds(), but the message still joins every bound. Take Comparable c; Serializable s = (Comparable & Serializable) c;. The operand Comparable has the same erasure and arguments as the first bound, so identity is true and the check reports Unnecessary cast from Comparable to Comparable & Serializable. Removing that cast breaks compilation, because Comparable is not assignable to Serializable. The widening && cast.isArray() && isIndexedArray path has the same problem. Fix: when the cast has extra bounds, also require the operand to be a subtype of each bound before treating it as widening/identity. The acceptedAsIs path is already correct, because it checks against the assignment target.

✅ Edge Case: Unnamed variable _ turns off MASKED_CATCH for the whole file

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CompilerWarnings.java:220-227
reportUnreachableCatches(unit) skips every try in the file as soon as any collected identifier has symbol().isUnknown(). IdentifierTreeImpl.symbol() always returns Symbol.UNKNOWN_SYMBOL when isUnnamedVariable is set. So resolved Java 22+ code that uses _ anywhere (for example catch (IOException _) or (a, _) -> ...) loses every MASKED_CATCH warning, while ECJ still reports them. Fix: leave unnamed-variable identifiers out of the unresolved check, for example by filtering on IdentifierTreeImpl.isUnnamedVariable() or skipping identifiers named _.

...and 6 more closed from earlier reviews

Verification Rules 3/3 met PRs 2 inspected

Functional validation No results

Rules 3 passed 1 not applicable

✅ Internal artifact registries
✅ Release secrets usage
✅ Repository license compliance

Broader impact PRs 2 inspected
Cross-PR 2 PRs inspected 0 open impacts

PR 6553: SONARJAVA-7339 Parse with the SemSitter translator behind the feature flag Inspected
PR 6578: JAVA-7401 Rank library overloads to pick the most specific method Inspected

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Auto-apply is off → Gitar will not commit updates to this branch.
Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Auto-apply Compact
gitar auto-apply:on         
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

@sonarqube-next

sonarqube-next Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

This branch has not been deployed

No deployments
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.

1 participant