Skip to content

Support for <expr> instanceof <Type> <var> - #3976

Open
wadoon wants to merge 35 commits into
mainfrom
weigl/instanceof
Open

wadoon wants to merge 35 commits into
mainfrom
weigl/instanceof

Conversation

@wadoon

@wadoon wadoon commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Intended Change

Add support for Java 16 instanceof patterns of the form <expr> instanceof <Type> <var>, including the JLS 6.3.1.5 flow-scoping rules for the pattern variable. Code such as

if (!(o instanceof String s)) {
    return false;
}
return s.isEmpty();

now loads and can be proved in KeY.

Primary changes

  • Parser, AST and translation: new InstanceofPattern node, translated during loading. Each pattern name maps to one ProgramVariable, shared by the declaration and all uses in its scope.
  • Pattern-aware if rules: ifUnfoldPattern, ifElseUnfoldPattern and ifUnfoldPatternUnreachable evaluate the guard once and introduce #posBinding/#negBinding in the branches where the binding is guaranteed. This is needed because the generic ifUnfold/ifElseUnfold rules do not know about pattern bindings and would drop the declaration. Braced and braceless branches are both supported.
  • Pattern-variable identity: after declaring pattern variable y for x instanceof T y, #posBinding/#negBinding emit a JML assume x == y. This makes the identity of the bound variable with the tested reference explicit in the branch; non-nullness follows from the instanceof guard. The assumption is omitted when the tested expression cannot be converted without an execution context.
  • Flow scoping after an if: AlwaysAbnormallyTerminatingAnalysis and the \alwaysAbnormallyTerminates varcond implement JLS 14.22. If the then branch cannot complete normally, ifUnfoldPatternUnreachable declares the pattern variable after the if. Without this, legal code such as the s.isEmpty() example cannot be proved. The analysis is conservative: it may miss an opportunity, but never declares a binding that is not guaranteed.
  • Assignments and boolean combinations: rules for b = e instanceof T v, &&, ||, ! and ?: evaluate the guard once and declare the variable in the branches where it is bound. orPatternAssignment also adds the missing #negBinding in its else branch, which is reached exactly when the left operand failed to match, so the right operand sees the binding.
  • Visible-variable analysis: walks both if branches. Previously an //@ assert in the then branch could prevent class loading; the integration suite hit this with heap/BoyerMoore/BM.bm.key.
  • Example: key.ui/examples/Java/InstanceOfPattern covers the supported forms.

