You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
JAVA-7398 Translate SemSitter documents into the Java syntax tree - #6575
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:
declarations, names, literals and annotations (other constructs throw UnsupportedConstructException, so the file is a parse error)
expressions, invocations and creations
statements
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 ECJassertThat(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
Code Review✅ Approved🟡 Medium risk9 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part 7 of 17 of JAVA-7392. Ticket: JAVA-7398.
Intent
SemSitterTranslatorturns a SemSitter document into the sameCompilationUnitTreeECJ builds, with symbols and types fromJSema. It implements theDocumentTranslatorof PR3.Review commit by commit, each one is green on its own:
UnsupportedConstructException, so the file is a parse error)ReplayTestchecks every recorded sample twice:The approved
X.expected.txtfiles 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
ReplayTeston the 58 recorded samples: same tree shape as ECJ and approved semantics