Skip to content

JAVA-7398 Translate SemSitter documents into the Java syntax tree - #6575

Open
rombirli wants to merge 5 commits into
rombirli/semsitter-replay-recordingsfrom
rombirli/semsitter-translator
Open

rombirli wants to merge 5 commits into
rombirli/semsitter-replay-recordingsfrom
rombirli/semsitter-translator

Conversation

@rombirli

@rombirli rombirli commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Part 7 of 17 of JAVA-7392. Ticket: JAVA-7398.

Intent

SemSitterTranslator turns a SemSitter document into the same CompilationUnitTree ECJ builds, with symbols and types from JSema. It implements the DocumentTranslator of PR3.

flowchart LR
  D[Document] --> T[SemSitterTranslator]
  T --> DT[DeclarationTranslator, MemberTranslator, TypeTranslator]
  T --> ET[ExpressionTranslator, InvocationTranslator, NameTranslator]
  T --> ST[StatementTranslator, SwitchTranslator, LambdaTranslator]
  DT & ET & ST --> U[CompilationUnitTree with JSema symbols]
Loading

Review commit by commit, each one is green on its own:

  1. declarations, names, literals and annotations (other constructs throw UnsupportedConstructException, so the file is a parse error)
  2. expressions, invocations and creations
  3. statements
  4. lambdas, method references, patterns, switches and try

ReplayTest checks every recorded sample twice:

assertThat(TreeDescription.shape(semSitter.get())).containsExactlyElementsOf(TreeDescription.shape(ecj.get()));   // same tree as ECJ
assertThat(describe(translate(sample))).containsExactlyElementsOf(Replays.read(approved).lines().toList());        // approved semantics

The approved X.expected.txt files describe every tree node with its symbol and type. The next PRs change them only where they improve the result, so their diffs show the gain.

State on master

Nothing calls the translator outside tests.

Test plan

  • ReplayTest on the 58 recorded samples: same tree shape as ECJ and approved semantics
  • Unit tests per translator part

@hashicorp-vault-sonar-prod

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

Copy link
Copy Markdown
Contributor

JAVA-7398

@rombirli
rombirli added this pull request to stack #6570 November 25, 2026 11:48
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 2288b1b to 02b2832 Compare November 25, 2026 12:00
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 02b2832 to 67efecf Compare November 25, 2026 12:03
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch 2 times, most recently from c562fbf to e0f2902 Compare November 25, 2026 13:41
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from e0f2902 to e696653 Compare November 25, 2026 14:14
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch 2 times, most recently from ab2ba7d to 8ad1940 Compare November 25, 2026 15:32
@sonarqube-next

Copy link
Copy Markdown
Contributor

@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 8ad1940 to ad7309c Compare November 25, 2026 16:31
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch 3 times, most recently from 3078497 to da00fc1 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-translator branch from da00fc1 to 5290fb0 Compare November 27, 2026 07:55
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 5290fb0 to 6d1d41a Compare November 27, 2026 08:29
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from bd6282e to 8cf8ed1 Compare November 30, 2026 07:24
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 8cf8ed1 to 3d552c1 Compare November 30, 2026 15:47
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 3d552c1 to 27c24f3 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-translator branch from 27c24f3 to 4598569 Compare December 2, 2026 13:35
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 4598569 to 33f3ee0 Compare December 2, 2026 14:06
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 33f3ee0 to 855f15d Compare December 2, 2026 14:36
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 855f15d to 71c6d6b Compare December 2, 2026 14:55
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch 2 times, most recently from 4daece8 to 133b60a Compare December 2, 2026 15:30
@rombirli
rombirli force-pushed the rombirli/semsitter-translator branch from 133b60a to bd9ae8f Compare December 2, 2026 16:15
@sonarqube-next

sonarqube-next Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@gitar-bot

gitar-bot Bot commented Dec 2, 2026 •

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

The new SemSitter translator adds extensive syntax and symbol binding; errors could mislead consumers, but it is currently used only in tests.

Translates SemSitter documents into the same CompilationUnitTree ECJ builds, covering declarations, names, literals, annotations, expressions, invocations, statements, lambdas, method references, patterns, switches and try. Seven review findings were resolved, including effectively-final marking, narrowing conversions, recorder package output, call target rebinding, and functional method detection. No open findings remain.

✅ 9 closed
✅ Bug: Effectively-final marking counts assignments instead of using flow

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/EffectivelyFinalVariables.java:34-48 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/EffectivelyFinalVariables.java:70-84
EffectivelyFinalVariables.mark decides JLS 4.12.4 effective finality by counting syntactic assignments. A local declared without an initializer counts as effectively final only when it has at most one plain assignment. That gets both directions wrong:

  • False negative: int x; if (c) x = 1; else x = 2; Runnable r = () -> use(x); compiles, because x is definitely unassigned before each assignment. Here the counter reaches 2, so isEffectivelyFinal() returns false.
  • False positive: int x; while (c) { x = 1; } has only one syntactic assignment, but x is not definitely unassigned before it inside the loop. It is not effectively final (javac rejects capturing it), yet this code marks it effectively final.