Secondary (auxiliary) changes

  • Generic rule guards: ifUnfold/ifElseUnfold reject binding guards (\not \isBindingExpr(#nse)). Otherwise both rule families match, and automation often picks the generic rule and drops the pattern declaration.
  • Flat branch splicing (#blockBody): matching a branch as a Statement is required for braceless ifs, but reinserting that statement directly adds a block level. #blockBody expands a block into its statements and passes a single statement through, so braced branches keep the original flat statement sequence.
  • Stable rule rendering: BindingExpressionCond and AbnormallyTerminatesCond now have stable toString() methods, and taclets.old.txt is updated. Without this, taclet output contains an identity hash and TestTacletEquality is non-deterministic.

Impact

  • Simple instanceof patterns, pattern if/if else, flow scoping, assignments and boolean combinations load and can be proved.
  • Programs without pattern bindings are unaffected: the generic if rules are restricted only for guards that bind pattern variables.
  • Pattern rewrites introduce a fresh boolean variable because the guard is evaluated once, and bindings carry the x == y assumption.
  • while/for/do pattern rules are not included; this is follow-up work.

Testing

  • TestPatternIfRules covers rule selection and the rewritten programs for binding and non-binding guards, braced and braceless branches, aborting versus completing then branches, flat splicing of multi-statement branches, and the absence of a spurious binding after a positive pattern.
  • AlwaysAbnormallyTerminatingAnalysisTest covers 32 JLS 14.22 cases: returns, throws, loops, switch, try/catch/finally, labeled statements, and constant short-circuit guards.
  • InstanceOfPatternFlowScopingTest proves the JLS 6.3.1.5 flow-scoping example end-to-end; the proof closes.
  • TestPatternAssignmentRules exercises all six pattern-assignment rules against the production javaRules.key and checks the resulting succedent modulo bound renaming.
  • BindingsOfExprTest is a parser regression test for using one program variable per pattern name; it ignores the additional identity assumption when collecting the generated declarations.
  • The testForNull, checkNotString and processNumber example contracts verify the #posBinding/#negBinding paths with the new assumption.
  • JmlAssertLoadingTest covers the visible-variable analysis walking both if branches.
  • JavaFeatureCoverageTest moves the instanceof pattern-matching example from coverage/rejected/ to coverage/supported/, as the feature now loads.
  • TestTacletEquality verifies the updated taclet oracle.
  • spotlessCheck and the Checker Framework nullness compile pass.

Plan and follow-up

  • Add AST and translation support
  • Add pattern-aware rules for if and if else
  • Make the rules parseable
  • Implement flow scoping as the \alwaysAbnormallyTerminates varcond
  • Add assignment and boolean-combination rules
  • Add the pattern-variable identity assumption
  • Add example
  • Add regression tests and keep CI green

Type of pull request

  • New feature (non-breaking change which adds functionality)
  • There are changes to the (Java) code
  • There are changes to the taclet rule base

Ensuring quality

  • I made sure that introduced/changed code is well documented (javadoc and inline comments).
  • I made sure that new/changed end-user features are well documented (https://github.com/KeYProject/key-docs).
  • I added new test case(s) for new functionality.
  • I have tested the feature as follows: the JLS flow-scoping example and the PR example contracts are proved with ProofStarter; the targeted Gradle test suites, spotlessCheck and the nullness compile pass.

Additional information and contact(s)

The contributions within this pull request are licensed under GPLv2, or (at your option) any later version, for inclusion in KeY.

@wadoon wadoon self-assigned this Aug 19, 2026
@wadoon wadoon added Java Parser Java Pull requests that update Java code Completeness labels Aug 19, 2026
@wadoon wadoon changed the title Weigl/instanceof Support for <expr> instanceof <Type> <var> Aug 19, 2026
@wadoon

wadoon commented Aug 21, 2026 •

Copy link
Copy Markdown
Member Author

State of PR 3976 zu instanceof:

  • added varcond `isBindingExpr(#expression, #posBinding, #negBindings) (true iff one of the bindings is not empty)
  • added varcond alwaysAbnormallyTerminates(#stmts) (true iff #stmts are never reaches the natural end, e.g., if(x) { assert false; }) under-approximation
  • added rule: ifElseUnfoldPattern, ifUnfoldPatternUnreachable, ifElseUnfoldPattern
  • General-Idea: if(#bnse) #slist1 else #slist2 ~~~~~> boolean #boolv; {#boolv = #bnse} if(#bnse) { #posBinding; #slist1} else {#negBinding; #slist2}
  • added rules for #boolv = #nse instanceof #T #id which does not match.

Todo:

  • forbid \ifElseUnfold for binding expressions

@wadoon wadoon added this to the v3.1.0 milestone Aug 21, 2026
@unp1

unp1 commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Hi,

  • added rules for #boolv = #nse instanceof #T #id which does not match.

The rule matches for me in the example below:

 /*@ normal_behavior
      @ requires obj != null;
      @ ensures \result instanceof String;
      @*/
    public static Object getString(Object obj) {
        return "ha";
    }

    /*@ normal_behavior
      @ requires obj != null;
      @ ensures \result;
      @*/
    public static boolean isString(Object obj) {
        boolean result = getString(obj) instanceof String id;
        return result;
    }

I added the example and a minor fix (replacewith of the instance_eval_id taclet)

@wadoon
wadoon force-pushed the weigl/instanceof branch 2 times, most recently from 2654e43 to 73183af Compare August 23, 2026 13:32
@wadoon

wadoon commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Currently waiting on #4025

@wadoon
wadoon changed the base branch from main to jmltk-1.0.1-snapshot November 12, 2026 19:47
@wadoon
wadoon added this pull request to stack #4034 November 12, 2026 19:47
Base automatically changed from jmltk-1.0.1-snapshot to main November 14, 2026 10:37
@wadoon
wadoon force-pushed the weigl/instanceof branch 2 times, most recently from ec3c18a to 31aeb43 Compare November 14, 2026 17:08
@wadoon

wadoon commented Nov 14, 2026 •

Copy link
Copy Markdown
Member Author

Code review (updated)

I re-reviewed the current head 58d9c84ac9 and re-ran the focused probes and tests. The previous findings are now mostly resolved.

Resolved

  • orPatternAssignment binding: the else branch has #negBinding(#nse), and orPatternAssignmentWithBoundVariable covers the right-hand use of the binding.
  • Pattern-rule shadowing: ifUnfold/ifElseUnfold carry \not \isBindingExpr(#nse); the example proofs select the pattern-aware rules.
  • AbnormallyTerminatesCond: implemented for both Statement and ImmutableArray instantiations; ifUnfoldPatternUnreachable fires.
  • Analysis false positives: loop guards, try/catch/finally, break/continue and labeled statements are handled; the test table covers them.
  • Test scaffolding: removed.
  • Compile break: head b1f28c2fd6 did not compile — ProgramTransformer had moved to the abstract getArguments() API, but ConstructorCall, EnhancedForElimination, ForToWhile, InitArrayCreation and UnwindLoop still called the removed schema-variable varargs constructor. Fixed in 58d9c84ac9; :key.core:compileTestJava passes.
  • instanceof_eval_id_or: fixed in 8d6d9e5c86; the rule now assigns !A to #v, so #nse is evaluated exactly when the negated instanceof is false. A direct regression test is still missing because the rule needs an assignment to an already-declared variable rather than a declaration.
  • Example: fixed in b1f28c2fd6; the calls to the commented-out compareIfBothStrings method are gone, the processNumber output comments match the implementation, the intended assertions are JML asserts, the unused static invariant is removed, and the README now names the actual taclets. javac accepts the file.
  • Display names: ifUnfoldPattern and ifUnfoldPatternUnreachable now have their own names.
  • getPatternVariable javadoc: no longer claims the result can be null.
  • AGENT.md: removed in 9f08d92987.

Remaining

  1. java5.key adds unused schema variables. #fresh, #then and #else are declared at java5.key:16,30 but no rule uses them. Remove them; the #fresh change also touches the #v0 declaration line unnecessarily.

  2. VMTacletMatcher.logDecision evaluates its varargs at every call site even when out == null. The Object... array and boxing are paid on the hot matching path. Guard call sites or pass lazy suppliers. Low.

  3. TacletMatchDebuggerExtension is registered with experimental = false, optional = true, so the developer dialog appears in every user's context menu. experimental = true seems more appropriate; matching also runs synchronously on the EDT. Low.

  4. conditionalPatternAssignment only matches a declaration (#t #v = …), not an assignment to an already-declared variable (v = c ? a : b). This remains a feature gap if both forms are intended.

  5. The new equality assumption has two limitations. It is silently skipped when the tested expression cannot be converted without an execution context (e.g. new …, this.field, method calls that need ec); for getString(obj) instanceof String id no id == getString(obj) assumption is generated. Also, every generated JmlAssert carries the parse-tree condition "true" and relies on the registered JmlStatementSpec; a fallback that loses the spec would print assume true. Document the restriction and add a test for the skip path, or use the equality text as the condition.

Tests

TestPatternIfRules, TestPatternAssignmentRules, BindingsOfExprTest, spotlessCheck and :key.core:compileTestJava pass locally. All eight example contracts (getString, isString, getStringLength, checkNotString, processNumber, getToStringLength, traditionalVsPattern, testForNull) close with ProofStarter; the example Java file compiles with javac. The remaining gaps are the untested instanceof_eval_id_or rule and the equality-assumption skip path.

@wadoon
wadoon marked this pull request as ready for review November 14, 2026 22:57
wadoon and others added 24 commits November 24, 2026 17:50
- BindingsOfExpr ignored the `positive` flag and always emitted the
  whenTrue bindings; the negative meta construct now uses whenFalse().
- Align the transformer names with the dispatched constructs (#posBinding /
  #negBinding instead of #posBindings / #negBindings).
- alwaysAbnormallyTerminates used BindingExpressionCond (copy-paste bug);
  use AbnormallyTerminatesCond. Drop the dangling BINDING_EXPRESSION_FULL
  reference from the registry.
- Add BindingsOfExprTest covering positive/negative bindings for instanceof
  patterns, negation, && / || and non-binding expressions.
The six tests load the production rules from javaRules.key (LDT +
javaRules profile) and apply each rule to a goal with a single rule in
the index, asserting the successor succedent modulo bound renaming.

Until the jmlparser supports the #posBinding/#negBinding meta-constructs
the rule base cannot be loaded, so the tests skip via an assumption that
detects that specific parse error.

Also fixes javaRules.key, which otherwise would not load once the parser
supports the meta-constructs:
- declare the schema variables #b and #nse3 used by the rules
- add the missing semicolon after #negBinding(#nse) in
  conditionalPatternAssignment
The \replacewith modality block of the notPatternAssignment rule was
missing the trailing '...' hole, so the whole production rule file
javaRules.key failed to parse under the JMLtk 1.0.1 generic
meta-construct grammar, which made loading the standard rule base
impossible and cascaded into hundreds of test failures.
ProgramTransformer.getArguments() became abstract with the JMLtk 1.0.1
grammar; implement it in the abstract parent BindingsOfExpr so the
pattern-binding meta-constructs (and hence :key.core:compileJava) work
again.

The pattern-assignment rule tests failed with "0 applications": the
matcher reaches only the first non-prefix statement of the goal, while
the tests placed the pattern assignment after a local declaration.
Rewrite each goal as a single active statement whose right-hand side is
self-contained (this for #se, a new expression for #nse), and run
tryToInstantiate so rules with a \new condition generate their fresh
boolean variable. Update the expected succedents to the real rule output.
The PR makes `x instanceof T v` parse and load, so the JavaFeatureCoverageTest
example for that feature is no longer rejected. Move it from
coverage/rejected/ to coverage/supported/ so the coverage test reflects the new
support (as the test itself instructs).
The pattern-variable support handles `if` statements explicitly in
collectLocalVariablesVisibleTo, but for an `if` with an `else` it only
recursed into the else-branch. An assertion in the then-branch was
therefore never found, the method returned null, and append() failed
with a NullPointerException while loading e.g.
heap/BoyerMoore/BM.bm.key (caught by testRunAllFunProofs).

Check the then-branch first (pattern variables are bound when the guard
is true) and the else-branch afterwards, and add a regression test that
loads a class with a JML assert in the then-branch of an if/else.
A use of a pattern variable in the scope of the instanceof pattern (for
example `s.length()` in `o instanceof String s && s.length() > 0`) was
converted to a fresh LocationVariable on every name resolution, so it
never referred to the variable the pattern binds. Declarations generated
by #posBinding/#negBinding therefore declared a different variable than
the one the branch read.

Cache the program variable per pattern name so that the declaring
InstanceOfExpr and all uses share one ProgramVariable.
- orPatternAssignment missed #negBinding in its else branch, which is
  entered exactly when the left operand failed to match, so the right
  operand could not see the pattern variable.
- ifUnfold/ifElseUnfold also matched binding guards and won over the
  pattern-aware rules in automation, dropping the pattern variable
  declarations. Guard them with \not \isBindingExpr(#nse).
- ifUnfoldPattern/ifElseUnfoldPattern only matched braced branches;
  match a Statement instead so that braceless ifs keep a rule.

Regression tests cover the rewritten programs and the rule selection.
ifUnfoldPatternUnreachable was dead code: AbnormallyTerminatesCond never
evaluated the analysis, and AlwaysAbnormallyTerminatingAnalysis had
several wrong answers (loops with non-constant guards were treated as
aborting, try/catch and break/continue handling was broken).

- Reimplement the analysis around JLS 14.22 "cannot complete normally":
  sequence reachability, return/throw/break/continue, constant guards,
  loop breaks, switch default/cases, try/catch/finally and labeled
  statements. The analysis stays conservative with respect to normal
  completion.
- Implement AbnormallyTerminatesCond, including negation, for both a
  single Statement and an ImmutableArray of statements.
- Guard ifUnfoldPattern with \not \alwaysAbnormallyTerminates(#s0) and
  let ifUnfoldPatternUnreachable match #s0 instead of a braced list. This
  makes automation select exactly one rule and declares the pattern
  variable after the if when the then branch cannot complete normally.
- Give the two binding conditions stable toString implementations; the
  new varcond would otherwise print an identity hash and break the
  taclet oracle.
- Rewrite the analysis table, add rule-selection and rewrite tests, and
  prove the JLS 6.3.1.5 flow-scoping example end-to-end.
Matching a branch with a Statement schema variable (#s0) binds the whole
branch, including a braced block. Inserting that binding directly into the
replacement added an extra block level and changed the shape of the
rewritten program compared to the previous #slist splice.

Add a #blockBody meta-construct that expands a block into its statements and
returns any other statement unchanged. Use it in the pattern-if
replacements so braced branches keep their flat statement sequence while
braceless branches are still supported.

The new tests cover multi-statement braced branches for both
ifUnfoldPattern and ifUnfoldPatternUnreachable.
#posBinding/#negBinding now emit a JML assume statement `x == y` after
declaring the pattern variable `y` for `x instanceof T y`. Together with
the instanceof guard this makes the pattern variable's non-nullness
available to the branch.

BindingsOfExprTest now ignores the additional assumption when collecting
the generated declarations.
Use \invariant_for(obj) instead of true so the contract exposes the
invariant needed by the method call in the example.
The JavaRedux stubs for Double and Long do not declare intValue(), so the
example used to abort while resolving that method. Use the pattern binding
for a non-null assertion in those branches and return a constant instead.

Require \invariant_for(obj) so the Integer.intValue() receiver
precondition is available, and use ensures true because intValue() may be
negative. The processNumber proof now closes.
The repository already has AGENTS.md; this second agent-guidance file was
added by the feature branch and is unrelated to the instanceof pattern
support.
The right-hand side of instanceof_eval_id_or is `!A || nse`; the rule
assigned `A` to #v and evaluated #nse when A was false, which is the
opposite of Java's short-circuit behaviour. Assign !A instead so #nse is
evaluated exactly when the negated instanceof is false.

Also give ifUnfoldPattern and ifUnfoldPatternUnreachable their own display
names, and drop the stale "or null" from getPatternVariable()'s javadoc.
Remove the calls to the commented-out compareIfBothStrings method, update
the processNumber output comments, turn the intended assertions into JML
asserts, and drop the unused static invariant. Update the README's taclet
names and remove the commented-out example section.
ProgramTransformer no longer has the schema-variable varargs constructor;
its getArguments() is abstract and each transformer supplies its own
arguments. Update the remaining transformers that still passed schema
variables to super, so key.core compiles again.
Add the missing class, record and method documentation: what the
visitor computes (JLS 6.3.1.1-6.3.1.7 flow scoping), how the Bindings
result is meant to be consumed by #posBinding/#negBinding, and the
parameters of binds/analyze/toStatements.
Review feedback: the four instanceof_eval_id* rules (assignment form b = e
instanceof T v) had no test coverage, and the two rule-test classes silently
skipped if javaRules.key failed to load because of the jmlparser
#posBinding/#negBinding gap. The parser supports the meta constructs now, so a
load failure is a regression and should fail the test instead of skipping it.

Adds one test per rule: a non-simple and a simple subject, a right-operand
binding under &&, and a negated left operand under ||. The assignment-form
rules need the assignment to be the first active statement, so the tests use
program variables declared in a dedicated key file.
…4.22

Review feedback, two cases:

- An assert statement can complete normally when it is reachable, because
  assertions may be disabled at runtime; the condition is irrelevant. The
  analysis classified assert false as never completing normally, which let
  ifUnfoldPatternUnreachable introduce a negative binding (and a cast) on a
  path that completes normally. Treat Assert as able to complete normally and
  update the test expectations.

- A do statement can complete normally via a reachable continue that targets
  it when the condition is not the constant true (JLS 14.22). Add that clause
  (OuterBreakContinueAndReturnCollector already collects the continues) and
  add the corresponding test cases.

Also avoid the LogicServices -> Services cast in AbnormallyTerminatesCond: if
the matcher only provides LogicServices the analysis cannot run, so report the
condition as not satisfied instead of throwing a ClassCastException.
Review feedback: #fresh, #then and #else are not referenced by java5.key or
javaRules.key.
Review feedback: the 263-line GUI debugging extension is unrelated to pattern
matching and would be better as a separate PR. Removing it also removes the
PrintWriter/logDecision machinery from VMTacletMatcher, whose varargs arguments
were allocated on every match attempt on the hot path even when logging was
disabled.
@wadoon

wadoon commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Thanks for the review. Addressed in the updated branch (stack re-cascaded onto the current main):

1. Binding declarations re-evaluate the tested expression (high) — fixed by the stacked PR #4045, which replaces #posBinding/#negBinding with the hoisting/assignment rules. A non-simple subject is evaluated once by instanceofPatternAssignmentNSE (#typeof(#nse) #v0 = #nse;) and the binding assigns from #v0; a simple subject needs no temporary. PatternSoundnessTest#subjectIsEvaluatedOnce pins the a[i++] case. If #3976 should be sound standalone rather than together with #4045, the subject-temporary rule would need to be backported here — that duplicates #4045, so I left it in the upper PR; say the word if you prefer the backport.

2. AlwaysAbnormallyTerminatingAnalysis and JLS 14.22 — fixed:

  • Assert now counts as able to complete normally (assertions may be disabled; the condition is irrelevant), and the two test expectations for assert false / assert x && false are corrected.
  • do statements now complete normally via a reachable continue targeting them when the condition is not the constant true; OuterBreakContinueAndReturnCollector was already available for this. Added do { continue; } while (false);, the conditional variant, and the while (true) negative case to the CSV test.
  • Note that in Replace pattern bindings with hoisting and assignment taclets #4045 ifUnfoldPatternUnreachable no longer exists, but the restored analysis and test now match the JLS behavior.

3. Assignment rules / unused schema variables — added one test per instanceof_eval_id* rule: instanceof_eval_id (non-simple subject), instanceof_eval_id_simple, instanceof_eval_id_and (&& right-operand binding) and instanceof_eval_id_or (negated left operand). The assignment form needs the assignment to be the first active statement, so the tests use program variables from a dedicated key file. Removed the unused #fresh, #then and #else from java5.key.

4. logDecision allocation on the hot path — the PrintWriter/logDecision machinery is removed together with the debugger extension, so VMTacletMatcher is back to its main version and no varargs are allocated during matching.

5. Minor

  • TacletMatchDebuggerExtension (263 lines of GUI tooling) is removed from this PR; it can be proposed separately.
  • TestPatternIfRules/TestPatternAssignmentRules no longer skip when javaRules.key fails to load because of the #posBinding/#negBinding parser gap — a load failure now fails the test.
  • AbnormallyTerminatesCond no longer casts LogicServices to Services; if the matcher provides only LogicServices it reports the condition as not satisfied instead of throwing ClassCastException.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Completeness Java Parser Java Pull requests that update Java code Review Request Waiting for review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants