Skip to content

Patterns: where guards, and where restrictions in proofs - #2822

Draft
Negabinary wants to merge 2 commits into
prover-mainfrom
where-patterns
Draft

Negabinary wants to merge 2 commits into
prover-mainfrom
where-patterns

Conversation

@Negabinary

@Negabinary Negabinary commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #2823 (the prover). Review that one first; this PR's diff is against its branch.

Closes #832 ("Boolean pattern guards").

A pattern p where g matches a value when p matches it and then the boolean g is true. It can appear wherever a pattern can, at any depth:

case xs | h :: t where h > 0 => h | _ => 0 end
case v | (x where x > 0, y where y > x) => x + y | _ => 0 end
fun x where x != 0 -> 100 / x
let n where n >= 0 = f(3) in n
forall x where x != 0 -> x / x == 1

Semantics. Matching is structural and runs left to right. When it reaches a guard, having matched everything to the guard's left with bindings σ, the case steps to an ordinary if:

if g[σ] then
  case (v2, ...) | (p2, ...) => body[σ] | _ => case v | later arms end end
else case v | later arms end

where (v2, ...) are the parts of the value not yet matched and (p2, ...) the rest of the arm's pattern; a guard further right is handled when that inner case steps. Guards therefore run interleaved with matching, in the order written: a guard runs after everything to its left has matched and before anything to its right is looked at. A false guard falls through to the later arms; a guard that is indeterminate leaves the if stuck.

fun p where g applied to an argument, and let p where g = e, step the same way, with one difference: the failure branch is an error, DynamicErrorHole(<the application or let>, UnsatisfiedWhere): "The value doesn't satisfy the pattern's where condition". After a passing guard, the rest of the pattern is matched by the same inner case as above, whose second arm (the rest of the pattern without its guards) leads to that error:

if g then
  case (v2, ...) | (p2, ...) => body | <(p2, ...) without guards> => error end
else error

So a guard that fails anywhere in the pattern reports one error around the original application or let, and a structural mismatch matches neither arm and stays stuck, as it does with no guards. The step into the error is final, from either the if or the inner case, so the error hole is not evaluated again.

Scope. A guard sees everything bound to its left in the enclosing pattern, its own sub-pattern included, plus the enclosing scope: in (y, x where x > y) the guard's y is the tuple's first component. The statics type g against Bool in that context (a non-Bool guard is a marked type error), and a variable used only in a guard counts as used. This differs from Successor ML's nested guards (p if e) (Reppy and Zahir, "Compiling Successor ML Pattern Guards", ML Workshop 2019), where a guard sees only its own sub-pattern's bindings and the enclosing scope. Their order is the same as ours: left to right, each guard checked as soon as its sub-pattern has matched.

Precedence. where is looser than every operator that can appear on either side (h :: t where a && b guards the whole cons with a && b) and tighter than ,, ->, => and =, so (x where x > 0, y) guards x alone. Parenthesize a tuple to guard it as a whole. Both the editor parser and the menhir parser read it this way, and the printer round-trips it.

Coverage. A guard can fail, so a case row with a guard anywhere in its pattern neither covers values nor makes later rows redundant. In fun and let a guard narrows the domain and is ignored by coverage.

Why guards are part of evaluation, not a separate run. The matcher evaluates nothing: it returns the bindings so far, the guard and the rest of the pattern, and the Match, Ap and Let rules build the if. So a guard's steps count against the program's step limit, probes inside a guard record (nested ones included), the stepper shows the guard as an ordinary if and case, and incremental evaluation sees it like any other subterm. Everything stays printable.

Known conservative gap: alpha-equivalence compares a guard under its own sub-pattern's renamings but not its left siblings', so two patterns that differ only in the names of a sibling a guard refers to compare unequal.

Pattern probes record once matching reaches their sub-pattern, so a probe on a guarded arm's pattern can record a value even when the guard then fails.

Also: ExplainThis docs for fun p where g and guarded patterns; the agent tree utilities and exercise syntax checks look through where.

In proofs. A where is a restriction the prover can use:

  • forall x where g -> P: in the proof, g is a hypothesis named where. revert where puts it back into the goal, and generalize recovers a binder's restriction instead of dropping it. A theorem with a restricted binder, cited as a rewrite rule, adds the instantiated guard as a condition.
  • A guarded case arm: its guard is a fact in that case, under cases and induction alike (Induction.where_facts), and a guarded row doesn't count toward exhaustiveness. In an induction case, a where fact that mentions the scrutinee leaves scope like any other fact.
  • fun p where g is a contract. The body's conditions are checked against g once, at the definition, and each call creates the obligation g[p := arg] in the caller's terms, never the body's.
  • In the stepper, an open side condition on a statement's variable can be added to the statement ("Add to statement" writes forall z where z != 0 ->). A function body's open condition shows as a ƒ circle on the theorem's header, with "Add to contract", which writes fun w where <condition> ->.

Status

Draft. Locally: the quick suite passes (5363 tests), as do MenhirCorpus, FastParseCorpus and the release-profile warnings check (make ci-check).

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.92192% with 187 lines in your changes missing coverage. Please review.
✅ Project coverage is 51.53%. Comparing base (498d6d1) to head (9e5fb4b).

Files with missing lines Patch % Lines
src/web/app/editors/result/Theorems.re 34.00% 33 Missing ⚠️
src/web/app/editors/stepper/Obligations.re 70.52% 28 Missing ⚠️
src/language/dynamics/transition/PatternMatch.re 70.83% 21 Missing ⚠️
src/language/proof/Induction.re 53.48% 20 Missing ⚠️
src/web/app/explainthis/ExplainThis.re 0.00% 12 Missing ⚠️
src/language/term/Pat.re 80.00% 8 Missing ⚠️
src/language/proof/ProofCheck.re 90.66% 7 Missing ⚠️
src/language/term/Abbreviate.re 0.00% 7 Missing ⚠️
src/menhirParser/AST.re 12.50% 7 Missing ⚠️
src/haz3lcore/tiles/Segment.re 63.63% 4 Missing ⚠️
... and 19 more
Additional details and impacted files
@@               Coverage Diff               @@
##           prover-main    #2822      +/-   ##
===============================================
+ Coverage        51.36%   51.53%   +0.16%     
===============================================
  Files              510      511       +1     
  Lines            62625    63169     +544     
===============================================
+ Hits             32169    32554     +385     
- Misses           30456    30615     +159     
Files with missing lines Coverage Δ
src/haz3lcore/lang/Form.re 94.54% <100.00%> (+0.01%) ⬆️
src/haz3lcore/lang/MakeTerm.re 81.91% <100.00%> (+0.10%) ⬆️
src/haz3lcore/lang/Precedence.re 96.22% <ø> (ø)
src/haz3lcore/pretty/ExpToSegment.re 70.04% <100.00%> (+0.12%) ⬆️
src/language/dynamics/Evaluator.re 91.73% <100.00%> (ø)
src/language/dynamics/Substitution.re 86.71% <100.00%> (+0.18%) ⬆️
src/language/grammar/FormId.re 84.13% <100.00%> (+0.11%) ⬆️
src/language/grammar/Token.re 87.69% <100.00%> (+0.09%) ⬆️
src/language/proof/Occurrence.re 74.59% <ø> (ø)
src/language/proof/ProofRule.re 53.84% <100.00%> (+1.99%) ⬆️
... and 39 more

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Negabinary
Negabinary added this pull request to stack #2824 November 14, 2026 02:14
@Negabinary
Negabinary removed this pull request from stack #2824 November 16, 2026 20:19
@Negabinary
Negabinary changed the base branch from dev to prover-main November 16, 2026 20:19
@Negabinary
Negabinary added this pull request to stack #2826 November 16, 2026 20:19
@Negabinary Negabinary changed the title Patterns: where guards, evaluated as part of the program Patterns: where guards, and where restrictions in proofs Nov 16, 2026
@Negabinary
Negabinary force-pushed the where-patterns branch 2 times, most recently from 11e68af to 4f5a76b Compare November 18, 2026 01:53
@Negabinary
Negabinary force-pushed the where-patterns branch 2 times, most recently from 5f7b4c9 to a1efff5 Compare November 20, 2026 18:08
@Negabinary
Negabinary force-pushed the where-patterns branch 2 times, most recently from 0c8eaf0 to fbc7233 Compare November 20, 2026 20:38
@Negabinary
Negabinary removed this pull request from stack #2826 November 20, 2026 20:39
@Negabinary
Negabinary added this pull request to stack #2852 November 20, 2026 20:39
@Negabinary
Negabinary removed this pull request from stack #2852 November 20, 2026 22:09
@Negabinary
Negabinary added this pull request to stack #2854 November 20, 2026 22:10
Negabinary and others added 2 commits November 20, 2026 17:10
Adds a prover to Hazel. A theorem's proof is checked as it is written,
and a stepper shows the proof as a chain of goals and writes steps for
you.

Theorems. `theorem t = <statement> proof <proof> in e`. The statement's
outer `forall`s are introduced automatically. A theorem is proven,
refuted or incomplete.

The proof language:
- `step`: one evaluation step at the root. Where evaluation has none,
  a function or `let` at the root takes its argument as it is (beta at
  any argument), so `from inc(2 + 3) do step end` gives `2 + 3 + 1`;
- `rewrite h end` and `rewrite <- h end`: rewrite with a fact, theorem
  or axiom, either way round;
- `algebra e end`: an algebraic rewrite, checked with Algebrite;
- `from p at n do <steps> end`: run steps on the nth occurrence of a
  subterm (`at 1` is the default);
- `forall`, `funext`, `revert`, `generalize` and `alias`;
- `assume P =>` on a goal `P ==> Q`, and `have P proof <proof> =>` on
  any goal. Their facts are named `assume` and `have`, or `h` when
  written `assume h = P` or `have h = P`. `assume` on any other goal is
  refused;
- `cases e`: a split on any expression. Each case has the case equation
  `e == pat`, named `case_eq`, and no inductive hypothesis. A nested
  split that needs the outer equation names it with `alias`;
- `induction e`: each case has inductive hypotheses `ih_<var>` and no
  case equation. A computed `e` is generalized first, and in each case
  the facts that mention the scrutinee leave scope. Nothing gives both: to
  carry a fact into the IH, `revert` it first.

Proof words are keywords only in proof syntax. Elsewhere both parsers
read them as ordinary names, so a program can still bind `from`, `at`,
`have` or `induction`; only `theorem` and `forall` are reserved.

The checker. `ProofCheck` records, for each proof node, its incoming and
outgoing goal, its marks, its obligations and its scope (`ProofMap`).
Goals are kept as written: a definition is unfolded only where a step
needs to look inside it.

Checking runs in the evaluation worker, as part of evaluation. Each
theorem's check is cached and reused while the theorem, the theorems it
can cite, their verdicts and the definitions it names are unchanged. The
checker reads the statics through `ProofStatics`: the full statics map in
the CLI and tests, and in the worker the `EvalInfo` sent with each
request, which carries types, coverage and theorem namespaces only for a
program that has theorems. A program without theorems sends and computes
nothing extra.

Algebra. The worker has its own Algebrite, loaded the first time a proof
has an `algebra` step. A step is verified when it is Int arithmetic (`+`,
`-`, `*`, powers) over literals and Int-typed variables, or Nat
arithmetic (`+`, `*`, powers) over Nat-typed ones, checked as integers.
Anything else, such as division, Nat's `monus` or a function call, stays
an open condition. Two built-in rules state the Nat facts algebra can't
check: `nat_succ_ne_zero` (`(m + 1 == 0) == false`) and `nat_add_sub`
(`monus(a + k, k) == a`).

Side conditions. Definedness (`x / y` needs `y != 0`) and rule premises
become obligations. Facts in scope or evaluation discharge them;
otherwise they stay open. Evaluating a closed condition stops at its
first error.

Citations. Theorems are checked in program order, each knowing the
verdicts of those before it. Citing a refuted theorem is an error on
that step. Citing an unfinished one is allowed: it is an assumption, not
a gap.

Status. A theorem reads:
- proven: finished, relying on nothing unproven;
- proven*: finished, but citing theorems that aren't; the star's tooltip
  names them;
- incomplete: a hole, or an open condition other than a citation, with
  a quiet count of the open conditions ("incomplete · 1 open"). Clicking
  the count scrolls to the first one;
- refuted.

An exercise's score counts proven theorems only, since a student could
cite an unproven lemma that states the theorem itself.

Equality. `refl` needs `==` to be reflexive, so the polymorphic `==`
treats two NaNs as equal. The Float-only `==.` stays IEEE.

The stepper is a projection of the proof. Each line between two goals is
a step, and structured steps (induction, `forall`, `have`, focus) draw as
blocks.
- Each side condition is a circle on its step's line. An open one is red,
  and its exits, "Prove here" (a `have`) and "Split on it" (a `cases`),
  patch the proof.
- The main interaction is a write box after an unfinished proof, with
  three tabs:
  - Write: type the goal you want next, and a bounded search finds steps
    that reach it. An empty box offers the next step or reflexivity,
    which Tab takes. With part of the goal selected, the offer is the
    outermost step in it, and the box rewrites just that part. Typing a
    rule's name lists its uses.
  - Step: green highlights on what can step. A click writes a focused
    step at that node.
  - Strategy: one button per structured step, each writing its form
    with holes for the user to fill.
- A block's header names the fact it introduces. What a focus works on
  shows as the underline in the goal above, not in the header.
- Every offer is checked before it's shown.
- Focus selectors are generalized with `$e`, so proofs survive edits.
- Stepper edits keep the user's comments and layout.

The documentation slides get a Prover section: short slides on
theorems, the stepper, lemmas, induction and side conditions, and one
whose proofs use every step form. Clicking a step shows its docs entry,
titled by what the user types. ProverDocs checks each theorem on the
slides has the status its text gives.

Editor changes outside the prover:
- The holes completion adds inside a tile, such as the proof of a
  half-typed `theorem t = 1`, keep their ids across edits, so the stepper
  keeps its state while the statement is typed.
- Folding a selection that isn't a whole term, such as a `let ... in`
  header without its body, is refused. It used to crash the editor.
- A toggle that is on shows the accent color. The shared toggle's on and
  off tracks were two shades of one hue, so an off toggle looked on.

Known soundness gaps are pinned as tests in
`test/evaluator/Test_ProverKnownBugs.re`. Each asserts today's wrong
behaviour, so a fix shows up as a failing pin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Closes #832 ("Boolean pattern guards").

A pattern `p where g` matches a value when `p` matches it and then the
boolean `g` is true. It can appear wherever a pattern can, at any depth:

    case xs | h :: t where h > 0 => h | _ => 0 end
    case v | (x where x > 0, y where y > x) => x + y | _ => 0 end
    fun x where x != 0 -> 100 / x
    let n where n >= 0 = f(3) in n
    forall x where x != 0 -> x / x == 1

Semantics. Matching is structural and runs left to right. When it
reaches a guard, having matched everything to the guard's left with
bindings σ, the `case` steps to an ordinary `if`:

    if g[σ] then
      case (v2, ...) | (p2, ...) => body[σ] | _ => case v | later arms end end
    else case v | later arms end

where `(v2, ...)` are the parts of the value not yet matched and
`(p2, ...)` the rest of the arm's pattern; a guard further right is
handled when that inner `case` steps. Guards therefore run interleaved
with matching, in the order written: a guard runs after everything to its
left has matched and before anything to its right is looked at. A false
guard falls through to the later arms; a guard that is indeterminate
leaves the `if` stuck.