ECJ computes this flag with definite-assignment analysis, so the SemSitter tree gives checks that read Symbol.VariableSymbol#isEffectivelyFinal different answers. This contradicts the class Javadoc's claim to work "as the compiler does". Separately, the Tree.Kind.FOR_STATEMENT entry in isLocalDeclaration never matches, because a for-init variable's parent is the initializer ListTreeImpl (kind LIST). To match ECJ, base the flag on definite-unassignment of the variable at each assignment, at least for if/else branches, switch arms and loops. Otherwise, document the approximation and make isLocalDeclaration accept a LIST parent whose parent is a FOR_STATEMENT.

✅ Bug: Conditional narrows to byte/short/char without checking the int fits

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ExpressionTranslator.java:319-333
In numericPromotion, a conditional takes the narrow operand type T (byte, short or char) whenever the other operand is any INT_LITERAL. JLS 15.25 only allows this when the int constant fits in T. For example, flag ? b : 300 with byte b has type int, but this code types it byte, and flag ? c : 70000 with char c is typed char. A negative constant such as -1 is a UNARY_MINUS tree, not an INT_LITERAL, so it misses the narrowing even when it fits. The fix is to read the literal's value (handling hex, octal, binary and underscores, and folding a unary minus) and narrow only when it lies within T's range.

✅ Bug: Recorder rewrites packages.json as {} because nothing fills packages

📄 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ReplayRecorderTest.java:52-59 📄 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ReplayRecorderTest.java:63 📄 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ReplayRecorderTest.java:86-91 📄 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ReplayRecorderTest.java:109-115
record_every_sample creates an empty packages JsonObject, hands it to every recordSample call, and then writes it with Replays.writeSorted(Replays.PACKAGES, packages). recordSample never adds anything to it. The hasPackage(SemSitterClient, String) helper that would query the server is never called. Running the documented recording procedure (-Dsemsitter.record=true) therefore replaces the checked-in replay/packages.json, which currently holds "com.example.missing": false and "java.util": true, with an empty object. ReplayTest and TranslationStateFixtures load that file, so its recorded answers are lost. Fix: record the package answers into packages (for example by wiring hasPackage(client, name) into the loader the translator uses), or stop writing PACKAGES until something fills it.

✅ Bug: Rebinding a call target leaves its recorded use on the old method

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/InvocationTranslator.java:70 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/InvocationTranslator.java:88-90 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/InvocationTranslator.java:103-114 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/InvocationTranslator.java:117-127 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/InvocationTranslator.java:130-138 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSema.java:276-284
invocation() first calls bindUse, which runs sema.use(usageId(symbol, target), identifier) and records the call under the symbol SemSitter resolved. Three later steps then rebind the identifier with plain Bindings.bind, which only calls setSymbol:

  • bindStaticImport switches to the statically imported method.
  • bindLibraryOrOverload replaces an arity-only target with the overload declaredMethod picks, or binds a library method for an unresolved name.
  • refineMethodBinding drops the method to UNKNOWN_METHOD.

In each case usages() on the originally resolved symbol still lists this call even though the tree no longer points to it, and the newly bound method never gets the use. The repo's rule is to move uses before rebinding. This PR adds JSema.moveUse for that, but no main code calls it. bindConstructor does call recordUse, so constructors and methods now behave differently. Fix: call sema.moveUse(oldId, newId, identifier) (using usageId) wherever the invocation's identifier is rebound to a different symbol.

✅ Edge Case: functionalMethod counts abstract methods overridden by defaults

📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberLookup.java:283-297 📄 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberLookup.java:168-181
collectAbstractMethods only records abstract methods, keyed by name and arity with putIfAbsent. A default method in a subinterface therefore does not hide the abstract method it overrides in a superinterface. Example: for interface B extends A { default void a() {} void b(); } with A { void a(); }, B's default a is skipped, then A's abstract a is added. found ends up as {a, b}, and functionalMethod(B) returns null even though B is a functional interface. As a result, lambdas targeting B get no functional method, and takesNoFunction can discard valid overloads. Fix: track every name/arity key you visit, abstract or not, so a subtype's concrete or default declaration shadows inherited abstract ones.

...and 4 more closed from earlier reviews

Verification Knowledge 🔎 1 Repos 2 inspected

Functional validation No results

Rules 3 not applicable

Knowledge 🔎 1 informed a finding

🔎 Move uses before rebinding overloads informed a finding, resolved -> Rebinding a call target leaves its recorded use on the old method

Broader impact Repos 2 inspected
Cross-repo 2 repositories inspected 0 open impacts

SonarSource/sonar-java-symbolic-execution Inspected
SonarSource/sonar-iac 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

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