Repository navigation
Conversation
e339388 to
40adc5d
Compare
|
State of PR 3976 zu
Todo:
|
42b0b3b to
c8021b3
Compare
|
Hi,
The rule matches for me in the example below: I added the example and a minor fix (replacewith of the |
2654e43 to
73183af
Compare
73183af to
27c3854
Compare
27c3854 to
52c8108
Compare
52c8108 to
f044e20
Compare
|
Currently waiting on #4025 |
9e06a57 to
7f6a329
Compare
ec3c18a to
31aeb43
Compare
Code review (updated)I re-reviewed the current head Resolved
Remaining
Tests
|
360ef64 to
9f08d92
Compare
- 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.
97bc649 to
5a63c60
Compare
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.
|
Thanks for the review. Addressed in the updated branch (stack re-cascaded onto the current 1. Binding declarations re-evaluate the tested expression (high) — fixed by the stacked PR #4045, which replaces 2.
3. Assignment rules / unused schema variables — added one test per 4. 5. Minor
|
Intended Change
Add support for Java 16
instanceofpatterns of the form<expr> instanceof <Type> <var>, including the JLS 6.3.1.5 flow-scoping rules for the pattern variable. Code such asnow loads and can be proved in KeY.
Primary changes
InstanceofPatternnode, translated during loading. Each pattern name maps to oneProgramVariable, shared by the declaration and all uses in its scope.ifrules:ifUnfoldPattern,ifElseUnfoldPatternandifUnfoldPatternUnreachableevaluate the guard once and introduce#posBinding/#negBindingin the branches where the binding is guaranteed. This is needed because the genericifUnfold/ifElseUnfoldrules do not know about pattern bindings and would drop the declaration. Braced and braceless branches are both supported.yforx instanceof T y,#posBinding/#negBindingemit a JMLassume x == y. This makes the identity of the bound variable with the tested reference explicit in the branch; non-nullness follows from theinstanceofguard. The assumption is omitted when the tested expression cannot be converted without an execution context.if:AlwaysAbnormallyTerminatingAnalysisand the\alwaysAbnormallyTerminatesvarcond implement JLS 14.22. If the then branch cannot complete normally,ifUnfoldPatternUnreachabledeclares the pattern variable after theif. Without this, legal code such as thes.isEmpty()example cannot be proved. The analysis is conservative: it may miss an opportunity, but never declares a binding that is not guaranteed.b = e instanceof T v,&&,||,!and?:evaluate the guard once and declare the variable in the branches where it is bound.orPatternAssignmentalso adds the missing#negBindingin its else branch, which is reached exactly when the left operand failed to match, so the right operand sees the binding.ifbranches. Previously an//@ assertin the then branch could prevent class loading; the integration suite hit this withheap/BoyerMoore/BM.bm.key.key.ui/examples/Java/InstanceOfPatterncovers the supported forms.Secondary (auxiliary) changes
ifUnfold/ifElseUnfoldreject binding guards (\not \isBindingExpr(#nse)). Otherwise both rule families match, and automation often picks the generic rule and drops the pattern declaration.#blockBody): matching a branch as aStatementis required for bracelessifs, but reinserting that statement directly adds a block level.#blockBodyexpands a block into its statements and passes a single statement through, so braced branches keep the original flat statement sequence.BindingExpressionCondandAbnormallyTerminatesCondnow have stabletoString()methods, andtaclets.old.txtis updated. Without this, taclet output contains an identity hash andTestTacletEqualityis non-deterministic.Impact
instanceofpatterns, patternif/if else, flow scoping, assignments and boolean combinations load and can be proved.ifrules are restricted only for guards that bind pattern variables.x == yassumption.while/for/dopattern rules are not included; this is follow-up work.Testing
TestPatternIfRulescovers 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.AlwaysAbnormallyTerminatingAnalysisTestcovers 32 JLS 14.22 cases: returns, throws, loops,switch,try/catch/finally, labeled statements, and constant short-circuit guards.InstanceOfPatternFlowScopingTestproves the JLS 6.3.1.5 flow-scoping example end-to-end; the proof closes.TestPatternAssignmentRulesexercises all six pattern-assignment rules against the productionjavaRules.keyand checks the resulting succedent modulo bound renaming.BindingsOfExprTestis a parser regression test for using one program variable per pattern name; it ignores the additional identity assumption when collecting the generated declarations.testForNull,checkNotStringandprocessNumberexample contracts verify the#posBinding/#negBindingpaths with the new assumption.JmlAssertLoadingTestcovers the visible-variable analysis walking bothifbranches.JavaFeatureCoverageTestmoves theinstanceofpattern-matching example fromcoverage/rejected/tocoverage/supported/, as the feature now loads.TestTacletEqualityverifies the updated taclet oracle.spotlessCheckand the Checker Framework nullness compile pass.Plan and follow-up
ifandif else\alwaysAbnormallyTerminatesvarcondType of pull request
Ensuring quality
ProofStarter; the targeted Gradle test suites,spotlessCheckand 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.