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

@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 523956b to e10d981 Compare November 25, 2026 18:39
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from e10d981 to b9cce65 Compare November 25, 2026 20:45
@rombirli
rombirli removed this pull request from stack #6570 November 25, 2026 20:47
@rombirli
rombirli added this pull request to stack #6589 November 25, 2026 20:48
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from b9cce65 to a0b8fe6 Compare November 25, 2026 20:57
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from a0b8fe6 to 15946fe Compare November 25, 2026 21:26
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 15946fe to 37b29c7 Compare November 25, 2026 21:28
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 37b29c7 to 6becbe9 Compare November 27, 2026 07:55
@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from 6becbe9 to a00d670 Compare November 27, 2026 08:29
@datadog-sonarsource

This comment has been minimized.

@rombirli
rombirli force-pushed the rombirli/semsitter-cast-catch-warnings branch from a00d670 to 6d30c73 Compare November 27, 2026 09:24
@gitar-bot

gitar-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown
CI failed: The ruling-update job failed because the upstream ruling-qa job was cancelled and uploaded no actual artifacts, so the update action found nothing to download. The log does not show why ruling-qa was cancelled, and the finding is not attributed to this PR's warning-derivation or golden changes.

Overview

The ruling-update job failed because the upstream ruling-qa job was cancelled and uploaded no actual artifacts, so the update action found nothing to download. The log does not show why ruling-qa was cancelled, and the finding is not attributed to this PR's warning-derivation or golden changes.

Failures

Ruling-update job fails on missing actual artifacts after upstream ruling-qa cancellation (unrelated to PR)

  • Type: infrastructure
  • Affected jobs: 140420214319
  • Related to change: no
  • Confidence: high
  • Root cause: The log reports needs.ruling-qa.result as cancelled; the wrapper treats any non-success result as ruling-failed=true. The update action then attempts to sync ruling artifacts, but none are available, so it exits with No artifacts were downloaded. The log does not show why ruling-qa was cancelled or any failing test assertion. The PR changes warning derivation and replay goldens, but there is no evidence that those changes caused the cancellation or affected the artifact-download step.
  • Suggested fix: Determine why the upstream ruling-qa job was cancelled and rerun it to completion so it can upload its artifacts. Also make the update action skip artifact syncing or handle the cancelled/no-artifacts case gracefully.

Summary

  • Change-related failures: 0
  • Infrastructure/flaky failures: 1
  • Recommended action: Determine why the upstream ruling-qa job was cancelled and rerun it to completion so it can upload its artifacts. Also make the update action skip artifact syncing or handle the cancelled/no-artifacts case gracefully.
Code Review ✅ Approved 🟡 Medium risk 8 closed / 8 findings

Adding redundant-cast and masked-catch derivation changes Java diagnostics; imperfect type or exception analysis could produce misleading warnings.

Derives REDUNDANT_CAST and MASKED_CATCH warnings from the compiler warnings so the SemSitter frontend matches ECJ for redundant casts and unreachable catch blocks. Resolved issues include inherited-method overload misses, widening casts into reference targets, intersection cast bounds, and the unnamed variable _ disabling MASKED_CATCH for the whole file. No open issues remain.

✅ 8 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 3 more closed from earlier reviews

Verification Rules 3/3 met Repos 4 inspected · PRs 4 inspected

Functional validation No results

Rules 3 passed 2 not applicable

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

Broader impact Repos 4 inspected PRs 4 inspected
Cross-repo 4 repositories inspected 0 open impacts

SonarSource/sonarlint-intellij Inspected
SonarSource/sonarlint-eclipse Inspected
SonarSource/sonar-iac Inspected
SonarSource/sonar-java-symbolic-execution Inspected

Cross-PR 4 PRs inspected 0 open impacts

PR 6576: JAVA-7399 Infer invocation return types, thrown types and diamonds Inspected
PR 6578: JAVA-7401 Rank library overloads to pick the most specific method Inspected
PR 6579: JAVA-7402 Expose annotations and nullability through symbol metadata Inspected
PR 6583: JAVA-7406 Offer the SemSitter frontend behind a flag Inspected

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Tip

Comment Gitar fix CI or enable auto-apply: gitar auto-apply:on

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

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