`fun p where g` applied to an argument, and `let p where g = e`, step the
same way, with one difference: the failure branch is an error,
`DynamicErrorHole(<the application or let>, UnsatisfiedWhere)`: "The
value doesn't satisfy the pattern's `where` condition". After a passing
guard, the rest of the pattern is matched by the same inner `case` as
above, whose second arm (the rest of the pattern without its guards)
leads to that error:

    if g then
      case (v2, ...) | (p2, ...) => body | <(p2, ...) without guards> => error end
    else error

So a guard that fails anywhere in the pattern reports one error around the
original application or `let`, and a structural mismatch matches neither
arm and stays stuck, as it does with no guards. The step into the error is
final, from either the `if` or the inner `case`, so the error hole is not
evaluated again.

Scope. A guard sees everything bound to its left in the enclosing
pattern, its own sub-pattern included, plus the enclosing scope:
in `(y, x where x > y)` the guard's `y` is the tuple's first component.
The statics type `g` against Bool in that context (a non-Bool guard is a
marked type error), and a variable used only in a guard counts as used.
This differs from Successor ML's nested guards `(p if e)` (Reppy and
Zahir, "Compiling Successor ML Pattern Guards", ML Workshop 2019), where
a guard sees only its own sub-pattern's bindings and the enclosing scope.
Their order is the same as ours: left to right, each guard checked as
soon as its sub-pattern has matched.

Precedence. `where` is looser than every operator that can appear on
either side (`h :: t where a && b` guards the whole cons with `a && b`)
and tighter than `,`, `->`, `=>` and `=`, so `(x where x > 0, y)` guards
`x` alone. Parenthesize a tuple to guard it as a whole. Both the editor
parser and the menhir parser read it this way, and the printer
round-trips it.

Coverage. A guard can fail, so a `case` row with a guard anywhere in its
pattern neither covers values nor makes later rows redundant. In `fun` and
`let` a guard narrows the domain and is ignored by coverage.

Why guards are part of evaluation, not a separate run. The matcher
evaluates nothing: it returns the bindings so far, the guard and the rest
of the pattern, and the `Match`, `Ap` and `Let` rules build the `if`. So
a guard's steps count against the program's step limit, probes inside a
guard record (nested ones included), the stepper shows the guard as an
ordinary `if` and `case`, and incremental evaluation sees it like any
other subterm. Everything stays printable.

Known conservative gap: alpha-equivalence compares a guard under its own
sub-pattern's renamings but not its left siblings', so two patterns that
differ only in the names of a sibling a guard refers to compare unequal.

Pattern probes record once matching reaches their sub-pattern, so a probe
on a guarded arm's pattern can record a value even when the guard then
fails.

Also: ExplainThis docs for `fun p where g` and guarded patterns; the
agent tree utilities and exercise syntax checks look through `where`.

In proofs. A `where` is a restriction the prover can use:
- `forall x where g -> P`: in the proof, `g` is a hypothesis named
  `where`. `revert where` puts it back into the goal, and `generalize`
  recovers a binder's restriction instead of dropping it. A theorem with
  a restricted binder, cited as a rewrite rule, adds the instantiated
  guard as a condition.
- A guarded case arm: its guard is a fact in that case, under `cases`
  and `induction` alike (`Induction.where_facts`), and a guarded row
  doesn't count toward exhaustiveness. In an induction case, a `where`
  fact that mentions the scrutinee leaves scope like any other fact.
- `fun p where g` is a contract. The body's conditions are checked
  against `g` once, at the definition, and each call creates the
  obligation `g[p := arg]` in the caller's terms, never the body's.
- In the stepper, an open side condition on a statement's variable can be
  added to the statement ("Add to statement" writes `forall z where
  z != 0 ->`). A function body's open condition shows as a ƒ circle on
  the theorem's header, with "Add to contract", which writes `fun w where
  <condition> ->`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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.

Boolean pattern guards

1 participant