perf: prove `String` literal disequalities in `match` equations without `String.decEq` (#16354) This PR speeds up the generation of equation lemmas for definitions that `match` on `String` literals. With 64 literal patterns, generation used to hit the heartbeat limit. The equation generators try `rfl` first, which reduces `String.decEq` on the literals. This PR adds `Meta.Config.stringLitToCtor`. When it is `false`, `whnf` and `isDefEq` throw an internal exception instead of converting a `String` literal into a constructor application. `proveCondEqThm` and `mkEqnProof` try `rfl` with the flag off, then the proof that does not use `rfl`, then unrestricted `rfl`. Part of #16313. š¤ Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
diff --git a/src/Lean/Elab/PreDefinition/Eqns.lean b/src/Lean/Elab/PreDefinition/Eqns.lean index 6b6c256..2adbd6a 100644 --- a/src/Lean/Elab/PreDefinition/Eqns.lean +++ b/src/Lean/Elab/PreDefinition/Eqns.lean
@@ -10,6 +10,7 @@ import Lean.Meta.LetToHave import Lean.Meta.Match.NamedPatterns import Lean.Meta.Match.Rewrite +import Lean.Meta.Tactic.Refl import Lean.Meta.Tactic.Simp.Main import Lean.Meta.Tactic.Split import Lean.Meta.Tactic.SplitIf @@ -101,11 +102,10 @@ -- Try rfl before deltaLHS to avoid `id` checkpoints in the proof, which would make -- the lemma ineligible for dsimp - if (← tryURefl mvarId #[declName]) then + let rfl : MetaM Unit := do + unless (← tryURefl mvarId #[declName]) do throwError "`rfl` failed" trace[Elab.definition.eqns] "proved directly by rfl" - return ← instantiateMVars main - - go (← unfoldLHS declName mvarId) + reflOrProve rfl do go (← unfoldLHS declName mvarId) instantiateMVars main where /-- @@ -117,30 +117,31 @@ -/ go (mvarId : MVarId) : MetaM Unit := do withTraceNode `Elab.definition.eqns (fun _ => return m!"step:\n{MessageData.ofGoal mvarId}") do - if (← tryURefl mvarId) then - return () - else if (← tryContradiction mvarId) then - return () - else if let some mvarId ← simpMatch? mvarId then - go mvarId - else if let some mvarId ← simpIf? mvarId (useNewSemantics := true) then - go mvarId - else if let some mvarId ← whnfReducibleLHS? mvarId then - go mvarId - else - let ctx ← Simp.mkContext (config := { dsimp := false }) - match (← simpTargetStar mvarId ctx (simprocs := {})).1 with - | TacticResultCNM.closed => return () - | TacticResultCNM.modified mvarId => go mvarId - | TacticResultCNM.noChange => - if let some mvarIds ← casesOnStuckLHS? mvarId then - mvarIds.forM go - else if let some mvarIds ← splitTarget? mvarId (useNewSemantics := true) then - mvarIds.forM go - else if let some mvarId ← rwMatcherLHS? mvarId then - go mvarId - else - throwError "failed to generate equational theorem for `{.ofConstName declName}`\n{MessageData.ofGoal mvarId}" + let rfl : MetaM Unit := do + unless (← tryURefl mvarId) do throwError "`rfl` failed" + reflOrProve rfl do + if (← tryContradiction mvarId) then + return () + else if let some mvarId ← simpMatch? mvarId then + go mvarId + else if let some mvarId ← simpIf? mvarId (useNewSemantics := true) then + go mvarId + else if let some mvarId ← whnfReducibleLHS? mvarId then + go mvarId + else + let ctx ← Simp.mkContext (config := { dsimp := false }) + match (← simpTargetStar mvarId ctx (simprocs := {})).1 with + | TacticResultCNM.closed => return () + | TacticResultCNM.modified mvarId => go mvarId + | TacticResultCNM.noChange => + if let some mvarIds ← casesOnStuckLHS? mvarId then + mvarIds.forM go + else if let some mvarIds ← splitTarget? mvarId (useNewSemantics := true) then + mvarIds.forM go + else if let some mvarId ← rwMatcherLHS? mvarId then + go mvarId + else + throwError "failed to generate equational theorem for `{.ofConstName declName}`\n{MessageData.ofGoal mvarId}" /-- Checks whether the left-hand side of a quantified equality depends on `fvarId`.
diff --git a/src/Lean/Meta/Basic.lean b/src/Lean/Meta/Basic.lean index 73e149a..a17c469 100644 --- a/src/Lean/Meta/Basic.lean +++ b/src/Lean/Meta/Basic.lean
@@ -33,6 +33,8 @@ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck +/-- See `Config.stringLitToCtor`. -/ +builtin_initialize stringLitToCtorExceptionId : InternalExceptionId ← registerInternalExceptionId `stringLitToCtor /-- NOTE: value purely intended for equality comparison, *NOT* following the transparency lattice. -/ def TransparencyMode.toUInt64 : TransparencyMode → UInt64 @@ -211,6 +213,15 @@ Ignored if `Context.customCanUnfoldPredicate?` is set. -/ canUnfoldPredicateConfig : CanUnfoldPredicateConfig := .default + /-- + If `true`, `whnf` and `isDefEq` convert a `String` literal into the constructor application + `String.ofList [cā, ..., cā]` when a reduction step needs its constructor, e.g., to reduce + `String.decEq` on two literals. The reductions enabled by this conversion are linear in the + size of the literal. + If `false`, the internal exception `stringLitToCtor` is thrown instead of performing the + conversion. See `withoutStringLitToCtor`. + -/ + stringLitToCtor : Bool := true deriving Inhabited, Repr /-- Convert `isDefEq` and `WHNF` relevant parts into a key for caching results -/ @@ -234,6 +245,7 @@ (c.proj.toUInt64 <<< 19) ||| (c.zetaHave.toUInt64 <<< 21) ||| (c.zetaUnused.toUInt64 <<< 22) ||| + (c.stringLitToCtor.toUInt64 <<< 24) ||| (c.canUnfoldPredicateConfig.toBool.toUInt64 <<< 23) /-- Configuration with key produced by `Config.toKey`. -/ @@ -1397,6 +1409,13 @@ let config := f ctx.config { ctx with keyedConfig := { config } } +/-- +Executes `x` with `Config.stringLitToCtor := false`. That is, `x` is interrupted with the internal +exception `stringLitToCtor` if a reduction step needs the constructor of a `String` literal. +-/ +@[inline] def withoutStringLitToCtor : n α → n α := + withConfig ({ · with stringLitToCtor := false }) + @[inline] def withConfigWithKey (c : ConfigWithKey) : n α → n α := mapMetaM <| withReader fun ctx => let config := c.config
diff --git a/src/Lean/Meta/Match/MatchEqs.lean b/src/Lean/Meta/Match/MatchEqs.lean index 91711ac..c23bc55 100644 --- a/src/Lean/Meta/Match/MatchEqs.lean +++ b/src/Lean/Meta/Match/MatchEqs.lean
@@ -16,6 +16,7 @@ import Lean.Meta.Match.AltTelescopes import Lean.Meta.Match.NamedPatterns import Lean.Meta.SplitSparseCasesOn +import Lean.Meta.StringLitProof public section @@ -57,6 +58,29 @@ 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. +-/ +private def rwStringLitDite? (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 + let some sā := getStringValue? a | return none + let some sā := getStringValue? b | return none + let us := dite.constLevels! + let (lhs', proof) ← + if sā == sā then + let hc ← mkEqRefl a + pure (t.beta #[hc], mkAppN (mkConst ``dite_eq_left us) #[c, h, hc, α, t, e]) + else + let hc := mkExpectedPropHint (← mkStringLitNeProof sā sā) (mkNot c) + pure (e.beta #[hc], mkAppN (mkConst ``dite_eq_right us) #[c, h, hc, α, t, e]) + let mvarNew ← mkFreshExprSyntheticOpaqueMVar (← mkEq lhs' rhs) (← mvarId.getTag) + mvarId.assign (← mkEqTrans proof mvarNew) + return some mvarNew.mvarId! + +/-- Helper method for proving a conditional equational theorem associated with an alternative of the `match`-eliminator `matchDeclName`. `type` contains the type of the theorem. @@ -75,17 +99,20 @@ (_, mvarId) ← introSubstEq mvarId trace[Meta.Match.matchEqs] "proveCondEqThm after subst{mvarId}" mvarId := (← mvarId.intros).2 - try mvarId.refl - catch _ => - mvarId ← mvarId.deltaTarget (· == matchDeclName) - mvarId ← mvarId.heqOfEq - go mvarId 0 + reflOrProve mvarId.refl (unfoldAndProve mvarId) instantiateMVars mvar0 where + unfoldAndProve (mvarId : MVarId) : MetaM Unit := do + let mvarId ← mvarId.deltaTarget (· == matchDeclName) + go (← mvarId.heqOfEq) 0 + go (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`" + return #[mvarId]) + <|> (do mvarId.refl; return #[]) <|> (do mvarId.contradiction { genDiseq := true }; return #[])
diff --git a/src/Lean/Meta/Tactic/Refl.lean b/src/Lean/Meta/Tactic/Refl.lean index d2aec16..fd7b4bd 100644 --- a/src/Lean/Meta/Tactic/Refl.lean +++ b/src/Lean/Meta/Tactic/Refl.lean
@@ -39,6 +39,22 @@ mvarId.assign (mkApp2 (mkConst ``Eq.refl us) α lhs) /-- +Proves a goal with `rfl`, provided that no reduction step needs the constructor of a `String` +literal (see `Config.stringLitToCtor`). Otherwise, executes `prove`, and tries `rfl` without this +restriction if `prove` fails. `rfl` must throw an exception if it fails. +-/ +def reflOrProve (rfl : MetaM Unit) (prove : MetaM Unit) : MetaM Unit := do + try + withoutStringLitToCtor rfl + catch _ => + let s ← saveState + try + prove + catch ex => + s.restore + try rfl catch _ => throw ex + +/-- Try to apply `heq_of_eq`. If successful, then return new goal, otherwise return `mvarId`. -/ def _root_.Lean.MVarId.heqOfEq (mvarId : MVarId) : MetaM MVarId :=
diff --git a/src/Lean/Meta/WHNF.lean b/src/Lean/Meta/WHNF.lean index c617a92..39ce5a2 100644 --- a/src/Lean/Meta/WHNF.lean +++ b/src/Lean/Meta/WHNF.lean
@@ -25,7 +25,9 @@ | .lit (.natVal v) => if v == 0 then return mkConst ``Nat.zero else return mkApp (mkConst ``Nat.succ) (mkRawNatLit (v-1)) - | .lit (.strVal v) => + | .lit (.strVal v) => do + unless (← Lean.Meta.getConfig).stringLitToCtor do + throw <| .internal Lean.Meta.stringLitToCtorExceptionId Lean.Meta.whnf (mkApp (mkConst ``String.ofList) (toExpr v.toList)) | e => return e
diff --git a/tests/elab/keyedConfig.lean b/tests/elab/keyedConfig.lean index f25427a..3e5b021 100644 --- a/tests/elab/keyedConfig.lean +++ b/tests/elab/keyedConfig.lean
@@ -66,5 +66,6 @@ (_ : UInt64) <<< _ = a, (_ : UInt64) <<< _ = a, (_ : UInt64) <<< _ = a, (_ : UInt64) <<< _ = a, (_ : UInt64) <<< _ = a, (_ : UInt64) <<< _ = a, - (_ : UInt64) <<< _ = a, (_ : UInt64) <<< _ = a + (_ : UInt64) <<< _ = a, (_ : UInt64) <<< _ = a, + (_ : UInt64) <<< _ = a simp only [UInt64.or_assoc, UInt64.or_comm]
diff --git a/tests/elab/matchEqnsStringLits.lean b/tests/elab/matchEqnsStringLits.lean new file mode 100644 index 0000000..b3750c0 --- /dev/null +++ b/tests/elab/matchEqnsStringLits.lean
@@ -0,0 +1,123 @@ +/-! +Generating the equation lemmas of a definition by `match` on many `String` literals. With 64 +alternatives, generation used to hit the heartbeat limit (#16313). +-/ + +def onStr : String → Nat + | "registered_name_0" => 0 + | "registered_name_1" => 1 + | "registered_name_2" => 2 + | "registered_name_3" => 3 + | "registered_name_4" => 4 + | "registered_name_5" => 5 + | "registered_name_6" => 6 + | "registered_name_7" => 7 + | "registered_name_8" => 8 + | "registered_name_9" => 9 + | "registered_name_10" => 10 + | "registered_name_11" => 11 + | "registered_name_12" => 12 + | "registered_name_13" => 13 + | "registered_name_14" => 14 + | "registered_name_15" => 15 + | "registered_name_16" => 16 + | "registered_name_17" => 17 + | "registered_name_18" => 18 + | "registered_name_19" => 19 + | "registered_name_20" => 20 + | "registered_name_21" => 21 + | "registered_name_22" => 22 + | "registered_name_23" => 23 + | "registered_name_24" => 24 + | "registered_name_25" => 25 + | "registered_name_26" => 26 + | "registered_name_27" => 27 + | "registered_name_28" => 28 + | "registered_name_29" => 29 + | "registered_name_30" => 30 + | "registered_name_31" => 31 + | "registered_name_32" => 32 + | "registered_name_33" => 33 + | "registered_name_34" => 34 + | "registered_name_35" => 35 + | "registered_name_36" => 36 + | "registered_name_37" => 37 + | "registered_name_38" => 38 + | "registered_name_39" => 39 + | "registered_name_40" => 40 + | "registered_name_41" => 41 + | "registered_name_42" => 42 + | "registered_name_43" => 43 + | "registered_name_44" => 44 + | "registered_name_45" => 45 + | "registered_name_46" => 46 + | "registered_name_47" => 47 + | "registered_name_48" => 48 + | "registered_name_49" => 49 + | "registered_name_50" => 50 + | "registered_name_51" => 51 + | "registered_name_52" => 52 + | "registered_name_53" => 53 + | "registered_name_54" => 54 + | "registered_name_55" => 55 + | "registered_name_56" => 56 + | "registered_name_57" => 57 + | "registered_name_58" => 58 + | "registered_name_59" => 59 + | "registered_name_60" => 60 + | "registered_name_61" => 61 + | "registered_name_62" => 62 + | "registered_name_63" => 63 + | _ => 1000 + +example := @onStr.match_1.eq_65 +example := @onStr.eq_65 + +/-! +The equation for the `n+1` alternative does not reduce the nested `match` on `String` literals, +so it is proved by `rfl`. +-/ + +def nested (n : Nat) (s : String) : Nat := + match n with + | 0 => (match s with | "a" => 1 | _ => 2) + | n+1 => n + +/-- +info: @[backward_defeq] theorem nested.eq_3 : ∀ (s : String) (n_2 : Nat), nested n_2.succ s = n_2 := +fun s n_2 => Eq.refl (nested n_2.succ s) +-/ +#guard_msgs in +#print nested.eq_3 + +/-! +A `match` on `String` literals under a binder. The equation is provable only by `rfl`. +-/ + +def underLambda : List (String → Nat) := + [fun s => match s with | "a" => 1 | _ => 2] + +example := @underLambda.eq_1 + +/-! +The equation for a `String` literal alternative is proved with the `match` equation, and not by +`rfl` after unfolding the definition. +-/ + +def lits : String → Nat + | "a" => 0 + | "b" => 1 + | "c" => 2 + | _ => 3 + +/-- +info: theorem lits.eq_3 : lits "c" = 2 := +id + (Eq.mpr + (id + (congrFun' (congrArg Eq (lits.match_1.eq_3 (fun x => Nat) (fun _ => 0) (fun _ => 1) (fun _ => 2) fun x => 3)) 2)) + (Eq.refl 2)) +-/ +#guard_msgs in +set_option pp.proofs true in +#print lits.eq_3
diff --git a/tests/elab_bench/big_match_string.lean b/tests/elab_bench/big_match_string.lean new file mode 100644 index 0000000..356f6dd --- /dev/null +++ b/tests/elab_bench/big_match_string.lean
@@ -0,0 +1,26 @@ +import Lean + +/-! +Generates the equation lemmas of a definition by `match` on many `String` literals with a +catch-all case (#16313). +-/ + +set_option Elab.async false + +open Lean Elab Command + +elab "#test_gen " f:ident n:num : command => do + let n := n.getNat + let cases ← (Array.range n).mapM fun i => + `(Lean.Parser.Term.matchAltExpr| | $(Syntax.mkStrLit s!"registered_name_{i}") => $(Syntax.mkNatLit i)) + let cases := cases.push (← `(Lean.Parser.Term.matchAltExpr| | _ => $(Syntax.mkNatLit n))) + elabCommand (← `(def $f:ident : String → Nat $cases:matchAlt*)) + let some eqns ← liftTermElabM <| Meta.getEqnsFor? f.getId + | throwError "no equation lemmas for `{f}`" + unless eqns.size == n + 1 do + throwError "expected {n + 1} equation lemmas, got {eqns.size}" + +#eval show CommandElabM Unit from do + let bench := (← IO.getEnv "TEST_BENCH") == some "1" + let n := if bench then 128 else 64 + elabCommand (← `(#test_gen f $(Syntax.mkNatLit n)))