diff --git a/docs/usage.md b/docs/usage.md index 06df8bc7..192c8327 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -392,6 +392,8 @@ bun run math bootstrap-lean-eval --help | `freeze-retrieval` | 冻结允许检索的本地源码语料 | | `summarize` | 汇总保存的实验记录 | +`search-lean --query` 和数学库目录支持直接粘贴单个 Lean 名称,例如 `_root_.Matrix.det_mul` 或 `#check @Set.mem_union`。 + `search-lean --goal` 会匹配方向相反的等式和等价命题。结果中的 `"application": "symm"` 表示可尝试用 `exact (定理名 实参).symm`,具体实参和前提由 Lean 检查。 diff --git a/scripts/mathematics/benchmarkTheoremSearch.ts b/scripts/mathematics/benchmarkTheoremSearch.ts index 17910fc8..d7c60b0e 100644 --- a/scripts/mathematics/benchmarkTheoremSearch.ts +++ b/scripts/mathematics/benchmarkTheoremSearch.ts @@ -5,7 +5,7 @@ import { mathDigest, readMathText } from '../../src/math/mathRuntimeIo'; type Declaration = { qualifiedName: string; sourceModule: string }; type QueryCase = { - group: 'zh' | 'en' | 'ranking' | 'control' | 'negative' | 'generatedName'; + group: 'zh' | 'en' | 'ranking' | 'control' | 'negative' | 'generatedName' | 'leanReference'; query: string; expected?: Declaration; }; @@ -25,6 +25,9 @@ const concepts = [ ['Finset.card_union_add_card_inter', 'Mathlib.Data.Finset.Card', '有限集的并集与交集的基数相加等于两集合的基数之和', 'for two finite sets the cardinality of the union plus that of the intersection equals the sum of their cardinalities'], + ['Finset.card_inter_add_card_union', 'Mathlib.Data.Finset.Card', + '有限集的交集与并集的基数相加等于两集合的基数之和', + 'for two finite sets the cardinality of the intersection plus that of the union equals the sum of their cardinalities'], ['MeasureTheory.integral_add', 'Mathlib.MeasureTheory.Integral.Bochner.Basic', '两个可积函数的和的积分等于它们各自的积分相加', 'the integral of the sum of two integrable functions is the sum of their integrals'], ['Int.gcd_eq_gcd_ab', 'Mathlib.Data.Int.GCD', @@ -38,6 +41,16 @@ const concepts = [ ] as const; export const theoremSearchCases: readonly QueryCase[] = [ + ...[ + ['_root_.Set.mem_union', 'Set.mem_union', 'Mathlib.Data.Set.Basic'], + ['_root_.Matrix.det_mul', 'Matrix.det_mul', 'Mathlib.LinearAlgebra.Matrix.Determinant.Basic'], + ['_root_.norm_add_le', 'norm_add_le', 'Mathlib.Analysis.Normed.Group.Basic'], + ["_root_.Real.sqrt_mul'", "Real.sqrt_mul'", 'Mathlib.Analysis.Real.Sqrt'], + ['#check Real.exp_log', 'Real.exp_log', 'Mathlib.Analysis.SpecialFunctions.Log.Basic'], + ['#check @Set.inter_union_distrib_left', 'Set.inter_union_distrib_left', 'Mathlib.Data.Set.Basic'], + ['@Finset.sum_add_distrib', 'Finset.sum_add_distrib', 'Mathlib.Algebra.BigOperators.Group.Finset.Basic'], + ["Real.sqrt_mul'", "Real.sqrt_mul'", 'Mathlib.Analysis.Real.Sqrt'], + ].map(([query, qualifiedName, sourceModule]): QueryCase => ({ group: 'leanReference', query, expected: { qualifiedName, sourceModule } })), ...concepts.flatMap(([qualifiedName, sourceModule, zh, en]): QueryCase[] => { const expected = { qualifiedName, sourceModule }; return [{ group: 'zh', query: zh, expected }, { group: 'en', query: en, expected }]; @@ -45,6 +58,12 @@ export const theoremSearchCases: readonly QueryCase[] = [ ...[ ['the closure of a set equals the set if and only if the set is closed', 'closure_eq_iff_isClosed', 'Mathlib.Topology.Closure'], ['转置矩阵的行列式等于原矩阵的行列式', 'Matrix.det_transpose', 'Mathlib.LinearAlgebra.Matrix.Determinant.Basic'], + ['两个有限集的交集包含于第一个有限集', 'Finset.inter_subset_left', 'Mathlib.Data.Finset.Lattice.Basic'], + ['两个有限集的交集包含于第二个有限集', 'Finset.inter_subset_right', 'Mathlib.Data.Finset.Lattice.Basic'], + ['the first finite set is a subset of the union of the two finite sets', 'Finset.subset_union_left', 'Mathlib.Data.Finset.Lattice.Basic'], + ['the second finite set is a subset of the union of the two finite sets', 'Finset.subset_union_right', 'Mathlib.Data.Finset.Lattice.Basic'], + ['the intersection of two sets is contained in the second set', 'Set.inter_subset_right', 'Mathlib.Data.Set.Basic'], + ['第一个集合包含于两个集合的并集', 'Set.subset_union_left', 'Mathlib.Data.Set.Basic'], ['两个可积函数的差的积分等于各自积分的差', 'MeasureTheory.integral_sub', 'Mathlib.MeasureTheory.Integral.Bochner.Basic'], ['if two integrable functions are ordered almost everywhere then their integrals are ordered', 'MeasureTheory.integral_mono_ae', 'Mathlib.MeasureTheory.Integral.Bochner.Basic'], @@ -64,6 +83,44 @@ export const theoremSearchCases: readonly QueryCase[] = [ export const theoremSearchGoalCases: readonly GoalCase[] = [ ...[ + ["a b : Set α\n⊢ (a ∪ b) = (b ∪ a)","Set.union_comm","Mathlib.Data.Set.Basic"], + ["a b : Set α\n⊢ (a ∩ b) = b ∩ a","Set.inter_comm","Mathlib.Data.Set.Basic"], + ["a b : Set α\n⊢ (a ∩ b) ⊆ (a)","Set.inter_subset_left","Mathlib.Data.Set.Basic"], + ["a b : Set α\n⊢ (b) ⊆ (a ∪ b)","Set.subset_union_right","Mathlib.Data.Set.Basic"], + ["x y : ℝ\n⊢ (|x * y|) = (|x| * |y|)","abs_mul","Mathlib.Algebra.Order.Ring.Abs"], + ['x y : ℝ\n⊢ |x * y| = |x| * |y|', 'abs_mul', 'Mathlib.Algebra.Order.Ring.Abs'], + ['x y : ℝ\n⊢ abs (x * y) = abs x * abs y', 'abs_mul', 'Mathlib.Algebra.Order.Ring.Abs'], + ['x y : ℝ\n⊢ abs (x / y) = |x| / |y|', 'abs_div', 'Mathlib.Algebra.Order.Field.Basic'], + ['x y : ℝ\n⊢ abs (x ^ 2) = x ^ 2', 'abs_sq', 'Mathlib.Algebra.Order.Ring.Abs'], + ['x y : ℝ\n⊢ |x| * |y| = abs (x * y)', 'abs_mul', 'Mathlib.Algebra.Order.Ring.Abs'], + ["x : ℝ\n⊢ (Real.log ∘ Real.exp) x = x", "Real.log_exp", "Mathlib.Analysis.SpecialFunctions.Log.Basic"], + ["x : ℝ\nh : 0 < x\n⊢ (Real.exp ∘ Real.log) x = x", "Real.exp_log", "Mathlib.Analysis.SpecialFunctions.Log.Basic"], + ["x : ℝ\n⊢ (Real.tan ∘ Real.arctan) x = x", "Real.tan_arctan", "Mathlib.Analysis.SpecialFunctions.Trigonometric.Arctan"], + ["x : ℝ\nh₁ : -1 ≤ x\nh₂ : x ≤ 1\n⊢ (Real.sin ∘ Real.arcsin) x = x", "Real.sin_arcsin", "Mathlib.Analysis.SpecialFunctions.Trigonometric.Inverse"], + ["x : ℝ\n⊢ (Real.sinh ∘ Real.arsinh) x = x", "Real.sinh_arsinh", "Mathlib.Analysis.SpecialFunctions.Arsinh"], + ["x y : ℝ\nh : 0 < x + y\n⊢ x + y = (Real.exp ∘ Real.log) (x + y)", "Real.exp_log", "Mathlib.Analysis.SpecialFunctions.Log.Basic"], + ["α β : Type\nφ : α → β\np q : Set β\n⊢ φ ⁻¹' (p ∪ q) = φ ⁻¹' p ∪ φ ⁻¹' q", 'Set.preimage_union', 'Mathlib.Data.Set.Image'], + ["α β : Type\nφ : α → β\np q : Set β\n⊢ Set.preimage φ (p ∪ q) = Set.preimage φ p ∪ Set.preimage φ q", 'Set.preimage_union', 'Mathlib.Data.Set.Image'], + ["α β : Type\nφ : α → β\np q : Set β\n⊢ Set.preimage φ (p ∩ q) = Set.preimage φ p ∩ Set.preimage φ q", 'Set.preimage_inter', 'Mathlib.Data.Set.Image'], + ["α β : Type\nφ : α → β\n⊢ Set.preimage φ ∅ = ∅", 'Set.preimage_empty', 'Mathlib.Data.Set.Image'], + ["α β : Type\nφ : α → β\ns t : Set α\n⊢ Set.image φ (s ∪ t) = Set.image φ s ∪ Set.image φ t", 'Set.image_union', 'Mathlib.Data.Set.Image'], + ["α β : Type\nφ : α → β\ns t : Set α\n⊢ Set.image φ (s ∩ t) ⊆ φ '' s ∩ φ '' t", 'Set.image_inter_subset', 'Mathlib.Data.Set.Image'], + ["α β : Type\nφ : α → β\ns : Set α\nt : Set β\n⊢ Set.image φ s ⊆ t ↔ s ⊆ Set.preimage φ t", 'Set.image_subset_iff', 'Mathlib.Data.Set.Image'], + ["α β : Type\nφ : α → β\n⊢ φ '' ∅ = ∅", 'Set.image_empty', 'Mathlib.Data.Set.Image'], + ["α : Type u\nA B : Set α\nx : α\n⊢ x ∈ Aᶜ ↔ x ∉ A", "Set.mem_compl_iff", "Mathlib.Data.Set.Operations"], + ["α : Type u\nA B : Set α\nx : α\n⊢ (A ∪ B)ᶜ = Aᶜ ∩ Bᶜ", "Set.compl_union", "Mathlib.Order.BooleanAlgebra.Set"], + ["α : Type u\nA B : Set α\nx : α\n⊢ (A ∩ B)ᶜ = Aᶜ ∪ Bᶜ", "Set.compl_inter", "Mathlib.Order.BooleanAlgebra.Set"], + ["α : Type u\nA B : Set α\nx : α\n⊢ Aᶜ ⊆ Bᶜ ↔ B ⊆ A", "Set.compl_subset_compl", "Mathlib.Order.BooleanAlgebra.Set"], + ["α : Type u\ninst : Fintype α\ninst₂ : DecidableEq α\nA B : Finset α\nx : α\n⊢ x ∈ Aᶜ ↔ x ∉ A", "Finset.mem_compl", "Mathlib.Data.Finset.BooleanAlgebra"], + ["α : Type u\ninst : Fintype α\ninst₂ : DecidableEq α\nA B : Finset α\nx : α\n⊢ (A ∪ B)ᶜ = Aᶜ ∩ Bᶜ", "Finset.compl_union", "Mathlib.Data.Finset.BooleanAlgebra"], + ["α : Type u\ninst : Fintype α\ninst₂ : DecidableEq α\nA B : Finset α\nx : α\n⊢ (A ∩ B)ᶜ = Aᶜ ∪ Bᶜ", "Finset.compl_inter", "Mathlib.Data.Finset.BooleanAlgebra"], + ["α : Type u\ninst : Fintype α\ninst₂ : DecidableEq α\nA B : Finset α\nx : α\n⊢ Aᶜ ⊆ Bᶜ ↔ B ⊆ A", "Finset.compl_subset_compl", "Mathlib.Data.Finset.BooleanAlgebra"], + ["α : Type u\nx : α\nu v : Set α\n⊢ x ∈ u \\ v ↔ x ∈ u ∧ x ∉ v", "Set.mem_sdiff", "Mathlib.Data.Set.Operations"], + ["α : Type u\nx : α\nu v : Set α\n⊢ u \\ u = ∅", "Set.sdiff_self", "Mathlib.Order.BooleanAlgebra.Set"], + ["α : Type u\nx : α\nu v : Set α\n⊢ u \\ ∅ = u", "Set.sdiff_empty", "Mathlib.Order.BooleanAlgebra.Set"], + ["α : Type u\ninst : DecidableEq α\nx : α\nu v : Finset α\n⊢ x ∈ u \\ v ↔ x ∈ u ∧ x ∉ v", "Finset.mem_sdiff", "Mathlib.Data.Finset.SDiff"], + ["α : Type u\ninst : DecidableEq α\nx : α\nu v : Finset α\n⊢ u \\ u = ∅", "Finset.sdiff_self", "Mathlib.Data.Finset.SDiff"], + ["α : Type u\ninst : DecidableEq α\nx : α\nu v : Finset α\n⊢ u \\ ∅ = u", "Finset.sdiff_empty", "Mathlib.Data.Finset.SDiff"], ['α : Type u\ninst : MeasurableSpace α\ns t : Set α\nμ : MeasureTheory.Measure α\n⊢ μ (s ∪ t) ≤ μ s + μ t', 'MeasureTheory.measure_union_le', 'Mathlib.MeasureTheory.OuterMeasure.Basic'], ['E : Type u\ninst : SeminormedAddCommGroup E\ninst_1 : InnerProductSpace ℝ E\nx y : E\n⊢ ‖⟪x, y⟫‖ ≤ ‖x‖ * ‖y‖', @@ -116,6 +173,12 @@ export const theoremSearchGeneratedNameCases: readonly QueryCase[] = theoremSear })); export const theoremSearchOrderGoalCases: readonly GoalCase[] = [ + ["α : Type u\ns t : Set α\n⊢ s ∪ t ⊇ s", "Set.subset_union_left", "Mathlib.Data.Set.Basic"], + ["α : Type u\ns t : Set α\n⊢ t ⊇ s ∩ t", "Set.inter_subset_right", "Mathlib.Data.Set.Basic"], + ["α : Type u\ns t : Set α\na : α\nh : a ∉ s\n⊢ insert a s ⊃ s", "Set.ssubset_insert", "Mathlib.Data.Set.Insert"], + ["α : Type u\ninst : DecidableEq α\ns t : Finset α\n⊢ s ∪ t ⊇ s", "Finset.subset_union_left", "Mathlib.Data.Finset.Lattice.Basic"], + ["α : Type u\ninst : DecidableEq α\ns t : Finset α\n⊢ t ⊇ s ∩ t", "Finset.inter_subset_right", "Mathlib.Data.Finset.Lattice.Basic"], + ["α : Type u\ninst : DecidableEq α\ns t : Finset α\na : α\nh : a ∉ s\n⊢ insert a s ⊃ s", "Finset.ssubset_insert", "Mathlib.Data.Finset.Insert"], ['E : Type u\ninst : SeminormedAddGroup E\nx : E\n⊢ ‖x‖ ≥ 0', 'norm_nonneg', 'Mathlib.Analysis.Normed.Group.Basic'], ['x : ℝ\n⊢ √x >= 0', 'Real.sqrt_nonneg', 'Mathlib.Analysis.Real.Sqrt'], @@ -148,6 +211,11 @@ export const theoremSearchSpecializedGoalCases: readonly GoalCase[] = [ // The same conclusion can have separate lemmas for different available premises. export const theoremSearchSpecializedPremiseCases: readonly GoalCase[] = [ + ['x y : ℝ\nh : -1 > x + y\n⊢ 0 < Real.log (x + y)', 'Real.log_pos_of_lt_neg_one', 'Mathlib.Analysis.SpecialFunctions.Log.Basic'], + ['x y : ℝ\nh : 0 > x + y ∧ x + y > -1\n⊢ Real.log (x + y) < 0', 'Real.log_neg_of_lt_zero', 'Mathlib.Analysis.SpecialFunctions.Log.Basic'], + ['x : ℝ\nh : 1 > x ∧ x > 0\n⊢ Real.log x < 0', 'Real.log_neg', 'Mathlib.Analysis.SpecialFunctions.Log.Basic'], + ['a b c : ℝ\nh : b + c ≥ 0\n⊢ √(a * (b + c)) = √a * √(b + c)', "Real.sqrt_mul'", 'Mathlib.Analysis.Real.Sqrt'], + ['a b c : ℝ\nh : b + c ≥ 0\n⊢ √(a / (b + c)) = √a / √(b + c)', "Real.sqrt_div'", 'Mathlib.Analysis.Real.Sqrt'], ['x y : ℝ\nh : x + y < -1\n⊢ 0 < Real.log (x + y)', 'Real.log_pos_of_lt_neg_one', 'Mathlib.Analysis.SpecialFunctions.Log.Basic'], ['x y : ℝ\nh : 1 < x + y\n⊢ 0 < Real.log (x + y)', 'Real.log_pos', 'Mathlib.Analysis.SpecialFunctions.Log.Basic'], ['x y : ℝ\nh₀ : x + y < 0\nh₁ : -1 < x + y\n⊢ Real.log (x + y) < 0', 'Real.log_neg_of_lt_zero', 'Mathlib.Analysis.SpecialFunctions.Log.Basic'], @@ -195,7 +263,7 @@ function run(workspace: string, corpusPath: string) { const { queries: [result] } = searchMathRetrievalCorpusBatch(workspace, corpus, [''], 3, test.goal); cases.push(scoreCase(test, result!)); } - const groups = ['zh', 'en', 'ranking', 'control', 'goal', 'algebraGoal', 'generatedName', 'generatedGoal', + const groups = ['zh', 'en', 'ranking', 'control', 'leanReference', 'goal', 'algebraGoal', 'generatedName', 'generatedGoal', 'orderGoal', 'specializedGoal', 'specializedPremise', 'symmetricGoal'] as const; const summary = Object.fromEntries(groups.map(group => { const items = cases.filter(item => item.group === group && item.expected); diff --git a/src/math/frozenLibraryQuery.ts b/src/math/frozenLibraryQuery.ts index 019db0cf..964bc908 100644 --- a/src/math/frozenLibraryQuery.ts +++ b/src/math/frozenLibraryQuery.ts @@ -1,3 +1,5 @@ +import { leanLookupReference } from './leanSyntax'; + const chinese = /\p{Script=Han}/u; const words = new Intl.Segmenter('zh', { granularity: 'word' }); const filler = new Set([ @@ -35,11 +37,12 @@ export function frozenLibraryQuery(query: string) { || naturalTerms.length === 1 && chinese.test(query) && !chinese.test(naturalTerms[0]!) ); - const identifier = query.trim().toLowerCase().replace(/^_root_\./u, ''); + const reference = leanLookupReference(query); + const identifier = reference?.name.toLowerCase(); return (searchable: string, name: string, prepared?: () => FrozenLibrarySearchWords): number => { const qualified = name.toLowerCase(), shortName = qualified.split('.').at(-1); - if (identifier === qualified || identifier === shortName + if (identifier === qualified || (!reference?.rooted && identifier === shortName) || (useNatural && naturalTerms.length === 1 && naturalTerms[0] === shortName)) return 3; const lower = searchable.toLowerCase(); if (literalWords.every(term => lower.includes(term))) return 2; diff --git a/src/math/leanGoalPremises.ts b/src/math/leanGoalPremises.ts index 8f7ca53c..b009e7bb 100644 --- a/src/math/leanGoalPremises.ts +++ b/src/math/leanGoalPremises.ts @@ -1,8 +1,10 @@ -import { isSimpleLeanName, leanConclusionTokens, leanSurfaceTokens, leanTopLevelTokenIndexes } from './leanSyntax'; +import { isSimpleLeanName, leanConclusionTokens, leanSurfaceTokens, leanTopLevelTokenIndexes, reversedLeanComparisons } from './leanSyntax'; type ConclusionLocals = ReadonlyMap; type Substitution = ReadonlyMap; -const comparisons = new Set(['=', '≠', '<', '≤', '>', '≥', '∈', '∉', '⊆', '∣']); +const comparisons = new Set(['=', '≠', '<', '≤', '∈', '∉', '⊆', '⊂', '∣', ...reversedLeanComparisons.keys()]); +// These tokens can extend the scope of an operand past a following infix operator. +const scopeTokens = new Set(['→', '->', '↔', '<->', '∨', '∀', 'forall', '∃', 'exists', '∃!', 'fun', 'λ', 'let', 'if', 'match', 'by', 'show', ':', ',']); function unwrap(tokens: string[]): string[] { while (tokens[0] === '(' && tokens.at(-1) === ')' && leanTopLevelTokenIndexes(tokens).length === 2) @@ -49,10 +51,12 @@ function premiseKey(premise: string[], locals: ConclusionLocals, substitution?: if (binder === -1) { const top = leanTopLevelTokenIndexes(pattern); const operators = top.filter(index => comparisons.has(pattern[index])); - if (operators.length === 1 && !top.some(index => ['→', '↔', '<->', '∧', '∨', '¬', ','].includes(pattern[index]))) { + if (operators.length === 1 && !top.some(index => scopeTokens.has(pattern[index]) || ['∧', '¬'].includes(pattern[index]))) { const index = operators[0]; const left = unwrap(pattern.slice(0, index)); const right = unwrap(pattern.slice(index + 1)); + const reverse = reversedLeanComparisons.get(pattern[index]); + if (reverse) return [...right, reverse, ...left].join(' '); return [...left, pattern[index], ...right].join(' '); } } @@ -67,8 +71,21 @@ export function goalPremiseKeys(context: string, locals: ConclusionLocals) { const names = declaration[1].split(/\s+/u); if (names.some(name => locals.has(name))) continue; const type = context.slice(declaration.index + declaration[0].length, declarations[index + 1]?.index); - const key = premiseKey(leanSurfaceTokens(type), locals); - if (key) keys.add(key); + // Keep the whole hypothesis as well as facts obtainable by And.left / And.right. + const pending = [leanSurfaceTokens(type)]; + while (pending.length) { + const tokens = unwrap(pending.pop()!); + const key = premiseKey(tokens, locals); + if (key) keys.add(key); + const top = leanTopLevelTokenIndexes(tokens); + if (top.some(i => scopeTokens.has(tokens[i]))) continue; + let start = 0; + for (const i of top) if (tokens[i] === '∧') { + pending.push(tokens.slice(start, i)); + start = i + 1; + } + if (start) pending.push(tokens.slice(start)); + } } return keys; } diff --git a/src/math/leanSyntax.ts b/src/math/leanSyntax.ts index bbcbb7f8..2e68677e 100644 --- a/src/math/leanSyntax.ts +++ b/src/math/leanSyntax.ts @@ -2,6 +2,14 @@ export const isSimpleLeanName = (value: unknown): value is string => typeof value === 'string' && /^[\p{L}_][\p{L}\p{M}\p{N}_'?!]*(?:\.[\p{L}_][\p{L}\p{M}\p{N}_'?!]*)*$/u.test(value); +/** Recognize a single pasted declaration reference, without interpreting Lean expressions. */ +export function leanLookupReference(query: string) { + const reference = query.trim().replace(/^#check\s+/u, '').replace(/^@/u, ''); + if (!isSimpleLeanName(reference)) return undefined; + const rooted = reference.startsWith('_root_.'); + return { name: rooted ? reference.slice(7) : reference, rooted }; +} + /** Ordinary qualified names explicitly written in prose; preserve first mention and normalize root prefixes. */ export function qualifiedLeanReferences(text: string): string[] { return [...new Set([...text.matchAll(/(?', '<'], ['≥', '≤'], ['>=', '≤'], ['⊇', '⊆'], ['⊃', '⊂']]); + /** Tokens used for ranking printed Lean types. */ export const leanSurfaceTokens = (value: string): string[] => - value.match(/[\p{L}_][\p{L}\p{M}\p{N}_'.]*|\d+|<->|->|<=|>=|\S/gu) ?? []; + // Unicode classifies ᶜ as a letter, but Mathlib uses it as a postfix operator. + value.replaceAll('ᶜ', ' ᶜ ').match(/[\p{L}_][\p{L}\p{M}\p{N}_'.]*|\d+|⁻¹'|''|<->|->|<=|>=|\S/gu) ?? []; export function leanTopLevelTokenIndexes(tokens: readonly string[]): number[] { const indexes: number[] = []; diff --git a/src/math/mathRetrievalCorpus.ts b/src/math/mathRetrievalCorpus.ts index 91fd52cc..0551d51c 100644 --- a/src/math/mathRetrievalCorpus.ts +++ b/src/math/mathRetrievalCorpus.ts @@ -11,8 +11,8 @@ import { mathlibAdditiveTheorems, type MathlibAdditiveTheorem } from './mathlibA import { goalPremiseKeys, matchedGoalPremises } from './leanGoalPremises'; import { goalSpecialization } from './leanGoalSpecialization'; import { mathConceptSurfaces, mathSearchConcepts } from './mathSearchConcepts'; -import { isSimpleLeanName, maskLeanCommentsAndStrings, leanScopeCommands, leanScopeNamespace, updateLeanScopes, - leanSurfaceTokens, leanTopLevelTokenIndexes, leanConclusionTokens, type LeanScope } from './leanSyntax'; +import { isSimpleLeanName, leanLookupReference, maskLeanCommentsAndStrings, leanScopeCommands, leanScopeNamespace, updateLeanScopes, + leanSurfaceTokens, leanTopLevelTokenIndexes, leanConclusionTokens, reversedLeanComparisons, type LeanScope } from './leanSyntax'; const MAX_FILE_BYTES = MAX_INSTALLED_SOURCE_FILE_BYTES; const digestSchema = z.string().regex(/^[0-9a-f]{64}$/u); const relativeFileSchema = z @@ -291,6 +291,7 @@ function searchableDeclarations(source: string) { } const commands = leanScopeCommands(clean); const scopes: LeanScope[] = []; + const namespacesWithAbs = new Set(); const context: string[][] = [[]]; let command = commands.next(); let sourceLine = 1; @@ -328,16 +329,22 @@ function searchableDeclarations(source: string) { sourceLine++; newline = source.indexOf('\n', newline + 1); } + const namespace = leanScopeNamespace(scopes); const qualifiedName = declaration.name.startsWith('_root_.') ? declaration.name.slice('_root_.'.length) : - [leanScopeNamespace(scopes), declaration.name].filter(Boolean).join('.'); + [namespace, declaration.name].filter(Boolean).join('.'); const sourceContext = context.flat().join('\n'); + // Use the lexical namespace even for a theorem whose own name starts with _root_. + if (qualifiedName.endsWith('.abs')) namespacesWithAbs.add(qualifiedName.slice(0, -4)); + const shadowedAbs = namespacesWithAbs.size > 0 && declaration.declarationType.includes('abs') && + [...namespacesWithAbs].some(ns => ns === namespace || namespace.startsWith(ns + '.') || + sourceContext.split('\n').some(line => line.startsWith('open ') && line.slice(5).split(/\s+/u).includes(ns))); let doc: (typeof docs)[number] | undefined; while (docs[nextDoc]?.end <= declaration.startOffset) doc = docs[nextDoc++]; // A declaration can have attributes or modifiers between its doc comment and keyword. // Ignore comments preceding another command or embedded in a proof or a string. const docComment = doc && /^\s*(?:@\[[^\]]*\]\s*|(?:private|protected|public|noncomputable|nonrec|partial|unsafe|local|scoped|meta)\s+)*$/u .test(clean.slice(doc.end, declaration.startOffset)) ? source.slice(doc.start + 3, Math.min(doc.end - 2, doc.start + 3000)) : undefined; - return { ...declaration, qualifiedName, sourceLine, sourceContext: sourceContext.slice(0, 2000), + return { ...declaration, ...(shadowedAbs ? { shadowedAbs: true } : {}), qualifiedName, sourceLine, sourceContext: sourceContext.slice(0, 2000), contextTruncated: sourceContext.length > 2000, docComment }; }); } @@ -347,7 +354,7 @@ export type MathRetrievalCache = Readonly<{ directory: string; implementation: s /** Cache parsed hints only; current frozen source verification always runs first. */ function indexedDeclarations(source: VerifiedMathRetrievalSource, cache?: MathRetrievalCache) { if (!cache) return searchableDeclarations(source.source); - const key = mathDigest(`math-retrieval-index.v3\0${cache.implementation}\0${source.sha256}`); + const key = mathDigest(`math-retrieval-index.v4\0${cache.implementation}\0${source.sha256}`); const file = path.join(cache.directory, `${key}.json`); const signature = (payload: string) => crypto.createHmac('sha256', cache.secret).update(key).update('\0').update(payload).digest('hex'); try { @@ -433,10 +440,139 @@ function goalNotationBinders(tokens: readonly string[]) { return { binders, memberships }; } +const setImageOperators = new Map([['Set.image', "''"], ['Set.preimage', "⁻¹'"]]); +const applicationBoundaries = new Set(['=', '≠', '⊆', '⊇', '⊂', '⊃', '∈', '∉', '∪', '∩', '\\', '↔', '<->', '∧', '∨', ',']); + +// Exclusive end of one parenthesized argument; return start if it is unclosed. +function parenthesizedEnd(tokens: string[], start: number) { + let depth = 0; + for (let i = start; i < tokens.length; i++) { + if (tokens[i] === '(') depth++; + else if (tokens[i] === ')' && --depth === 0) return i + 1; + } + return start; +} + +const absoluteValueToken = '|·|'; +const scalarOperators = new Set(['+', '-', '*', '/', '^']); + +/** Outer parentheses around a complete term operand do not change a comparison. */ +function normalizeComparisonOperands(tokens: string[]) { + if (tokens[0] !== '(' && tokens.at(-1) !== ')') return tokens; + const comparisons = leanTopLevelTokenIndexes(tokens).filter(i => + ['=', '≠', '<', '>', '<=', '>=', '≤', '≥', '⊆', '⊇', '⊂', '⊃', '∈', '∉', '∣'].includes(tokens[i])); + if (comparisons.length !== 1) return tokens; + const unwrap = (side: string[]) => { + let start = 0, end = side.length; + while (side[start] === '(' && side[end - 1] === ')' && parenthesizedEnd(side, start) === end) { + start++; + end--; + } + if (!start) return side; + const term = side.slice(start, end); + // Tuples, type ascriptions and binders can require these parentheses. + const simple = term.length && leanTopLevelTokenIndexes(term).every(i => { + const t = term[i]; + return isSimpleLeanName(t) ? !['fun', 'let', 'if', 'match', 'by', 'do', 'show', 'forall', 'exists', 'λ'].includes(t) + : /^\d+$/u.test(t) || scalarOperators.has(t) || ['(', ')', '∩', '∪', '\\', 'ᶜ', '‖', '|', '√', '•'].includes(t); + }); + return simple ? term : side; + }; + const index = comparisons[0]; + return [...unwrap(tokens.slice(0, index)), tokens[index], ...unwrap(tokens.slice(index + 1))]; +} + +const scalarBoundary = (token: string) => scalarOperators.has(token) || applicationBoundaries.has(token) || + ['<', '>', '≤', '≥', '<=', '>='].includes(token); + +/** Align ordinary scalar expressions in bars and in a unary application of abs. */ +function normalizeAbsoluteValues(tokens: string[], named: boolean) { + if (!tokens.includes('|') && !tokens.includes('_root_.abs') && !(named && tokens.includes('abs'))) return tokens; + // These constructs introduce local names or use bars to separate patterns. + if (tokens.some(t => ['match', 'fun', 'λ', 'let', '∑', '∏', '∫', '{'].includes(t))) return tokens; + const result: string[] = []; + for (let i = 0; i < tokens.length; i++) { + const t = tokens[i]; + if ((t === '|' || t === '_root_.abs' || named && t === 'abs') && + (i === 0 || tokens[i - 1] === '(' || scalarBoundary(tokens[i - 1]))) { + const start = i + 1; + let end = start; + if (t === '|') { + // Stay inside this operand; never pair bars across a relation or unmatched parenthesis. + let depth = 0; + for (; end < tokens.length; end++) { + const part = tokens[end]; + if (part === '(') depth++; + else if (part === ')' && depth > 0) depth--; + else if (!isSimpleLeanName(part) && !/^\d+$/u.test(part) && !scalarOperators.has(part)) break; + } + if (depth || tokens[end] !== '|' || end === start) end = start; + } else if (tokens[start] === '(') end = parenthesizedEnd(tokens, start); + else if (isSimpleLeanName(tokens[start]) || /^\d+$/u.test(tokens[start] ?? '')) end++; + const next = t === '|' ? end + 1 : end; + if (end > start && (next === tokens.length || tokens[next] === ')' || scalarBoundary(tokens[next]))) { + const wrapped = tokens[start] === '(' && parenthesizedEnd(tokens, start) === end; + const operand = wrapped ? tokens.slice(start + 1, end - 1) : tokens.slice(start, end); + result.push(absoluteValueToken, '(', ...operand, ')'); + i = next - 1; + continue; + } + } + result.push(t); + } + return result; +} + +/** Recognize fully applied Set.image / Set.preimage with an atomic function argument. */ +function normalizeSetImageApplications(tokens: string[]) { + if (!tokens.some(token => setImageOperators.has(token))) return tokens; + const result = [...tokens]; + for (let i = 0; i + 2 < tokens.length; i++) { + const operator = setImageOperators.get(tokens[i]); + if (!operator || !isSimpleLeanName(tokens[i + 1]) || + (i > 0 && tokens[i - 1] !== '(' && !applicationBoundaries.has(tokens[i - 1]))) continue; + let end = i + 2; + if (tokens[end] === '(') { + end = parenthesizedEnd(tokens, end); + if (end === i + 2) continue; + } else if (isSimpleLeanName(tokens[end]) || tokens[end] === '∅') end++; + else continue; + // Keep partial applications, extra arguments and postfix operators in their original grouping. + if (end < tokens.length && tokens[end] !== ')' && !applicationBoundaries.has(tokens[end])) continue; + result[i] = tokens[i + 1]; + result[i + 1] = operator; + } + return result; +} + +/** Expand an applied composition of named functions, without changing the grouping of a surrounding application. */ +function normalizeAppliedComposition(tokens: string[]) { + if (!tokens.includes('∘')) return tokens; + const result: string[] = []; + for (let i = 0; i < tokens.length; i++) { + if (tokens[i] === '(' && tokens[i + 2] === '∘' && tokens[i + 4] === ')' && + isSimpleLeanName(tokens[i + 1]) && isSimpleLeanName(tokens[i + 3]) && + (i === 0 || tokens[i - 1] === '(' || applicationBoundaries.has(tokens[i - 1]))) { + const start = i + 5; + let end = start; + if (tokens[start] === '(') end = parenthesizedEnd(tokens, start); + else if (isSimpleLeanName(tokens[start]) || /^\d+$/u.test(tokens[start] ?? '')) end++; + if (end > start && (end === tokens.length || tokens[end] === ')' || applicationBoundaries.has(tokens[end]))) { + result.push(tokens[i + 1], '(', tokens[i + 3], ...tokens.slice(start, end), ')'); + i = end - 1; + continue; + } + } + result.push(tokens[i]); + } + return result; +} + /** Surface syntax ranks lookup hints; Lean still decides whether a premise applies. */ function goalRanker(goal: string) { const relations: Record = { '=': 'Eq', '≠': 'Ne', '<': 'LT.lt', '>': 'GT.gt', '≤': 'LE.le', '≥': 'GE.ge', - '<=': 'LE.le', '>=': 'GE.ge', '∈': 'Membership.mem', '⊆': 'Subset', '∣': 'Dvd.dvd', + '<=': 'LE.le', '>=': 'GE.ge', '∈': 'Membership.mem', '⊆': 'Subset', '⊇': 'Superset', + '⊂': 'SSubset', '⊃': 'SSuperset', '∣': 'Dvd.dvd', '∧': 'And', '∨': 'Or', '↔': 'Iff', '<->': 'Iff', '¬': 'Not' }; const aliases: Record = { 'ℕ': 'Nat', 'ℤ': 'Int', 'ℚ': 'Rat', 'ℝ': 'Real', 'ℂ': 'Complex' }; const notation = new Map([['√', 'sqrt'], ['#', 'card']]); @@ -444,7 +580,7 @@ function goalRanker(goal: string) { const wideScope = new Set(['→', '->', '∃', 'exists', '∀', 'forall', 'if', 'match', 'fun', 'let', 'show', 'by', 'do']); const identifiers = /[\p{L}_][\p{L}\p{M}\p{N}_'.]*/gu; type LocalType = { kind: 'parameter' | 'compound' } | { kind: 'named'; name: string }; - const shape = (source: string, context = '', declaration = false, reverse = false) => { + const shape = (source: string, context = '', { declaration = false, reverse = false, shadowedAbs = false } = {}) => { const clean = maskLeanCommentsAndStrings(source); const scope = context ? `${context.replace(/^open\s.*$/gmu, '')}\n${clean}` : clean; const bound = new Set(); @@ -479,7 +615,9 @@ function goalRanker(goal: string) { } tokens = colon === undefined ? [] : tokens.slice(colon + 1); } - tokens = leanConclusionTokens(tokens).tokens; + tokens = normalizeAppliedComposition(normalizeComparisonOperands(leanConclusionTokens(tokens).tokens)); + if (!bound.has('Set')) tokens = normalizeSetImageApplications(tokens); + tokens = normalizeAbsoluteValues(tokens, !bound.has('abs') && !shadowedAbs); let { binders, memberships } = goalNotationBinders(tokens); let outerIndexes = leanTopLevelTokenIndexes(tokens).filter(index => !memberships.has(index)); const relationIndexes = outerIndexes.filter(index => Object.hasOwn(relations, tokens[index])); @@ -501,8 +639,8 @@ function goalRanker(goal: string) { if (index > 0 && index < tokens.length - 1) { if (operator === '<=') { tokens[index] = '≤'; - } else if (operator === '≥' || operator === '>=' || operator === '>') { - tokens = [...tokens.slice(index + 1), operator === '>' ? '<' : '≤', ...tokens.slice(0, index)]; + } else if (reversedLeanComparisons.has(operator)) { + tokens = [...tokens.slice(index + 1), reversedLeanComparisons.get(operator)!, ...tokens.slice(0, index)]; ({ binders, memberships } = goalNotationBinders(tokens)); outerIndexes = leanTopLevelTokenIndexes(tokens).filter(index => !memberships.has(index)); } @@ -574,40 +712,45 @@ function goalRanker(goal: string) { const needed = Math.min(2, targetAnchors.length); const headSymbols = Object.keys(relations).filter(symbol => relations[symbol] === target.head); if (target.head === 'Exists') headSymbols.push('∃'); - if (target.head === 'LE.le') headSymbols.push('≥', '>='); - if (target.head === 'LT.lt') headSymbols.push('>'); + for (const [reverse, forward] of reversedLeanComparisons) + if (relations[forward] === target.head) headSymbols.push(reverse); const anchorsInSource = targetAnchors.map(term => ({ word: term.toLowerCase(), symbol: sourceNotation.get(term) })); // A distinctive notation may stand in for a named constant. Require the // complete normalized conclusion for this route, since the operators alone // are shared by many different lemmas. const notationAnchors = [...new Set(target.tokens.flatMap((token, index) => { + if (token === absoluteValueToken) return [token]; if (token === '⁻' && target.tokens[index + 1] === '¹') return ['⁻¹']; - return ['∪', '∩', '⊆', '∫', '⟪', '∣', '‖', '•', '∑', '∏'].includes(token) ? [token] : []; + if (token === "''" || token === "⁻¹'") return [token]; + return ['∪', '∩', '⊆', '⊂', '\\', 'ᶜ', '∫', '⟪', '∣', '‖', '•', '∑', '∏'].includes(token) ? [token] : []; }))]; - const notationMatch = (source: string) => notationAnchors.length > 0 && - notationAnchors.every(symbol => source.includes(symbol)); + const notationMatch = (source: string, raw = false) => notationAnchors.length > 0 && + notationAnchors.every(symbol => source.includes(symbol) || + raw && symbol === absoluteValueToken && (source.includes('|') || source.includes('abs')) || + symbol === "''" && source.includes('set.image') || symbol === "⁻¹'" && source.includes('set.preimage') || + symbol === '⊆' && source.includes('⊇') || symbol === '⊂' && source.includes('⊃')); const goalForm = (shape: typeof target, symmetry: boolean) => ({ ...shape, symmetry, premises: goalPremiseKeys(shape.localContext, shape.locals), specialize: goalSpecialization(shape.patternTokens, shape.canReverse && shape.head === 'Eq'), }); const direct = goalForm(target, false); const reversed = target.canReverse && (needed > 0 || notationAnchors.length > 0) - ? goalForm(shape(goal, '', false, true), true) : undefined; + ? goalForm(shape(goal, '', { reverse: true }), true) : undefined; return { mayMatch(source: string) { if (!target.head || (!needed && !notationAnchors.length)) return false; if (headSymbols.length && !headSymbols.some(symbol => source.includes(symbol)) && !source.includes(target.head.toLowerCase())) return false; - if (notationMatch(source)) return true; + if (notationMatch(source, true)) return true; let matched = 0; for (const { word, symbol } of anchorsInSource) { if ((source.includes(word) || symbol?.test(source)) && ++matched === needed) return true; } return false; }, - assess(header: string, context: string) { + assess(header: string, context: string, shadowedAbs = false) { const boundedHeader = header.slice(0, 4000); - const candidate = shape(boundedHeader, context, true); + const candidate = shape(boundedHeader, context, { declaration: true, shadowedAbs }); const matchingHead = Boolean(target.head && target.head === candidate.head); const anchors = targetAnchors.filter(term => candidate.anchors.has(term)).length; const anchored = needed > 0 && anchors >= needed; @@ -673,7 +816,8 @@ export function searchMathRetrievalCorpusBatch(root: string, value: unknown, que const compareMatches = (a: Match, b: Match) => b.score - a.score || compare(a.name, b.name) || compare(a.sourceModule, b.sourceModule) || compare(a.sourceFile, b.sourceFile); const parsed = queries.map(query => { - const normalized = query.toLowerCase(); + const reference = leanLookupReference(query); + const normalized = (reference?.name ?? query).toLowerCase(); const terms = [...new Set(searchWords(normalized))]; if ((!terms.length && !(goal && query === '')) || Buffer.byteLength(query) > 256) throw new Error('math_search_invalid_query'); const aliases = new Map>(); @@ -684,7 +828,7 @@ export function searchMathRetrievalCorpusBatch(root: string, value: unknown, que } const docTerms = terms.filter(term => !docStopwords.has(term)); return { query, terms, docTerms, aliases, concepts: mathSearchConcepts(query), - exact: normalized.trim(), totalMatches: 0, matches: [] as Match[] }; + exact: normalized.trim(), rooted: reference?.rooted, totalMatches: 0, matches: [] as Match[] }; }); if (!Number.isSafeInteger(limit) || limit < 1 || limit > INSTALLED_CORPUS_POLICY.maxResultLimit) throw new Error('math_search_invalid_limit'); @@ -725,7 +869,7 @@ export function searchMathRetrievalCorpusBatch(root: string, value: unknown, que let conceptSurfaces: ReturnType | undefined; for (const { query: candidate, lexical, docs, aliasNames, concepts } of candidates) { const { terms, exact, matches } = candidate; - const exactName = name === exact || localName === exact; + const exactName = name === exact || !candidate.rooted && localName === exact; const aliasRank = aliasNames?.get(qualifiedName); const lexicalMatch = lexical && terms.every(term => name.includes(term) || header.includes(term) || context.includes(term) || module.includes(term)); const docsMatch = docs && !translation && declaration.docComment && @@ -735,7 +879,7 @@ export function searchMathRetrievalCorpusBatch(root: string, value: unknown, que const conceptScore = concepts?.mayMatch(conceptText ??= name + ' ' + header + ' ' + context) ? concepts.score(conceptSurfaces ??= mathConceptSurfaces(name, header, context)) : 0; const useGoal = lexicalMatch || docsMatch || conceptScore || exactName || aliasRank !== undefined || goalHeader; - if (rankGoal && useGoal) goalMatch ??= rankGoal.assess(exactGoalHeader, goalContext); + if (rankGoal && useGoal) goalMatch ??= rankGoal.assess(exactGoalHeader, goalContext, !translation && declaration.shadowedAbs); const goalRecall = goalHeader && goalMatch?.recalls; if (!(lexicalMatch || docsMatch || conceptScore || exactName || aliasRank !== undefined || goalRecall)) continue; candidate.totalMatches++; diff --git a/src/math/mathSearchConcepts.ts b/src/math/mathSearchConcepts.ts index 6fac6c75..91ef798b 100644 --- a/src/math/mathSearchConcepts.ts +++ b/src/math/mathSearchConcepts.ts @@ -1,4 +1,4 @@ -import { leanConclusionTokens, leanSurfaceTokens, leanTopLevelTokenIndexes } from './leanSyntax'; +import { isSimpleLeanName, leanConclusionTokens, leanSurfaceTokens, leanTopLevelTokenIndexes } from './leanSyntax'; /** Match reusable mathematical terms against Lean names and signatures. */ const concepts: readonly { prose: RegExp; lean: readonly string[] }[] = [ @@ -38,7 +38,7 @@ const concepts: readonly { prose: RegExp; lean: readonly string[] }[] = [ { prose: /根号\s*二|平方根\s*二|二的平方根|根号\s*2|平方根\s*2|\bsquare root of (?:two|2)\b/giu, lean: ['two', '2'] }, ]; -const leanWords = /ᵐ|ᵀ|[\p{L}\p{M}\p{N}]+|''|[∘∪∩⊆#∫*+≤‖⟪√-]/gu; +const leanWords = /ᵐ|ᵀ|[\p{L}\p{M}\p{N}]+|''|[∘∪∩⊆⊇#∫*+≤‖⟪√-]/gu; const genericEnglish = /\b(?:a|an|the|of|to|in|on|is|are|at|for|by|or|and|its|their|every|any|under|two|equal|equals|one|sets?|subsets?|maps?|functions?|inequality|if|only|be|show|that|can|written|as|express|which|with|taking|produces|results)\b/gi; export function mathConceptSurfaces(name: string, header: string, context: string) { @@ -64,6 +64,32 @@ function relationPreference(query: string) { }; } +/** Does the prose select one particular operand of a binary set operation? */ +function subsetProjection(query: string) { + const sides = query.split(/包含于|\b(?:is a subset of|(?:is )?contained in)\b/iu); + if (sides.length !== 2 || /不包含|并非|不是|\b(?:not|unless|if)\b/iu.test(query)) return; + for (const compound of [0, 1]) { + const operand = sides[1 - compound]; + const ordinal = [...operand.matchAll(/第([一二])个(?:有限)?集|\b(first|second) (?:finite )?set\b/giu)]; + if (ordinal.length !== 1) continue; + const operation = [...sides[compound].matchAll(/并集|交集|\b(?:union|intersection)\b/giu)]; + if (operation.length !== 1 || /并集|交集|\b(?:union|intersection)\b/iu.test(operand)) continue; + const operator = /并集|union/iu.test(operation[0][0]) ? '∪' : '∩'; + const index = ordinal[0][1] === '一' || ordinal[0][2]?.toLowerCase() === 'first' ? 0 : 2; + return (tokens: string[]) => { + if (tokens.length !== 5) return false; + // Read both spellings of inclusion in subset-to-superset order. + const rel = tokens.findIndex(t => t === '⊆' || t === '⊇'); + if (rel < 0) return false; + const sides = [tokens.slice(0, rel), tokens.slice(rel + 1)]; + if (tokens[rel] === '⊇') sides.reverse(); + const [a, op, b] = sides[compound]; + return sides[1 - compound].length === 1 && op === operator && isSimpleLeanName(a) && isSimpleLeanName(b) && + a !== b && sides[compound][index] === sides[1 - compound][0]; + }; + } +} + export function mathSearchConcepts(query: string) { const matched = concepts.filter(({ prose }) => [...query.matchAll(prose)].length > 0); if (matched.length < 2) return undefined; @@ -75,8 +101,19 @@ export function mathSearchConcepts(query: string) { // Two matching concepts must give independent evidence, rather than letting // one word fulfill several different parts of the query. - const distinct = [...new Map(matched.map(({ lean }) => [lean.join('\0'), lean])).values()]; + const projection = subsetProjection(query); + const distinct = [...new Map(matched.map(({ lean }) => [lean.join('\0'), lean])).values()] + .map(group => projection && group.includes('⊆') ? [...group, '⊇'] : group); const relation = relationPreference(query); + // For an explicitly described sum, keep the order of concepts on the left of "equals". + // Shared concepts such as "cardinality" cannot distinguish the two operands. + const equals = /等于|相等|\bequals?\b/iu.exec(query); + const lhs = equals && query.slice(0, equals.index); + const sumMentions = lhs && /相加|之和|\b(?:plus|sum)\b/iu.test(lhs) + ? matched.flatMap(({ prose, lean }) => { + const positions = [...lhs.matchAll(prose)]; + return positions.length === 1 ? [{ offset: positions[0].index, lean }] : []; + }) : []; const integral = distinct.some(group => group.includes('∫')); const ae = distinct.some(group => group.includes('ᵐ')); const aeEquality = /几乎处处\s*相等|\b(?:equal almost everywhere|almost everywhere equal)\b/iu.test(query); @@ -110,6 +147,25 @@ export function mathSearchConcepts(query: string) { const { tokens: conclusion, start } = leanConclusionTokens(tokens.slice(colon + 1)); const hypotheses = tokens.slice(0, colon + 1 + start); score += relation?.(conclusion) ?? 0; + if (projection?.(conclusion)) { + score += 24; + const family = distinct.some(group => group.includes('finset')) ? 'finset' : 'set'; + if (parts[0] === family || headerWords.has(family)) score += 6; + } + if (sumMentions.length >= 2) { + const outer = leanTopLevelTokenIndexes(conclusion); + const eq = outer.find(i => conclusion[i] === '='); + const plus = eq === undefined ? [] : outer.filter(i => i < eq && conclusion[i] === '+'); + if (plus.length === 1 && !outer.some(i => conclusion[i] === '↔' || conclusion[i] === '<->')) { + const words = (tokens: string[]) => new Set(tokens.join(' ').match(leanWords) ?? []); + const left = words(conclusion.slice(0, plus[0])); + const right = words(conclusion.slice(plus[0] + 1, eq)); + const offsets = (a: Set, b: Set) => sumMentions + .filter(({ lean }) => lean.some(t => a.has(t)) && !lean.some(t => b.has(t))).map(m => m.offset); + const first = offsets(left, right), second = offsets(right, left); + if (first.length && second.length && Math.max(...first) < Math.min(...second)) score++; + } + } if (integral && conclusion.includes('∫')) score += 9; if (ae && hypotheses.includes('ᵐ')) { score += 8; diff --git a/src/solver/theoremKnowledgeSearch.ts b/src/solver/theoremKnowledgeSearch.ts index d026a924..60e2a7fb 100644 --- a/src/solver/theoremKnowledgeSearch.ts +++ b/src/solver/theoremKnowledgeSearch.ts @@ -1,5 +1,5 @@ import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { maskLeanCommentsAndStrings } from '../math/leanSyntax'; +import { leanLookupReference, maskLeanCommentsAndStrings } from '../math/leanSyntax'; import { knowledgeGoalSurfaceShape, knowledgeResidualViews, splitIffConclusion, splitStatement } from './theoremKnowledgeGoal'; import type { TheoremKnowledgeBase, TheoremKnowledgeEntry } from './theoremKnowledge'; import { createKnowledgeRelationIndex, type KnowledgeRelation } from './theoremKnowledgeRelations'; @@ -383,21 +383,22 @@ function searchPrepared(prepared: ReturnType, evidence: Kn focusConclusion = true, allowNamespaceHints = false, textMatches?: ReadonlyMap) { const limit = options.limit ?? 10, goal = options.goal ?? '', { documents, groupCount, frequencies } = prepared; const goalOnly = !query.trim(), focused = goalOnly && focusConclusion && knowledgeRelevanceTerms(conclusion(goalTarget(goal)), true).length > 0; - const primaryText = goalOnly ? interfaceText(focused ? conclusion(goalTarget(goal)) : goalTarget(goal)) : query; + const reference = leanLookupReference(query); + const primaryText = goalOnly ? interfaceText(focused ? conclusion(goalTarget(goal)) : goalTarget(goal)) : reference?.name ?? query; const primary = terms(primaryText, goalOnly), primaryGroups = knowledgeRelevanceGroups(primaryText, goalOnly), goalTerms = terms(goal, true), normalizedGoal = canonical(goalTarget(goal)); const genericEquality = goalOnly && !primaryGroups.length && Boolean(equationSides(goalTarget(goal))); const targetConclusionKey = goalOnly ? conclusionKey(goalTarget(goal)) : undefined; const targetFit = goalOnly ? conclusionFits(goalTarget(goal))[0] : undefined; - const identifier = query.trim().replace(/^_root_\./u, '').toLowerCase(); - const nameQuery = /^[\p{L}_][\p{L}\p{M}\p{N}_'.]*$/u.test(identifier); + const identifier = reference?.name.toLowerCase() ?? ''; + const nameQuery = reference !== undefined; const relevant = [...new Set([...primary, ...goalTerms])]; const idf = new Map(relevant.map(term => [term, 1 + Math.log((groupCount + 1) / (1 + (frequencies.get(term) ?? 0)))])); const primaryWeight = primary.reduce((sum, term) => sum + idf.get(term)!, 0); const assess = (document: PreparedDocument) => { const { item, fields } = document, normalizedName = item.name.replace(/^_root_\./u, '').toLowerCase(); - const nameScore = !goalOnly && nameQuery ? normalizedName === identifier ? 5000 : + const nameScore = !goalOnly && nameQuery ? normalizedName === identifier ? 5000 : reference.rooted ? 0 : normalizedName.split('.').at(-1) === identifier ? 4500 : normalizedName.endsWith(`.${identifier}`) ? 4700 : 0 : 0; const textMatch = textMatches?.get(item.id) ?? 0; const matched = primary.filter(term => fields.some(field => field.has(term))); diff --git a/tests/libraryCatalog.test.ts b/tests/libraryCatalog.test.ts index 768a8159..d9234cd2 100644 --- a/tests/libraryCatalog.test.ts +++ b/tests/libraryCatalog.test.ts @@ -46,6 +46,8 @@ describe('versioned library catalog consumption', () => { metadata.entries.length = 0; expect(reopened.moduleMetadata(arithmetic).entries).not.toHaveLength(0); expect(reopened.search([{ query: 'Demo.commute' }])[0].hits[0]?.name).toBe('Demo.commute'); + const pasted = reopened.search([{ query: '#check @_root_.Demo.commute' }])[0]; + expect(pasted.hits[0]).toMatchObject({ name: 'Demo.commute', exactMatch: 'name' }); expect(reopened.search([{ query: 'Demo.secret' }])[0].hits.some(hit => hit.name === 'Demo.secret')).toBe(false); expect(reopened.identity).toMatchObject({ id: 'example/arithmetic', revision: 'v1', catalogDigest: f.built.digest }); }); diff --git a/tests/mathRetrievalCorpus.test.ts b/tests/mathRetrievalCorpus.test.ts index 69114c21..7ca80c03 100644 --- a/tests/mathRetrievalCorpus.test.ts +++ b/tests/mathRetrievalCorpus.test.ts @@ -8,6 +8,7 @@ import { mathDigest } from '../src/math/mathRuntimeIo'; import * as verifier from '../src/math/leanSource'; import * as installedPackageSearch from '../src/math/installedPackageSearch'; import * as additiveIndex from '../src/math/mathlibAdditiveIndex'; +import { goalPremiseKeys, matchedGoalPremises } from '../src/math/leanGoalPremises'; describe('frozen Lean declaration lookup', () => { let root: string; @@ -173,6 +174,33 @@ describe('frozen Lean declaration lookup', () => { ]); }); + it('uses the described order of summands even when names and hypotheses give no ordering clue', async () => { + fs.writeFileSync(source, [ + 'theorem aa (x : ℝ) (h : √x = ‖x‖) : ‖x‖ + √x = x := by sorry', + 'theorem zz (x : ℝ) (h : √x = ‖x‖) : √x + ‖x‖ = x := by sorry', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const queries = ['平方根与范数相加等于原数', 'the norm plus the square root equals the number', + '原数等于平方根与范数之和']; + const [forward, reverse, rhsOnly] = searchMathRetrievalCorpusBatch(root, corpus, queries, 2).queries; + expect(forward.results.map(item => item.name)).toEqual(['zz', 'aa']); + expect(reverse.results.map(item => item.name)).toEqual(['aa', 'zz']); + expect(rhsOnly.results).toHaveLength(2); + expect(rhsOnly.results[0].score).toEqual(rhsOnly.results[1].score); + }); + + it('selects the requested subset operand from the conclusion independently of names or binder order', async () => { + fs.writeFileSync(source, [ + 'theorem aa (t s : Set α) : t ⊇ s ∩ t := by sorry', + 'theorem zz (t s : Set α) : s ∩ t ⊆ s := by sorry', + 'theorem hh (t s : Set α) (h : s ∩ t ⊆ s) : t ⊆ t := by sorry', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const queries = ['两个集合的交集包含于第一个集合', 'the intersection of two sets is contained in the second set']; + const result = searchMathRetrievalCorpusBatch(root, corpus, queries, 1); + expect(result.queries.map(item => item.results[0]?.name)).toEqual(['zz', 'aa']); + }); + it('ranks the requested conclusion and almost-everywhere relation above neighboring declarations', async () => { fs.writeFileSync(source, [ 'theorem isClosed_closure : IsClosed (closure s) := by sorry', @@ -211,6 +239,22 @@ describe('frozen Lean declaration lookup', () => { expect(searchMathRetrievalCorpus(root, corpus, '', 15, 'x y : ℝ\n⊢ x = y').results).toEqual([]); }); + it('ranks a pasted Lean reference as an identifier and keeps the original query', async () => { + fs.writeFileSync(source, [ + "theorem step' : True := trivial", + 'namespace Other', + "theorem step' : True := trivial", + 'end Other', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const query = "#check @_root_.step'"; + const result = searchMathRetrievalCorpus(root, corpus, query, 5); + expect(result.query).toBe(query); + expect(result.results[0]?.qualifiedName).toBe("step'"); + expect(result.results.find(hit => hit.qualifiedName === "Other.step'")?.score).toBeLessThan(10_000); + expect(searchMathRetrievalCorpus(root, corpus, "#check @Other.step' x", 5).results).toEqual([]); + }); + it('recalls both spellings of the same comparison without swapping the inequality itself', async () => { fs.writeFileSync(source, [ 'variable {E : Type*} (x : E)', @@ -263,6 +307,103 @@ describe('frozen Lean declaration lookup', () => { expect(results[0]?.qualifiedName).toBe('Real.exp_pos'); }); + it('preserves the complement operator when set variables are renamed', async () => { + fs.writeFileSync(source, [ + 'variable {s : Set α} {x : α}', + 'theorem once : x ∈ sᶜ ↔ x ∉ s := by sorry', + 'theorem twice : x ∈ sᶜᶜ ↔ x ∈ s := by sorry', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const names = (goal: string) => searchMathRetrievalCorpus(root, corpus, '', 5, `A : Set α\ny : α\n⊢ ${goal}`) + .results.map(hit => hit.name); + expect(names('y ∈ Aᶜ ↔ y ∉ A')).toEqual(['once']); + expect(names('y ∈ Aᶜᶜ ↔ y ∈ A')).toEqual(['twice']); + expect(names('y ∈ A ↔ y ∉ A')).toEqual([]); + }); + + it('distinguishes function order and an unapplied composition passed as an argument', async () => { + fs.writeFileSync(source, [ + 'namespace Sample', + 'theorem a_backward (x : ℝ) : second (first x) = x := by sorry', + 'theorem z_forward (x : ℝ) : first (second x) = x := by sorry', + 'theorem higher (op : (ℝ → ℝ) → ℝ → ℝ) (x : ℝ) : op (first ∘ second) x = x := by sorry', + 'end Sample', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const firstHit = (target: string) => searchMathRetrievalCorpus(root, corpus, '', 1, + `a b : ℝ\nh : (ℝ → ℝ) → ℝ → ℝ\n⊢ ${target}`).results[0]; + expect(firstHit('(Sample.first ∘ Sample.second) a = a')?.name).toBe('z_forward'); + expect(firstHit('(Sample.second ∘ Sample.first) a = a')?.name).toBe('a_backward'); + expect(firstHit('a + b = (Sample.first ∘ Sample.second) (a + b)')).toMatchObject({ name: 'z_forward', application: 'symm' }); + expect(firstHit('h (Sample.first ∘ Sample.second) a = a')?.name).toBe('higher'); + }); + + it('recalls absolute values across spellings and keeps their operands grouped', async () => { + fs.writeFileSync(source, [ + 'theorem named (x y : ℝ) : abs (x * y) = abs x * abs y := by sorry', + 'theorem bars (x y : ℝ) : |x * y| = |x| * |y| := by sorry', + 'theorem normed (x y : ℝ) : ‖x * y‖ = ‖x‖ * ‖y‖ := by sorry', + 'theorem localFn (abs : ℝ → ℝ) (x y : ℝ) : abs (x * y) = abs x * abs y := by sorry', + 'theorem grouped (x : ℝ) : |x ^ 2| = x ^ 2 := by sorry', + 'namespace Other', + 'def abs (x : ℝ) := x * x', + 'theorem _root_.otherSquare (x : ℝ) : abs (x ^ 2) = x ^ 2 := by sorry', + 'theorem explicitRoot (x : ℝ) : _root_.abs (x ^ 2) = x ^ 2 := by sorry', + 'end Other', + 'theorem afterNamespace (x : ℝ) : abs (x ^ 2) = x ^ 2 := by sorry', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const search = (goal: string, extra = '') => + searchMathRetrievalCorpus(root, corpus, '', 8, `a b : ℝ\n${extra}⊢ ${goal}`).results; + for (const goal of ['abs (a * b) = |a| * abs b', '|a * b| = |a| * |b|']) + expect(search(goal).map(hit => hit.name).sort()).toEqual(['bars', 'named']); + expect(search('abs a * |b| = |a * b|').map(hit => hit.application)).toEqual(['symm', 'symm']); + expect(search('abs (a ^ 2) = a ^ 2').map(hit => hit.name).sort()).toEqual(['afterNamespace', 'explicitRoot', 'grouped']); + for (const goal of ['abs a ^ 2 = a ^ 2', 'f abs a = a ^ 2', 'a ∣ b', '{x | x = a} = {x | x = b}', + '(match a with | x => x) = (match b with | y => y)']) + expect(search(goal)).toEqual([]); + expect(search('abs (a * b) = abs a * abs b', 'abs : ℝ → ℝ\n')).toEqual([]); + expect(search('‖a * b‖ = ‖a‖ * ‖b‖').map(hit => hit.name)).toEqual(['normed']); + }); + + it('aligns set image names and notation without conflating other operations', async () => { + fs.writeFileSync(source, [ + "theorem named (f : α → β) : Set.image f ∅ = ∅ := by sorry", + "theorem written (f : α → β) : f '' ∅ = ∅ := by sorry", + "theorem inverse (f : α → β) : f ⁻¹' ∅ = ∅ := by sorry", + 'theorem finite (f : α → β) : Finset.image f ∅ = ∅ := by sorry', + "theorem primed (f'' : α → β) : f'' ∅ = ∅ := by sorry", + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const search = (goal: string) => searchMathRetrievalCorpus(root, corpus, '', 5, `g : α → β\n⊢ ${goal}`).results; + for (const goal of ["g '' ∅ = ∅", 'Set.image g ∅ = ∅']) + expect(search(goal).map(hit => hit.name).sort()).toEqual(['named', 'written']); + expect(search('Set.preimage g ∅ = ∅').map(hit => hit.name)).toEqual(['inverse']); + for (const goal of ['Set.image g = ∅', 'Set.image g ∅ x = ∅', 'Finset.image g ∅ = ∅']) + expect(search(goal).some(hit => hit.name === 'written' && hit.score >= 1500)).toBe(false); + }); + + it('normalizes inclusion in either spelling without reversing its meaning or changing strictness', async () => { + fs.writeFileSync(source, [ + 'variable {s t : Set α}', + 'theorem forward : s ∩ t ⊆ s := by sorry', + 'theorem reverse_spelling : s ⊇ s ∩ t := by sorry', + 'theorem opposite : s ⊆ s ∩ t := by sorry', + 'theorem strict (h : s ∩ t ≠ s) : s ∩ t ⊂ s := by sorry', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + for (const goal of ['a ⊇ a ∩ b', 'a ∩ b ⊆ a', 'a ⊃ a ∩ b']) { + const { results } = searchMathRetrievalCorpus(root, corpus, '', 5, `a b : Set α\n⊢ ${goal}`); + expect(results.map(hit => hit.name).sort()).toEqual(goal.includes('⊃') ? ['strict'] : ['forward', 'reverse_spelling']); + expect(results.every(hit => hit.application === undefined)).toBe(true); + } + const locals = new Map([['a', '$0'], ['b', '$1']]); + const available = goalPremiseKeys('h : b ⊃ a', locals); + for (const [premise, count] of [['a ⊂ b', 1], ['b ⊂ a', 0], ['a ⊆ b', 0]] as const) { + expect(matchedGoalPremises(`candidate (h : ${premise}) : a ≠ b`, locals, available)).toBe(count); + } + }); + it('recalls a theorem for compound arguments and checks repeated occurrences of the same parameter', async () => { fs.writeFileSync(source, [ 'variable {E : Type*} (a b : E)', @@ -290,6 +431,19 @@ describe('frozen Lean declaration lookup', () => { .results.map(result => result.name); expect(rank('0 ≤ z + t').slice(0, 2)).toEqual(['right', 'left']); expect(rank('0 ≤ (x + y)').slice(0, 2)).toEqual(['left', 'right']); + expect(rank('z + t >= 0').slice(0, 2)).toEqual(['right', 'left']); + }); + + it('uses facts projected from a conjunction only when they follow from the hypothesis', () => { + const locals = new Map([['x', '$0']]); + const matches = (hypothesis: string, premise = '0 < x') => matchedGoalPremises( + `lemmaName (h : ${premise}) : x = x`, locals, goalPremiseKeys(`h : ${hypothesis}`, locals)); + expect(matches('x < 1 ∧ (x > 0 ∧ x ≠ 2)')).toBe(1); + expect(matches('0 < x ∧ x < 1', '0 < x ∧ x < 1')).toBe(1); + for (const h of ['0 < x ∨ x < 1', 'p → 0 < x ∧ x < 1', 'p ∨ 0 < x ∧ x < 1', + '∀ n, 0 < x ∧ n < x', '¬ (0 < x ∧ x < 1)', 'x < 0 ∧ x < 1', 'x >= 0']) { + expect(matches(h), h).toBe(0); + } }); it('finds a notation-only goal using multiline variables and ranks concrete type mismatches lower', async () => { @@ -309,6 +463,19 @@ describe('frozen Lean declaration lookup', () => { expect(results[0].sourceContext).toBe('variable {α F : Type*} [OuterMeasureClass F α]\n {μ : F} {s t : Set α}\nopen scoped ENNReal'); }); + it('ignores parentheses around whole comparison operands but keeps nested operators grouped', async () => { + fs.writeFileSync(source, [ + 'theorem grouped (s t u : Set α) : ((s ∩ (t ∪ u))) ⊆ (s) := by sorry', + 'theorem other (s t u : Set α) : s ∩ t ∪ u ⊆ s := by sorry', + ].join('\n')); + const corpus = await createMathRetrievalCorpus(root, ['mathlib']); + const names = (target: string) => searchMathRetrievalCorpus(root, corpus, '', 5, + `a b c : Set α\n⊢ ${target}`).results.map(hit => hit.name); + expect(names('a ∩ (b ∪ c) ⊆ a')).toEqual(['grouped']); + expect(names('(a) ⊇ ((a ∩ (b ∪ c)))')).toEqual(['grouped']); + expect(names('(a ∩ b ∪ c) ⊆ (a)')).toEqual(['other']); + }); + it('matches redundant set intersection parentheses and keeps grouping that changes meaning', async () => { fs.writeFileSync(source, [ 'variable {s t u : Set α}', diff --git a/tests/webInstalledLibrary.test.ts b/tests/webInstalledLibrary.test.ts index 29ecb074..7e9d093f 100644 --- a/tests/webInstalledLibrary.test.ts +++ b/tests/webInstalledLibrary.test.ts @@ -76,6 +76,8 @@ describe('browsing the installed Lean release without publishing research assets const result = await get(`${route}?q=${name}&area=Algebra&environment=mathlib`); expect(result.total).toBe(1); const summary = result.items[0]; + const pasted = await get(`${route}?${new URLSearchParams({ q: '#check @_root_.' + name })}`); + expect(pasted.items[0]?.matchingInterfaces[0]?.name).toBe(name); expect(summary.preview.some(entry => entry.name === name)).toBe(true); const detailRoute = moduleRoute(summary.file, result.library.catalogDigest); const { item: detail } = await get<{ item: InstalledLibraryDetail }>(detailRoute);