perf: check `match` equations on many `String` literals faster in the kernel This PR makes the generation of equations faster for a `match` with many `String` literals. The `big_match_string` benchmark with 128 alternatives is about 37% faster (#16313). The equation of alternative `i` has to show that the `i-1` earlier literals are different from it, and its proof walked the chain of tests of the matcher again. For a matcher with at least 32 `String` literals, two auxiliary theorems are now generated once. The first one states a numeric code for each literal, so a disequality between two literals is a comparison of two numerals. The second one states what the `match` is equal to in each case, so each equation is a projection of it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/src/Init/Core.lean b/src/Init/Core.lean index d934df1..85cbfb5 100644 --- a/src/Init/Core.lean +++ b/src/Init/Core.lean
@@ -1237,6 +1237,28 @@ | isTrue hc => absurd hc hnc | isFalse hnc => h hnc +/-- +Auxiliary theorem for proving the equations of `match` expressions with value patterns. + +The match compiler generates a chain of tests +``` +dite (b = a₁) (Eq.ndrec_symm m₁) fun _ => dite (b = a₂) (Eq.ndrec_symm m₂) fun _ => ... e +``` +for the alternatives with value patterns `a₁`, `a₂`, ... This theorem is used to prove, with a +single traversal of the chain, a theorem that states what the chain `r` is equal to in each case: +``` +(b = a₁ → r ≍ m₁) ∧ (¬ b = a₁ → (b = a₂ → r ≍ m₂) ∧ (¬ b = a₂ → ... r ≍ e)) +``` +`q` is the statement for the remaining tests, and `h` its proof. +-/ +theorem dite_ndrec_symm_cases {α : Sort u} {a b : α} {inst : Decidable (b = a)} {motive : α → Sort v} + {m : motive a} {e : ¬ b = a → motive b} {r : motive b} {q : Prop} + (h : (hn : ¬ b = a) → r = e hn → q) : + r = dite (b = a) (Eq.ndrec_symm m) e → (b = a → r ≍ m) ∧ (¬ b = a → q) := + fun hr => match inst, hr with + | isTrue hc, hr => ⟨fun _ => by subst hc; subst hr; exact HEq.rfl, fun hn => absurd hc hn⟩ + | isFalse hn, hr => ⟨fun hc => absurd hc hn, fun hn' => h hn' hr⟩ + @[deprecated dite_eq_right (since := "2026-07-21")] theorem dif_neg {c : Prop} {h : Decidable c} (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬c → α} : dite c t e = e hnc := dite_eq_right hnc
diff --git a/src/Init/Data/String/Basic.lean b/src/Init/Data/String/Basic.lean index 0384a72..51e0535 100644 --- a/src/Init/Data/String/Basic.lean +++ b/src/Init/Data/String/Basic.lean
@@ -392,6 +392,59 @@ rw [sameCharAt_self] at h contradiction +/-- +Auxiliary function for proving that two `String` literals are different. See +`String.Internal.ne_of_code`. + +`codeOfList l` is a natural number that identifies the list of characters `l`: two different lists +have different codes. It is the value of the numeral in base `2^21` whose digits are +`c.toNat + 1` for the characters `c` of `l`, the first character being the least significant +digit. No digit is zero, so lists with different lengths also have different codes. +This property is not needed for soundness, and is not proved: `String.Internal.ne_of_code` holds +for any function, and the kernel rejects its proof if the two codes are equal. + +It is defined using a recursor to minimize the number of steps the kernel has to perform when +evaluating it. +-/ +@[expose] noncomputable def String.Internal.codeOfList (l : List Char) : Nat := + List.rec (motive := fun _ => Nat) 0 + (fun c _ n => Nat.add (Nat.add c.toNat 1) (Nat.mul 2097152 n)) l + +/-- +Auxiliary function for proving that two `String` literals are different. See +`String.Internal.ne_of_code`. + +`code s` is a natural number that identifies the string `s`, see `codeOfList`. +The kernel cannot evaluate `code s` efficiently when `s` is a literal. `String.Internal.code_ofList` +is used instead. +-/ +noncomputable def String.Internal.code (s : String) : Nat := + codeOfList s.toList + +/-- +Auxiliary theorem for computing the code of a `String` literal. A literal is definitionally equal +to `String.ofList l`, where `l` is the list of its characters, and `h` is `Eq.refl n`. +-/ +theorem String.Internal.code_ofList (l : List Char) (n : Nat) (h : codeOfList l = n) : + code (String.ofList l) = n := by + simp [code, h] + +/-- +Auxiliary theorem for proving that two `String` literals are different: their codes `n₁` and `n₂` +are different numerals, and `h` is `Eq.refl false`. + +The kernel evaluates `Nat.beq n₁ n₂` using arbitrary precision arithmetic, so the cost of this +proof does not depend on the two literals, once their codes are known. Use this theorem instead of +`String.Internal.ofList_ne_ofList` when many disequalities between the same literals are needed +and the proofs `h₁` and `h₂` can be shared. +-/ +theorem String.Internal.ne_of_code {s₁ s₂ : String} {n₁ n₂ : Nat} (h₁ : code s₁ = n₁) + (h₂ : code s₂ = n₂) (h : Nat.beq n₁ n₂ = false) : ¬ s₁ = s₂ := by + intro h' + subst h' h₁ h₂ + rw [Nat.beq_refl] at h + contradiction + @[deprecated String.ofList_inj (since := "2025-10-30")] theorem List.asString_inj {l₁ l₂ : List Char} : String.ofList l₁ = String.ofList l₂ ↔ l₁ = l₂ := String.ofList_inj
diff --git a/src/Lean/Meta/Match/MatchEqs.lean b/src/Lean/Meta/Match/MatchEqs.lean index ab018fa..42c2de1 100644 --- a/src/Lean/Meta/Match/MatchEqs.lean +++ b/src/Lean/Meta/Match/MatchEqs.lean
@@ -59,11 +59,131 @@ mvarId.deltaTarget (· == ``Nat.Internal.elimOffset) /-- -If the left-hand side of the goal is `dite (a = b) t e` where `a` and `b` are `String` literals, -rewrites it to the selected branch. Distinct literals are proved distinct with -`mkStringLitNeProof`; reducing `String.decEq` instead compares them character by character. +The codes of the `String` literals of a matcher: a mapping from a literal `s` to the numeral `n` +such that `String.Internal.code s = n`, and a proof of this equation. See `getStrLitCodes`. -/ -private def rwStringLitDite? (mvarId : MVarId) : MetaM (Option MVarId) := mvarId.withContext do +private abbrev StrLitCodes := Std.HashMap String (Expr × Expr) + +/-- +Returns `true` if `e` is a `String` literal that has a code in `StrLitCodes`. + +A literal with more than `256` characters does not have one: the kernel evaluates +`String.Internal.codeOfList` with one multiplication for each character, on a number whose size +is proportional to the number of characters already processed. +-/ +private def hasStrLitCode (e : Expr) : Bool := + match e with + | .lit (.strVal s) => s.length ≤ 256 + | _ => false + +/-- +The minimum number of `String` literals of a matcher for which the auxiliary theorems +`strLitCodes` (see `getStrLitCodes`) and `strLitChain` are generated. + +These theorems reduce the time the kernel takes to check the equations of a matcher with many +literals, but each equation has to request them, and this request has a cost. With less than `32` +literals, the equations are generated faster without them. +-/ +private def minStrLits := 32 + +/-- Returns `true` if at least `minStrLits` different `String` literals with a code occur in `e`. -/ +private def hasMinStrLits (e : Expr) : MetaM Bool := do + let (_, lits) ← e.forEach' visit |>.run {} + return lits.size ≥ minStrLits +where + visit (e : Expr) : StateRefT (Std.HashSet String) MetaM Bool := do + if (← get).size ≥ minStrLits then return false + if hasStrLitCode e then + let .lit (.strVal s) := e | unreachable! + modify (·.insert s) + return true + +/-- Returns the `String` literals occurring in `e` that have a code, without duplicates. -/ +private def collectStrLits (e : Expr) : MetaM (Array String) := do + let (_, lits, _) ← e.forEach visit |>.run (#[], {}) + return lits +where + visit (e : Expr) : StateRefT (Array String × Std.HashSet String) MetaM Unit := do + unless hasStrLitCode e do return () + let .lit (.strVal s) := e | return () + modify fun (lits, visited) => + if visited.contains s then (lits, visited) else (lits.push s, visited.insert s) + +/-- +Returns the codes of the `String` literals occurring in the definition of the matcher +`matchDeclName`. Only literals with at most `256` characters have a code (see `hasStrLitCode`), +and the result is empty if there are less than `minStrLits` different ones. + +The proof of an equation of a matcher with `n` `String` literal patterns contains up to `n-1` +proofs that two of these literals are different, and there is one equation for each alternative. +With `String.Internal.ne_of_code`, such a proof is a comparison between the codes of the two +literals. Computing the code of a literal is the expensive step: the kernel evaluates +`String.Internal.codeOfList` on its characters. So, it is performed once for each literal, in +the auxiliary theorem +``` +matchDeclName.strLitCodes : code "a" = n₁ ∧ code "b" = n₂ ∧ ... +``` +and the proof for the literal `i` returned by this function is a projection of this theorem. +-/ +private def getStrLitCodes (matchDeclName : Name) : MetaM StrLitCodes := do + -- A matcher with less than `minStrLits` alternatives is not traversed. + let some matchInfo ← getMatcherInfo? matchDeclName | return {} + if matchInfo.numAlts < minStrLits then return {} + let some value := (← getConstInfo matchDeclName).value? | return {} + unless (← hasMinStrLits value) do return {} + let thmName := mkPrivateName (← getEnv) matchDeclName ++ `strLitCodes + realizeConst matchDeclName thmName do + let mkFact (lit : String) : Expr × Expr := + let (n, h) := mkStringLitCodeProof lit + let code := mkApp (mkConst ``String.Internal.code) (mkStrLit lit) + (mkApp3 (mkConst ``Eq [1]) (mkConst ``Nat) code n, h) + let lits ← collectStrLits value + let (type, value) := lits.pop.foldr (init := mkFact lits.back!) fun lit (type, value) => + let (fact, h) := mkFact lit + (mkAnd fact type, mkApp4 (mkConst ``And.intro) fact type h value) + addDecl <| Declaration.thmDecl { name := thmName, levelParams := [], type, value } + -- The literals and their codes are retrieved from the statement of the theorem. + let getCode (fact : Expr) : String × Expr := + -- `fact` is `code lit = n` + match fact.appFn!.appArg! with + | .app _ (.lit (.strVal lit)) => (lit, fact.appArg!) + | _ => unreachable! + let mut codes : StrLitCodes := {} + let mut type := (← getConstInfo thmName).type + let mut proof := mkConst thmName + repeat + let_expr And fact rest := type | break + let (lit, n) := getCode fact + codes := codes.insert lit (n, .proj ``And 0 proof) + type := rest + proof := .proj ``And 1 proof + let (lit, n) := getCode type + return codes.insert lit (n, proof) + +/-- +Returns a proof of `¬ a = b`, where `a` and `b` are the `String` literals `s₁` and `s₂`, +which must be different. + +If both literals have a code in `codes`, the proof compares the codes. Otherwise, it compares the +characters at the first position where the two literals differ (see `mkStringLitNeProof`). +-/ +private def mkStrLitNeProof (codes : StrLitCodes) (a b : Expr) (s₁ s₂ : String) : MetaM Expr := do + let some (n₁, h₁) := codes[s₁]? | mkCharNeProof + let some (n₂, h₂) := codes[s₂]? | mkCharNeProof + let h := mkApp2 (mkConst ``Eq.refl [1]) (mkConst ``Bool) (mkConst ``false) + return mkApp7 (mkConst ``String.Internal.ne_of_code) a b n₁ n₂ h₁ h₂ h +where + mkCharNeProof : MetaM Expr := + return mkExpectedPropHint (← mkStringLitNeProof s₁ s₂) + (mkNot (mkApp3 (mkConst ``Eq [1]) (mkConst ``String) a b)) + +/-- +If the left-hand side of the goal is `dite (a = b) t e` where `a` and `b` are `String` literals, +rewrites it to the selected branch. Distinct literals are proved distinct with `mkStrLitNeProof`; +reducing `String.decEq` instead compares them character by character. +`codes` are the codes of the literals of the matcher, see `getStrLitCodes`. +-/ +private def rwStringLitDite? (codes : StrLitCodes) (mvarId : MVarId) : MetaM (Option MVarId) := mvarId.withContext do let some (_, lhs, rhs) := (← mvarId.getType).eq? | return none let_expr dite@dite α c h t e := lhs | return none let_expr Eq _ a b := c | return none @@ -77,7 +197,7 @@ mvarId.assign (← mkEqTrans proof mvarNew) return some mvarNew.mvarId! else - let hc := mkExpectedPropHint (← mkStringLitNeProof s₁ s₂) (mkNot c) + let hc ← mkStrLitNeProof codes a b s₁ s₂ -- The new goal is `e hc = rhs`, and `dite_eq_of_not` expects a proof of `∀ h, e h = rhs`. -- The proof of the new goal is put under the binder without abstracting `hc`: -- `e h` and `e hc` are definitionally equal by proof irrelevance. @@ -150,6 +270,187 @@ return mvarNew.mvarId! /-- +A matcher whose definition starts with a chain of tests on `String` literals +``` +dite (x = "a₁") (Eq.ndrec_symm (alt₁ ())) fun _ => dite (x = "a₂") (Eq.ndrec_symm (alt₂ ())) fun _ => ... e +``` +where `x` is its only discriminant. See `getStrLitChain?`. +-/ +private structure StrLitChain where + /-- The number of arguments of the matcher. -/ + arity : Nat + /-- The position of the discriminant in the arguments of the matcher. -/ + discrPos : Nat + /-- The literals tested by the chain. -/ + lits : Array String + /-- `altPos[i]` is the position, in the arguments of the matcher, of the alternative for `lits[i]`. -/ + altPos : Array Nat + /-- + The term `e` after the last test. Its loose bound variables are the arguments of the matcher: + it is under `arity` binders. + -/ + rest : Expr + +/-- Returns `true` if `e` has a loose bound variable with index smaller than `n`. -/ +private partial def hasLooseBVarLt (e : Expr) (n : Nat) : Bool := + go e 0 +where + go (e : Expr) (offset : Nat) : Bool := + if e.looseBVarRange ≤ offset then false else + match e with + | .bvar idx => idx < offset + n + | .app f a => go f offset || go a offset + | .lam _ d b _ | .forallE _ d b _ => go d offset || go b (offset + 1) + | .letE _ t v b _ => go t offset || go v offset || go b (offset + 1) + | .mdata _ b | .proj _ _ b => go b offset + | _ => false + +/-- +Returns the chain of tests on `String` literals at the beginning of the definition of the matcher +`matchDeclName`, if it has one with at least `minStrLits` tests. See `StrLitChain`. + +The `else` branch of a test is `fun h : ¬ x = "aᵢ" => ..`. No hypothesis `h` is used in a chain. +`getStrLitChainThm` relies on this property. +-/ +private def getStrLitChain? (matchDeclName : Name) : MetaM (Option StrLitChain) := do + let some matchInfo ← getMatcherInfo? matchDeclName | return none + unless matchInfo.numDiscrs == 1 && matchInfo.getNumDiscrEqs == 0 do return none + let some value := (← getConstInfo matchDeclName).value? | return none + let arity := matchInfo.arity + let discrPos := matchInfo.numParams + 1 + let mut e := value + for _ in *...arity do + let .lam _ _ b _ := e | return none + e := b + -- `e` is under `arity + lits.size` binders: the arguments of the matcher, and one hypothesis for + -- each test that failed. + -- The hypotheses are the bound variables with index smaller than `lits.size`. + let mut lits := #[] + let mut altPos := #[] + repeat + let depth := arity + lits.size + let_expr dite α c inst t e' := e | break + let_expr Eq _ x v := c | break + let_expr Eq.ndrec_symm _ _ motive m _ := t | break + let .lit (.strVal lit) := v | break + let .lam _ _ rest _ := e' | break + let .app (.bvar altIdx) unit := m | break + unless x == .bvar (depth - 1 - discrPos) && unit.isConstOf ``Unit.unit do break + unless lits.size ≤ altIdx && altIdx < depth do break + if hasLooseBVarLt α lits.size || hasLooseBVarLt inst lits.size || hasLooseBVarLt motive lits.size then break + lits := lits.push lit + altPos := altPos.push (depth - 1 - altIdx) + e := rest + if lits.size < minStrLits || hasLooseBVarLt e lits.size then return none + return some { arity, discrPos, lits, altPos, rest := e.lowerLooseBVars lits.size lits.size } + +/-- +Returns the name of the auxiliary theorem for the matcher `matchDeclName`, which has the chain of +tests `chain`. +``` +matchDeclName.strLitChain : ∀ params motive x alts (r : motive x), + r = matchDeclName params motive x alts → + (x = "a₁" → r ≍ alt₁ ()) ∧ (¬ x = "a₁" → (x = "a₂" → r ≍ alt₂ ()) ∧ (¬ x = "a₂" → ... r ≍ e)) +``` +It is proved with a single traversal of the chain, and has one case for each alternative. +The congruence equation for the literal `"aᵢ"` is the case `i` of this theorem: its proof +selects the case with `i-1` proofs that `"aᵢ"` is different from the preceding literals. +Proving each congruence equation directly traverses the chain up to the test `i`, and the +kernel processes the tests that follow at each step. + +The variable `r` is used instead of the matcher application in the cases because the size of the +latter is proportional to the number of alternatives, and each case is under a different number +of binders. +-/ +private def getStrLitChainThm (matchDeclName : Name) (chain : StrLitChain) : MetaM Name := do + let thmName := mkPrivateName (← getEnv) matchDeclName ++ `strLitChain + realizeConst matchDeclName thmName do + let info ← getConstInfo matchDeclName + let us := info.levelParams.map mkLevelParam + forallBoundedTelescope info.type chain.arity fun xs _ => do + let app := mkAppN (mkConst matchDeclName us) xs + let tests := (info.instantiateValueLevelParams! us).beta xs + withLocalDeclD `r (← inferType app) fun r => do + let (stmt, proof) ← mkCases r tests chain.lits.size + let type ← mkForallFVars (xs.push r) (.forallE `h (← mkEq r app) stmt .default) + let value ← mkLambdaFVars (xs.push r) proof + addDecl <| Declaration.thmDecl { name := thmName, levelParams := info.levelParams, type, value } + return thmName +where + /-- + Returns the statement of the cases of the first `n` tests of `tests`, and a proof for + `r = tests → statement`. + -/ + mkCases (r tests : Expr) : Nat → MetaM (Expr × Expr) + | 0 => return (← mkHEq r tests, ← mkAppOptM ``heq_of_eq #[none, r, tests]) + | n+1 => do + let_expr dite _ c inst t e := tests | unreachable! + let_expr Eq α b a := c | unreachable! + let_expr ndrec@Eq.ndrec_symm _ _ motive m _ := t | unreachable! + let .lam _ _ rest _ := e | unreachable! + let [u₁, u₂] := ndrec.constLevels! | unreachable! + let (q, h) ← mkCases r rest n + let heq := mkApp4 (mkConst ``HEq [u₁]) (motive.beta #[b]) r (motive.beta #[a]) m + let stmt := mkAnd (.forallE `h c heq .default) (.forallE `h (mkNot c) q .default) + let h := mkLambda `h .default (mkNot c) h + let proof := mkAppN (mkConst ``dite_ndrec_symm_cases [u₂, u₁]) #[α, a, b, inst, motive, m, e, r, q, h] + return (stmt, proof) + +/-- +Proves a goal `matchDeclName params motive a alts ≍ rhs` using the theorem +`matchDeclName.strLitChain`, if `matchDeclName` has a chain of tests on `String` literals, and +- `a` is one of the literals `"aᵢ"` of the chain and `rhs` is `altᵢ ()`. The case `i` of the + theorem is selected with proofs that `"aᵢ"` is different from the preceding literals. +- `a` is a variable `x`, `rhs` is the term after the last test, and for each literal `"aᵢ"` of + the chain there is a hypothesis `x = "aᵢ" → False`. The last case of the theorem is selected + with these hypotheses. + +Returns `false` otherwise. See `getStrLitChainThm`. +-/ +private def proveUsingStrLitChain? (matchDeclName : Name) (mvarId : MVarId) : MetaM Bool := + mvarId.withContext do + let some chain ← getStrLitChain? matchDeclName | return false + let some (_, lhs, _, rhs) := (← mvarId.getType).heq? | return false + unless lhs.isAppOfArity matchDeclName chain.arity do return false + let args := lhs.getAppArgs + let a := args[chain.discrPos]! + let mkChainThm : MetaM Expr := do + let thmName ← getStrLitChainThm matchDeclName chain + return mkAppN (mkConst thmName lhs.getAppFn.constLevels!) (args ++ #[lhs, ← mkEqRefl lhs]) + match a with + | .lit (.strVal lit) => + let some i := chain.lits.idxOf? lit | return false + unless rhs == mkApp args[chain.altPos[i]!]! (mkConst ``Unit.unit) do return false + let mut proof ← mkChainThm + -- The first case does not need the codes of the literals. + let codes ← if i == 0 then pure {} else getStrLitCodes matchDeclName + for j in *...i do + let lit' := chain.lits[j]! + proof := mkApp (.proj ``And 1 proof) (← mkStrLitNeProof codes a (mkStrLit lit') lit lit') + mvarId.assign (mkApp (.proj ``And 0 proof) (← mkEqRefl a)) + return true + | .fvar _ => + unless rhs == chain.rest.instantiateRev args do return false + -- The hypotheses `a = "aᵢ" → False` + let mut hyps : Std.HashMap String Expr := {} + for localDecl in (← getLCtx) do + let .forallE _ d b _ := localDecl.type | continue + let_expr Eq _ x v := d | continue + let .lit (.strVal lit) := v | continue + if x == a && b.isConstOf ``False then + hyps := hyps.insert lit localDecl.toExpr + let mut hs := #[] + for lit in chain.lits do + let some h := hyps[lit]? | return false + hs := hs.push h + let mut proof ← mkChainThm + for h in hs do + proof := mkApp (.proj ``And 1 proof) h + mvarId.assign proof + return true + | _ => return false + +/-- A `contradiction` variant for the goals of `proveCondEqThm`. It closes the goal if a hypothesis is - a disequality `h : a ≠ b`, or `h : a = b → False`, where `a` and `b` are definitionally equal, - a generalized disequality such as `h : ∀ ys, x = C ys → False` (see `processGenDiseq`), or @@ -201,15 +502,16 @@ instantiateMVars mvar0 where unfoldAndProve (mvarId : MVarId) : MetaM Unit := do + if (← proveUsingStrLitChain? matchDeclName mvarId) then return let mvarId ← mvarId.deltaTarget (· == matchDeclName) let mvarId ← mvarId.heqOfEq - go (← stripDiscrEqProofs matchDeclName mvarId) 0 + go (← getStrLitCodes matchDeclName) (← stripDiscrEqProofs matchDeclName mvarId) 0 - go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do + go (codes : StrLitCodes) (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do trace[Meta.Match.matchEqs] "proveCondEqThm.go {mvarId}" let mvarId ← mvarId.modifyTargetEqLHS whnfCore let subgoals ← - (do let some mvarId ← rwStringLitDite? mvarId | throwError "no `String` literal `dite`" + (do let some mvarId ← rwStringLitDite? codes mvarId | throwError "no `String` literal `dite`" return #[mvarId]) <|> (do mvarId.refl; return #[]) @@ -239,7 +541,7 @@ (substSomeVar mvarId) <|> (throwError "failed to generate equality theorems for `match` expression `{matchDeclName}`\n{MessageData.ofGoal mvarId}") - subgoals.forM (go · (depth+1)) + subgoals.forM (go codes · (depth+1)) /-- Create new alternatives (aka minor premises) by replacing `discrs` with `patterns` at `alts`.
diff --git a/src/Lean/Meta/StringLitProof.lean b/src/Lean/Meta/StringLitProof.lean index ce6c124..9854120 100644 --- a/src/Lean/Meta/StringLitProof.lean +++ b/src/Lean/Meta/StringLitProof.lean
@@ -35,4 +35,22 @@ | c₁ :: l₁, c₂ :: l₂, i => if c₁ == c₂ then firstDiff l₁ l₂ (i + 1) else i | _, _, i => i +/-- +Returns the code of the string `s`: the value of `String.Internal.code s`. +See `String.Internal.codeOfList`. +-/ +def stringLitCode (s : String) : Nat := + s.toList.foldr (fun c n => c.toNat + 1 + 2097152 * n) 0 + +/-- +Builds a proof of `String.Internal.code s = n` for the string literal `s`, where `n` is the +numeral `stringLitCode s`. Returns `n` and the proof. + +To check it, the kernel evaluates `String.Internal.codeOfList` on the list of characters of `s`. +-/ +def mkStringLitCodeProof (s : String) : Expr × Expr := + let n := mkRawNatLit (stringLitCode s) + let h := mkApp2 (mkConst ``Eq.refl [1]) (mkConst ``Nat) n + (n, mkApp3 (mkConst ``String.Internal.code_ofList) (toExpr s.toList) n h) + end Lean.Meta
diff --git a/tests/elab/matchEqnsStringLitChain.lean b/tests/elab/matchEqnsStringLitChain.lean new file mode 100644 index 0000000..9b13f55 --- /dev/null +++ b/tests/elab/matchEqnsStringLitChain.lean
@@ -0,0 +1,194 @@ +import Lean +/-! +A matcher that starts with a chain of at least 32 tests on `String` literals has an auxiliary +theorem `strLitChain` with one case for each test, proved with a single traversal of the chain. +The congruence equations of the alternatives of the chain, and of the alternative that follows it, +are cases of this theorem (#16313). +-/ +open Lean Meta + +/-- Returns the statement of the theorem `strLitChain` of `matcherName`, if it has one. -/ +def strLitChain? (matcherName : Name) : MetaM (Option Expr) := do + discard <| Match.genMatchCongrEqns matcherName + let name := mkPrivateName (← getEnv) matcherName ++ `strLitChain + let some (.thmInfo info) := (← getEnv).find? name | return none + return some info.type + +/-- Returns, for each congruence equation of `matcherName`, whether it is proved using `strLitChain`. -/ +def chainEqns (matcherName : Name) : MetaM (Array Bool) := do + let name := mkPrivateName (← getEnv) matcherName ++ `strLitChain + (← Match.genMatchCongrEqns matcherName).mapM fun eqn => do + let some (.thmInfo info) := (← getEnv).find? eqn | throwError "theorem expected: {eqn}" + return (info.value.find? (·.isConstOf name)).isSome + +/-! A matcher with less than 32 literals does not have the theorem. -/ + +def small : String → Nat + | "a" => 0 + | "b" => 1 + | "c" => 2 + | _ => 3 + +/-- info: (none, [false, false, false, false]) -/ +#guard_msgs in +run_meta do logInfo m!"{((← strLitChain? ``small.match_1).map fun _ => (), ← chainEqns ``small.match_1)}" + +/-! A matcher with 32 literals. -/ + +def f : String → Nat + | "lit_0" => 0 | "lit_1" => 1 | "lit_2" => 2 | "lit_3" => 3 + | "lit_4" => 4 | "lit_5" => 5 | "lit_6" => 6 | "lit_7" => 7 + | "lit_8" => 8 | "lit_9" => 9 | "lit_10" => 10 | "lit_11" => 11 + | "lit_12" => 12 | "lit_13" => 13 | "lit_14" => 14 | "lit_15" => 15 + | "lit_16" => 16 | "lit_17" => 17 | "lit_18" => 18 | "lit_19" => 19 + | "lit_20" => 20 | "lit_21" => 21 | "lit_22" => 22 | "lit_23" => 23 + | "lit_24" => 24 | "lit_25" => 25 | "lit_26" => 26 | "lit_27" => 27 + | "lit_28" => 28 | "lit_29" => 29 | "lit_30" => 30 | "lit_31" => 31 + | _ => 32 + +/-- +Checks that `type` is `∀ motive x alts (r : motive x), r = matcher motive x alts → cases`, where +`cases` is `(x = "lit_0" → r ≍ alt₀ ()) ∧ (¬ x = "lit_0" → (x = "lit_1" → r ≍ alt₁ ()) ∧ ..)`, +and returns the number of tests. +-/ +partial def numCases (type : Expr) : MetaM Nat := + forallTelescope type fun xs cases => go xs cases 0 +where + go (xs : Array Expr) (cases : Expr) (i : Nat) : MetaM Nat := do + let x := xs[1]! + let r := xs[xs.size - 2]! + match_expr cases with + | And pos neg => + let .forallE _ c heq _ := pos | throwError "unexpected case{indentExpr pos}" + let .forallE _ nc rest _ := neg | throwError "unexpected case{indentExpr neg}" + let some (_, lhs, _, rhs) := heq.heq? | throwError "unexpected case{indentExpr pos}" + unless c == (← mkEq x (mkStrLit s!"lit_{i}")) && nc == mkNot c && lhs == r && rhs == mkApp xs[i+2]! (mkConst ``Unit.unit) do + throwError "unexpected case{indentExpr cases}" + go xs rest (i+1) + | _ => + let some (_, lhs, _, rhs) := cases.heq? | throwError "unexpected case{indentExpr cases}" + unless lhs == r && rhs == mkApp xs[i+2]! x do throwError "unexpected case{indentExpr cases}" + return i + +/-- info: 32 -/ +#guard_msgs in +run_meta do + let some type ← strLitChain? ``f.match_1 | throwError "theorem expected" + logInfo m!"{← numCases type}" + +run_meta do + unless (← chainEqns ``f.match_1).all id do throwError "unexpected proof" + +example : f "lit_0" = 0 := by simp [f] +example : f "lit_17" = 17 := by simp [f] +example : f "lit_31" = 31 := by simp [f] +example : f "lit_32" = 32 := by simp [f] + +/-! A chain followed by an alternative that is not a catch-all, and a polymorphic function. -/ + +def thenVar : String → Nat + | "lit_0" => 0 | "lit_1" => 1 | "lit_2" => 2 | "lit_3" => 3 + | "lit_4" => 4 | "lit_5" => 5 | "lit_6" => 6 | "lit_7" => 7 + | "lit_8" => 8 | "lit_9" => 9 | "lit_10" => 10 | "lit_11" => 11 + | "lit_12" => 12 | "lit_13" => 13 | "lit_14" => 14 | "lit_15" => 15 + | "lit_16" => 16 | "lit_17" => 17 | "lit_18" => 18 | "lit_19" => 19 + | "lit_20" => 20 | "lit_21" => 21 | "lit_22" => 22 | "lit_23" => 23 + | "lit_24" => 24 | "lit_25" => 25 | "lit_26" => 26 | "lit_27" => 27 + | "lit_28" => 28 | "lit_29" => 29 | "lit_30" => 30 | "lit_31" => 31 + | s => s.length + +example : thenVar "lit_5" = 5 := by simp [thenVar] + +def poly {α : Type u} (a b : α) : String → α + | "lit_0" => a | "lit_1" => a | "lit_2" => a | "lit_3" => a + | "lit_4" => a | "lit_5" => a | "lit_6" => a | "lit_7" => a + | "lit_8" => a | "lit_9" => a | "lit_10" => a | "lit_11" => a + | "lit_12" => a | "lit_13" => a | "lit_14" => a | "lit_15" => a + | "lit_16" => a | "lit_17" => a | "lit_18" => a | "lit_19" => a + | "lit_20" => a | "lit_21" => a | "lit_22" => a | "lit_23" => a + | "lit_24" => a | "lit_25" => a | "lit_26" => a | "lit_27" => a + | "lit_28" => a | "lit_29" => a | "lit_30" => a | "lit_31" => a + | _ => b + +example : poly 1 2 "lit_7" = 1 := by simp [poly] +example : poly 1 2 "x" = 2 := by simp [poly] + +/-! +Matchers with at least 32 literals that do not start with a chain of tests on a single `String` +discriminant. Their equations are still generated. +-/ + +def twoDiscrs : String → Bool → Nat + | "lit_0", _ => 0 | "lit_1", _ => 1 | "lit_2", _ => 2 | "lit_3", _ => 3 + | "lit_4", _ => 4 | "lit_5", _ => 5 | "lit_6", _ => 6 | "lit_7", _ => 7 + | "lit_8", _ => 8 | "lit_9", _ => 9 | "lit_10", _ => 10 | "lit_11", _ => 11 + | "lit_12", _ => 12 | "lit_13", _ => 13 | "lit_14", _ => 14 | "lit_15", _ => 15 + | "lit_16", _ => 16 | "lit_17", _ => 17 | "lit_18", _ => 18 | "lit_19", _ => 19 + | "lit_20", _ => 20 | "lit_21", _ => 21 | "lit_22", _ => 22 | "lit_23", _ => 23 + | "lit_24", _ => 24 | "lit_25", _ => 25 | "lit_26", _ => 26 | "lit_27", _ => 27 + | "lit_28", _ => 28 | "lit_29", _ => 29 | "lit_30", _ => 30 | "lit_31", _ => 31 + | _, _ => 32 + +def nested : Option String → Nat + | some "lit_0" => 0 | some "lit_1" => 1 | some "lit_2" => 2 | some "lit_3" => 3 + | some "lit_4" => 4 | some "lit_5" => 5 | some "lit_6" => 6 | some "lit_7" => 7 + | some "lit_8" => 8 | some "lit_9" => 9 | some "lit_10" => 10 | some "lit_11" => 11 + | some "lit_12" => 12 | some "lit_13" => 13 | some "lit_14" => 14 | some "lit_15" => 15 + | some "lit_16" => 16 | some "lit_17" => 17 | some "lit_18" => 18 | some "lit_19" => 19 + | some "lit_20" => 20 | some "lit_21" => 21 | some "lit_22" => 22 | some "lit_23" => 23 + | some "lit_24" => 24 | some "lit_25" => 25 | some "lit_26" => 26 | some "lit_27" => 27 + | some "lit_28" => 28 | some "lit_29" => 29 | some "lit_30" => 30 | some "lit_31" => 31 + | _ => 32 + +def withEq (s : String) : Nat := + match _h : s with + | "lit_0" => 0 | "lit_1" => 1 | "lit_2" => 2 | "lit_3" => 3 + | "lit_4" => 4 | "lit_5" => 5 | "lit_6" => 6 | "lit_7" => 7 + | "lit_8" => 8 | "lit_9" => 9 | "lit_10" => 10 | "lit_11" => 11 + | "lit_12" => 12 | "lit_13" => 13 | "lit_14" => 14 | "lit_15" => 15 + | "lit_16" => 16 | "lit_17" => 17 | "lit_18" => 18 | "lit_19" => 19 + | "lit_20" => 20 | "lit_21" => 21 | "lit_22" => 22 | "lit_23" => 23 + | "lit_24" => 24 | "lit_25" => 25 | "lit_26" => 26 | "lit_27" => 27 + | "lit_28" => 28 | "lit_29" => 29 | "lit_30" => 30 | "lit_31" => 31 + | _ => 32 + +/-- info: [false, false, false] -/ +#guard_msgs in +run_meta do + logInfo m!"{[(← chainEqns ``twoDiscrs.match_1).any id, (← chainEqns ``nested.match_1).any id, (← chainEqns ``withEq.match_1).any id]}" + +example : twoDiscrs "lit_3" true = 3 := by simp [twoDiscrs] +example : nested (some "lit_3") = 3 := by simp [nested] +example : withEq "lit_3" = 3 := by simp [withEq] + +/-! +The size of the proof of the congruence equation of a literal does not depend on the number of +tests that follow it: `f` and `long` start with the same 32 literals. +-/ + +def long : String → Nat + | "lit_0" => 0 | "lit_1" => 1 | "lit_2" => 2 | "lit_3" => 3 + | "lit_4" => 4 | "lit_5" => 5 | "lit_6" => 6 | "lit_7" => 7 + | "lit_8" => 8 | "lit_9" => 9 | "lit_10" => 10 | "lit_11" => 11 + | "lit_12" => 12 | "lit_13" => 13 | "lit_14" => 14 | "lit_15" => 15 + | "lit_16" => 16 | "lit_17" => 17 | "lit_18" => 18 | "lit_19" => 19 + | "lit_20" => 20 | "lit_21" => 21 | "lit_22" => 22 | "lit_23" => 23 + | "lit_24" => 24 | "lit_25" => 25 | "lit_26" => 26 | "lit_27" => 27 + | "lit_28" => 28 | "lit_29" => 29 | "lit_30" => 30 | "lit_31" => 31 + | "lit_32" => 32 | "lit_33" => 33 | "lit_34" => 34 | "lit_35" => 35 + | "lit_36" => 36 | "lit_37" => 37 | "lit_38" => 38 | "lit_39" => 39 + | "lit_40" => 40 | "lit_41" => 41 | "lit_42" => 42 | "lit_43" => 43 + | "lit_44" => 44 | "lit_45" => 45 | "lit_46" => 46 | "lit_47" => 47 + | _ => 48 + +run_meta do + let shortEqns ← Match.genMatchCongrEqns ``f.match_1 + let longEqns ← Match.genMatchCongrEqns ``long.match_1 + let size (declName : Name) : MetaM Nat := do + let some (.thmInfo info) := (← getEnv).find? declName | throwError "theorem expected: {declName}" + (ShareCommon.shareCommon' info.value).numObjs + for i in [0:30] do + let d₁ := (← size shortEqns[i+1]!) - (← size shortEqns[i]!) + let d₂ := (← size longEqns[i+1]!) - (← size longEqns[i]!) + unless d₁ == d₂ do + throwError "proof size depends on the number of remaining tests: {d₁} {d₂}"
diff --git a/tests/elab/matchEqnsStringLitCodes.lean b/tests/elab/matchEqnsStringLitCodes.lean new file mode 100644 index 0000000..971214d --- /dev/null +++ b/tests/elab/matchEqnsStringLitCodes.lean
@@ -0,0 +1,166 @@ +import Lean +/-! +The equations of a `match` with many `String` literals prove that two literals are different by +comparing their codes with `String.Internal.ne_of_code`. The code of each literal of the matcher +is computed once, in an auxiliary theorem `strLitCodes`, and shared by all the equations (#16313). +-/ +open Lean Meta + +/-- Returns the statement of the theorem with the codes of the `String` literals of `matcherName`. -/ +def strLitCodes? (matcherName : Name) : MetaM (Option Expr) := do + discard <| Match.genMatchCongrEqns matcherName + let name := mkPrivateName (← getEnv) matcherName ++ `strLitCodes + let some (.thmInfo info) := (← getEnv).find? name | return none + return some info.type + +/-- Returns the conjuncts of `e`. -/ +partial def conjuncts (e : Expr) : Array Expr := + match_expr e with + | And a b => #[a] ++ conjuncts b + | _ => #[e] + +/-- Returns the number of occurrences of the constant `declName` in `e`. -/ +partial def numOccs (declName : Name) (e : Expr) : Nat := + match e with + | .const n _ => if n == declName then 1 else 0 + | .app f a => numOccs declName f + numOccs declName a + | .lam _ d b _ | .forallE _ d b _ => numOccs declName d + numOccs declName b + | .letE _ t v b _ => numOccs declName t + numOccs declName v + numOccs declName b + | .mdata _ b | .proj _ _ b => numOccs declName b + | _ => 0 + +/-- +Returns, for each congruence equation of `matcherName`, the number of disequalities between +literals proved by comparing codes, and by comparing characters. +-/ +def numNeProofs (matcherName : Name) : MetaM (Array (Nat × Nat)) := do + (← Match.genMatchCongrEqns matcherName).mapM fun eqn => do + let some (.thmInfo info) := (← getEnv).find? eqn | throwError "theorem expected: {eqn}" + return (numOccs ``String.Internal.ne_of_code info.value, numOccs ``String.Internal.ofList_ne_ofList info.value) + +/-! A matcher with 32 literals. The equation of the literal `i` skips `i` tests. -/ + +def f : String → Nat + | "lit_0" => 0 | "lit_1" => 1 | "lit_2" => 2 | "lit_3" => 3 + | "lit_4" => 4 | "lit_5" => 5 | "lit_6" => 6 | "lit_7" => 7 + | "lit_8" => 8 | "lit_9" => 9 | "lit_10" => 10 | "lit_11" => 11 + | "lit_12" => 12 | "lit_13" => 13 | "lit_14" => 14 | "lit_15" => 15 + | "lit_16" => 16 | "lit_17" => 17 | "lit_18" => 18 | "lit_19" => 19 + | "lit_20" => 20 | "lit_21" => 21 | "lit_22" => 22 | "lit_23" => 23 + | "lit_24" => 24 | "lit_25" => 25 | "lit_26" => 26 | "lit_27" => 27 + | "lit_28" => 28 | "lit_29" => 29 | "lit_30" => 30 | "lit_31" => 31 + | _ => 32 + +/-- +info: 32 +--- +info: String.Internal.code "lit_0" = 947798728022099382692216941 +--- +info: String.Internal.code "lit_1" = 967141541135933449487515757 +--- +info: String.Internal.code "lit_31" = 2028241966192334405996308206714989 +-/ +#guard_msgs in +run_meta do + let some type ← strLitCodes? ``f.match_1 | throwError "theorem expected" + let facts := conjuncts type + logInfo m!"{facts.size}" + for i in [0, 1, 31] do logInfo facts[i]! + +run_meta do + let ns ← numNeProofs ``f.match_1 + for i in [0:32] do + unless ns[i]! == (i, 0) do throwError "unexpected proof for alternative {i}: {ns[i]!}" + +example : f "lit_0" = 0 := by simp [f] +example : f "lit_17" = 17 := by simp [f] +example : f "lit_31" = 31 := by simp [f] +example : f "lit_32" = 32 := by simp [f] + +/-! +Literals with the same characters at the same positions but different lengths, the empty string, +and the character with code `0`. The code of a literal is different from the code of its prefixes. +-/ + +def special : String → Nat + | "" => 0 | "\x00" => 1 | "\x00\x00" => 2 | "a" => 3 + | "ab" => 4 | "abc" => 5 | "αβ" => 6 | "s0" => 7 + | "s1" => 8 | "s2" => 9 | "s3" => 10 | "s4" => 11 + | "s5" => 12 | "s6" => 13 | "s7" => 14 | "s8" => 15 + | "s9" => 16 | "s10" => 17 | "s11" => 18 | "s12" => 19 + | "s13" => 20 | "s14" => 21 | "s15" => 22 | "s16" => 23 + | "s17" => 24 | "s18" => 25 | "s19" => 26 | "s20" => 27 + | "s21" => 28 | "s22" => 29 | "s23" => 30 | "s24" => 31 + | _ => 32 + +/-- +info: String.Internal.code "" = 0 +--- +info: String.Internal.code "\x00" = 1 +--- +info: String.Internal.code "\x00\x00" = 2097153 +--- +info: String.Internal.code "a" = 98 +--- +info: String.Internal.code "ab" = 207618146 +--- +info: String.Internal.code "abc" = 439804858728546 +--- +info: String.Internal.code "αβ" = 1986003890 +-/ +#guard_msgs in +run_meta do + let some type ← strLitCodes? ``special.match_1 | throwError "theorem expected" + for fact in (conjuncts type)[*...7] do logInfo fact + +example : special "" = 0 := by simp [special] +example : special "\x00" = 1 := by simp [special] +example : special "\x00\x00" = 2 := by simp [special] +example : special "ab" = 4 := by simp [special] +example : special "abc" = 5 := by simp [special] +example : special "αβ" = 6 := by simp [special] +example : special "abcd" = 32 := by simp [special] + +/-! +A literal with more than 256 characters does not have a code: the kernel would need a time +quadratic in its length to compute it. A disequality with this literal compares characters. +-/ + +def long : String → Nat + | "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" => 100 + | "lit_0" => 0 | "lit_1" => 1 | "lit_2" => 2 | "lit_3" => 3 + | "lit_4" => 4 | "lit_5" => 5 | "lit_6" => 6 | "lit_7" => 7 + | "lit_8" => 8 | "lit_9" => 9 | "lit_10" => 10 | "lit_11" => 11 + | "lit_12" => 12 | "lit_13" => 13 | "lit_14" => 14 | "lit_15" => 15 + | "lit_16" => 16 | "lit_17" => 17 | "lit_18" => 18 | "lit_19" => 19 + | "lit_20" => 20 | "lit_21" => 21 | "lit_22" => 22 | "lit_23" => 23 + | "lit_24" => 24 | "lit_25" => 25 | "lit_26" => 26 | "lit_27" => 27 + | "lit_28" => 28 | "lit_29" => 29 | "lit_30" => 30 | "lit_31" => 31 + | _ => 32 + +/-- info: 32 -/ +#guard_msgs in +run_meta do + let some type ← strLitCodes? ``long.match_1 | throwError "theorem expected" + logInfo m!"{(conjuncts type).size}" + +run_meta do + let ns ← numNeProofs ``long.match_1 + for i in [0:32] do + -- The test for the long literal is the first one. + unless ns[i+1]! == (i, 1) do throwError "unexpected proof for alternative {i+1}: {ns[i+1]!}" + +example : long "lit_3" = 3 := by simp [long] + +/-! A matcher with less than 32 literals does not have the auxiliary theorem. -/ + +def small : String → Nat + | "a" => 0 + | "b" => 1 + | "c" => 2 + | _ => 3 + +/-- info: (none, [(0, 0), (0, 1), (0, 2), (0, 0)]) -/ +#guard_msgs in +run_meta do + logInfo m!"{((← strLitCodes? ``small.match_1).map fun _ => (), ← numNeProofs ``small.match_1)}"