From e7724c0571492165572718cb1d3381bd653c0412 Mon Sep 17 00:00:00 2001 From: Vasily Ilin Date: Sat, 28 Nov 2026 10:37:40 +0000 Subject: [PATCH 1/3] Import the categorial, Lambek, and minimalist grammar equivalences --- LeanPool/FormalLinguistics.lean | 49 + LeanPool/FormalLinguistics/ABG.lean | 274 ++ LeanPool/FormalLinguistics/ABGtoCFG.lean | 180 + LeanPool/FormalLinguistics/BarHillel.lean | 135 + LeanPool/FormalLinguistics/BinMCFG.lean | 811 +++++ LeanPool/FormalLinguistics/CFG.lean | 206 ++ LeanPool/FormalLinguistics/CFGtoABG.lean | 138 + LeanPool/FormalLinguistics/CNF.lean | 812 +++++ LeanPool/FormalLinguistics/Fixpoint.lean | 188 + LeanPool/FormalLinguistics/GNF.lean | 277 ++ LeanPool/FormalLinguistics/Imports.lean | 32 + LeanPool/FormalLinguistics/Lambek.lean | 319 ++ LeanPool/FormalLinguistics/LambekCore.lean | 122 + LeanPool/FormalLinguistics/LambekCut.lean | 280 ++ .../FormalLinguistics/LambekFreeGroup.lean | 652 ++++ .../LambekInterpolation.lean | 291 ++ LeanPool/FormalLinguistics/LambekPentus.lean | 569 +++ LeanPool/FormalLinguistics/LambekThin.lean | 190 + LeanPool/FormalLinguistics/MCFG.lean | 178 + LeanPool/FormalLinguistics/MCFGtoMG.lean | 1682 +++++++++ LeanPool/FormalLinguistics/MG.lean | 226 ++ LeanPool/FormalLinguistics/MGMCFGEquiv.lean | 472 +++ LeanPool/FormalLinguistics/MGOriginal.lean | 283 ++ LeanPool/FormalLinguistics/MGtoMCFG.lean | 3217 +++++++++++++++++ LeanPool/FormalLinguistics/MathlibBridge.lean | 154 + .../projects/formal-grammar-equivalences.yaml | 45 + 26 files changed, 11782 insertions(+) create mode 100644 LeanPool/FormalLinguistics.lean create mode 100644 LeanPool/FormalLinguistics/ABG.lean create mode 100644 LeanPool/FormalLinguistics/ABGtoCFG.lean create mode 100644 LeanPool/FormalLinguistics/BarHillel.lean create mode 100644 LeanPool/FormalLinguistics/BinMCFG.lean create mode 100644 LeanPool/FormalLinguistics/CFG.lean create mode 100644 LeanPool/FormalLinguistics/CFGtoABG.lean create mode 100644 LeanPool/FormalLinguistics/CNF.lean create mode 100644 LeanPool/FormalLinguistics/Fixpoint.lean create mode 100644 LeanPool/FormalLinguistics/GNF.lean create mode 100644 LeanPool/FormalLinguistics/Imports.lean create mode 100644 LeanPool/FormalLinguistics/Lambek.lean create mode 100644 LeanPool/FormalLinguistics/LambekCore.lean create mode 100644 LeanPool/FormalLinguistics/LambekCut.lean create mode 100644 LeanPool/FormalLinguistics/LambekFreeGroup.lean create mode 100644 LeanPool/FormalLinguistics/LambekInterpolation.lean create mode 100644 LeanPool/FormalLinguistics/LambekPentus.lean create mode 100644 LeanPool/FormalLinguistics/LambekThin.lean create mode 100644 LeanPool/FormalLinguistics/MCFG.lean create mode 100644 LeanPool/FormalLinguistics/MCFGtoMG.lean create mode 100644 LeanPool/FormalLinguistics/MG.lean create mode 100644 LeanPool/FormalLinguistics/MGMCFGEquiv.lean create mode 100644 LeanPool/FormalLinguistics/MGOriginal.lean create mode 100644 LeanPool/FormalLinguistics/MGtoMCFG.lean create mode 100644 LeanPool/FormalLinguistics/MathlibBridge.lean create mode 100644 LeanPool/projects/formal-grammar-equivalences.yaml diff --git a/LeanPool/FormalLinguistics.lean b/LeanPool/FormalLinguistics.lean new file mode 100644 index 0000000000..29a90708a8 --- /dev/null +++ b/LeanPool/FormalLinguistics.lean @@ -0,0 +1,49 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.BarHillel +public import LeanPool.FormalLinguistics.LambekPentus +public import LeanPool.FormalLinguistics.MGOriginal + +/-! +# Categorial, Lambek, and minimalist grammar equivalences + +Source: url:https://github.com/bocchitherock888-ux/lean-grammar-equivalences/releases/tag/v2.0 +Authors: bocchitherock888-ux +Status: verified +Main declarations: `FormalLinguistics.bar_hillel_gaifman_shamir`, + `FormalLinguistics.chomsky_pentus`, `FormalLinguistics.michaelis_harkema_equivalence_SK` +Tags: formal-languages, categorial-grammars, lambek-calculus, minimalist-grammars +MSC: 68Q42, 03B47 +-/ + +/- +Upstream source license for this project + +MIT License + +Copyright (c) 2026 bocchitherock888-ux + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +-/ diff --git a/LeanPool/FormalLinguistics/ABG.lean b/LeanPool/FormalLinguistics/ABG.lean new file mode 100644 index 0000000000..21af59bc0f --- /dev/null +++ b/LeanPool/FormalLinguistics/ABG.lean @@ -0,0 +1,274 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import Init + +/-! + AB Basic Categorial Grammars (Ajdukiewicz 1935; Bar-Hillel 1953; Bar-Hillel, Gaifman & Shamir 1960) + Standard directional slash-cancellation definition + equivalence with AB derivation trees (`ABTree`). +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Categorial types over atomic categories `P`: + `rslash A B` denotes `A / B` (combines with `B` on the right to yield `A`), + `lslash B A` denotes `B \ A` (combines with `B` on the left to yield `A`). -/ +inductive Cat (P : Type) where + | atom : P → Cat P + | rslash : Cat P → Cat P → Cat P + | lslash : Cat P → Cat P → Cat P + deriving DecidableEq, Repr + +/-- A finite AB Categorial Grammar over atomic categories `P` and alphabet `T`. -/ +structure ABG (P T : Type) where + /-- Primitive category of complete derivations. -/ + distinguished : P + /-- Allowed assignments of categories to individual terminals. -/ + lexicon : List (T × Cat P) + +namespace ABG + +variable {P T : Type} + +/-- Single-step AB cancellation: + - Forward application (`>`): `(A / B) B ⊢ A` + - Backward application (`<`): `B (B \ A) ⊢ A` -/ +inductive ABStep : List (Cat P) → List (Cat P) → Prop where + | fwd (u v : List (Cat P)) (A B : Cat P) : + ABStep (u ++ [Cat.rslash A B, B] ++ v) (u ++ [A] ++ v) + | bwd (u v : List (Cat P)) (A B : Cat P) : + ABStep (u ++ [B, Cat.lslash B A] ++ v) (u ++ [A] ++ v) + +/-- Multi-step AB cancellation: reflexive-transitive closure of `ABStep`. -/ +inductive ABDerives : List (Cat P) → List (Cat P) → Prop where + | refl (γ : List (Cat P)) : ABDerives γ γ + | tail {γ1 γ2 γ3 : List (Cat P)} : ABDerives γ1 γ2 → ABStep γ2 γ3 → ABDerives γ1 γ3 + +/-- Lexical assignment: word `w = [a₁, ..., aₙ]` is assigned categories `γ = [c₁, ..., cₙ]` + with `(aᵢ, cᵢ) ∈ G.lexicon`. -/ +inductive LexAssign (G : ABG P T) : List T → List (Cat P) → Prop where + | nil : LexAssign G [] [] + | cons {a : T} {c : Cat P} {w : List T} {γ : List (Cat P)} : + (a, c) ∈ G.lexicon → LexAssign G w γ → LexAssign G (a :: w) (c :: γ) + +/-- The string language generated by an AB Categorial Grammar. -/ +def Lang (G : ABG P T) (w : List T) : Prop := + ∃ γ, LexAssign G w γ ∧ ABDerives γ [Cat.atom G.distinguished] + +theorem ABStep.length_eq {γ1 γ2 : List (Cat P)} (h : ABStep γ1 γ2) : + γ1.length = γ2.length + 1 := by + cases h <;> simp <;> omega + +theorem ABDerives.length_ge {γ1 γ2 : List (Cat P)} (h : ABDerives γ1 γ2) : + γ2.length ≤ γ1.length := by + induction h with + | refl => exact Nat.le_refl _ + | tail _ hstep ih => + have hl := hstep.length_eq + omega + +theorem LexAssign.length_eq {G : ABG P T} {w : List T} {γ : List (Cat P)} + (h : LexAssign G w γ) : w.length = γ.length := by + induction h with + | nil => rfl + | cons _ _ ih => simp [ih] + +/-- Every AB categorial language is ε-free (contains no empty string). -/ +theorem lang_nonempty {G : ABG P T} {w : List T} (h : G.Lang w) : w ≠ [] := by + obtain ⟨γ, hlex, hder⟩ := h + have hlen1 := hlex.length_eq + have hlen2 := hder.length_ge + intro hw + subst hw + simp at hlen1 hlen2 + omega + +theorem ABDerives.single {γ1 γ2 : List (Cat P)} (h : ABStep γ1 γ2) : ABDerives γ1 γ2 := + ABDerives.tail (ABDerives.refl γ1) h + +theorem ABDerives.trans {γ1 γ2 γ3 : List (Cat P)} + (h1 : ABDerives γ1 γ2) (h2 : ABDerives γ2 γ3) : ABDerives γ1 γ3 := by + induction h2 with + | refl => exact h1 + | tail _ hstep ih => exact ABDerives.tail ih hstep + +theorem ABStep.append_left (p : List (Cat P)) {γ1 γ2 : List (Cat P)} + (h : ABStep γ1 γ2) : ABStep (p ++ γ1) (p ++ γ2) := by + cases h with + | fwd l r A B => + have h1 : p ++ (l ++ [Cat.rslash A B, B] ++ r) = (p ++ l) ++ [Cat.rslash A B, B] ++ r := by + simp [List.append_assoc] + have h2 : p ++ (l ++ [A] ++ r) = (p ++ l) ++ [A] ++ r := by + simp [List.append_assoc] + rw [h1, h2] + exact ABStep.fwd (p ++ l) r A B + | bwd l r A B => + have h1 : p ++ (l ++ [B, Cat.lslash B A] ++ r) = (p ++ l) ++ [B, Cat.lslash B A] ++ r := by + simp [List.append_assoc] + have h2 : p ++ (l ++ [A] ++ r) = (p ++ l) ++ [A] ++ r := by + simp [List.append_assoc] + rw [h1, h2] + exact ABStep.bwd (p ++ l) r A B + +theorem ABStep.append_right (s : List (Cat P)) {γ1 γ2 : List (Cat P)} + (h : ABStep γ1 γ2) : ABStep (γ1 ++ s) (γ2 ++ s) := by + cases h with + | fwd l r A B => + have h1 : (l ++ [Cat.rslash A B, B] ++ r) ++ s = l ++ [Cat.rslash A B, B] ++ (r ++ s) := by + simp [List.append_assoc] + have h2 : (l ++ [A] ++ r) ++ s = l ++ [A] ++ (r ++ s) := by + simp [List.append_assoc] + rw [h1, h2] + exact ABStep.fwd l (r ++ s) A B + | bwd l r A B => + have h1 : (l ++ [B, Cat.lslash B A] ++ r) ++ s = l ++ [B, Cat.lslash B A] ++ (r ++ s) := by + simp [List.append_assoc] + have h2 : (l ++ [A] ++ r) ++ s = l ++ [A] ++ (r ++ s) := by + simp [List.append_assoc] + rw [h1, h2] + exact ABStep.bwd l (r ++ s) A B + +theorem ABDerives.append_left (p : List (Cat P)) {γ1 γ2 : List (Cat P)} + (h : ABDerives γ1 γ2) : ABDerives (p ++ γ1) (p ++ γ2) := by + induction h with + | refl => exact ABDerives.refl _ + | tail _ hstep ih => exact ABDerives.tail ih (ABStep.append_left p hstep) + +theorem ABDerives.append_right (s : List (Cat P)) {γ1 γ2 : List (Cat P)} + (h : ABDerives γ1 γ2) : ABDerives (γ1 ++ s) (γ2 ++ s) := by + induction h with + | refl => exact ABDerives.refl _ + | tail _ hstep ih => exact ABDerives.tail ih (ABStep.append_right s hstep) + +theorem ABDerives.append {γ1 δ1 γ2 δ2 : List (Cat P)} + (h1 : ABDerives γ1 δ1) (h2 : ABDerives γ2 δ2) : ABDerives (γ1 ++ γ2) (δ1 ++ δ2) := + ABDerives.trans (ABDerives.append_right γ2 h1) (ABDerives.append_left δ1 h2) + +theorem LexAssign.append {G : ABG P T} {w1 w2 : List T} {γ1 γ2 : List (Cat P)} + (h1 : LexAssign G w1 γ1) (h2 : LexAssign G w2 γ2) : LexAssign G (w1 ++ w2) (γ1 ++ γ2) := by + induction h1 with + | nil => simpa using h2 + | cons ha _ ih => exact LexAssign.cons ha ih + +/-- Binary derivation trees for AB Categorial Grammars. -/ +inductive ABTree (G : ABG P T) : Cat P → List T → Prop where + | lex {a : T} {c : Cat P} : (a, c) ∈ G.lexicon → ABTree G c [a] + | fwd {A B : Cat P} {w1 w2 : List T} : + ABTree G (Cat.rslash A B) w1 → ABTree G B w2 → ABTree G A (w1 ++ w2) + | bwd {A B : Cat P} {w1 w2 : List T} : + ABTree G B w1 → ABTree G (Cat.lslash B A) w2 → ABTree G A (w1 ++ w2) + +/-- List of AB derivation trees matching a category sequence. -/ +inductive ABTreeList (G : ABG P T) : List (Cat P) → List T → Prop where + | nil : ABTreeList G [] [] + | cons {c : Cat P} {γ : List (Cat P)} {w1 w2 : List T} : + ABTree G c w1 → ABTreeList G γ w2 → ABTreeList G (c :: γ) (w1 ++ w2) + +theorem ABTreeList.append {G : ABG P T} {γ1 γ2 : List (Cat P)} {w1 w2 : List T} + (h1 : ABTreeList G γ1 w1) (h2 : ABTreeList G γ2 w2) : + ABTreeList G (γ1 ++ γ2) (w1 ++ w2) := by + induction h1 with + | nil => simpa using h2 + | cons ht _ ih => + simpa [List.append_assoc] using ABTreeList.cons ht ih + +theorem ABTreeList.split_append {G : ABG P T} {γ1 γ2 : List (Cat P)} {w : List T} + (h : ABTreeList G (γ1 ++ γ2) w) : + ∃ w1 w2, w = w1 ++ w2 ∧ ABTreeList G γ1 w1 ∧ ABTreeList G γ2 w2 := by + induction γ1 generalizing w with + | nil => exact ⟨[], w, rfl, ABTreeList.nil, h⟩ + | cons c t ih => + cases h with + | cons ht hrest => + obtain ⟨w1, w2, hw, h1, h2⟩ := ih hrest + refine ⟨_ ++ w1, w2, ?_, ABTreeList.cons ht h1, h2⟩ + simp [hw, List.append_assoc] + +theorem ABTreeList.of_lexAssign {G : ABG P T} {w : List T} {γ : List (Cat P)} + (h : LexAssign G w γ) : ABTreeList G γ w := by + induction h with + | nil => exact ABTreeList.nil + | cons ha _ ih => + simpa using ABTreeList.cons (ABTree.lex ha) ih + +theorem ABTreeList.step {G : ABG P T} {γ1 γ2 : List (Cat P)} {w : List T} + (h : ABTreeList G γ1 w) (hs : ABStep γ1 γ2) : ABTreeList G γ2 w := by + cases hs with + | fwd l r A B => + rw [List.append_assoc] at h + obtain ⟨w1, w23, hw1, hl, h23⟩ := ABTreeList.split_append h + obtain ⟨w2, w3, hw2, hmid, hr⟩ := ABTreeList.split_append h23 + cases hmid with + | @cons _ _ wa _ hAB hrest => + cases hrest with + | @cons _ _ wb _ hB hnil => + cases hnil + have hA : ABTree G A (wa ++ wb) := ABTree.fwd hAB hB + have hAs : ABTreeList G [A] (wa ++ wb) := by + simpa using ABTreeList.cons hA ABTreeList.nil + have hres := ABTreeList.append (ABTreeList.append hl hAs) hr + simpa [hw1, hw2, List.append_assoc] using hres + | bwd l r A B => + rw [List.append_assoc] at h + obtain ⟨w1, w23, hw1, hl, h23⟩ := ABTreeList.split_append h + obtain ⟨w2, w3, hw2, hmid, hr⟩ := ABTreeList.split_append h23 + cases hmid with + | @cons _ _ wa _ hB hrest => + cases hrest with + | @cons _ _ wb _ hBA hnil => + cases hnil + have hA : ABTree G A (wa ++ wb) := ABTree.bwd hB hBA + have hAs : ABTreeList G [A] (wa ++ wb) := by + simpa using ABTreeList.cons hA ABTreeList.nil + have hres := ABTreeList.append (ABTreeList.append hl hAs) hr + simpa [hw1, hw2, List.append_assoc] using hres + +theorem ABTreeList.of_derives {G : ABG P T} {γ1 γ2 : List (Cat P)} {w : List T} + (h : ABTreeList G γ1 w) (hd : ABDerives γ1 γ2) : ABTreeList G γ2 w := by + induction hd with + | refl => exact h + | tail _ hstep ih => exact ABTreeList.step ih hstep + +theorem abtree_iff_derives {G : ABG P T} {C : Cat P} {w : List T} : + ABTree G C w ↔ ∃ γ, LexAssign G w γ ∧ ABDerives γ [C] := by + constructor + · intro ht + induction ht with + | lex ha => + exact ⟨[_], LexAssign.cons ha LexAssign.nil, ABDerives.refl _⟩ + | @fwd A B w1 w2 _ _ ih1 ih2 => + obtain ⟨γ1, hl1, hd1⟩ := ih1 + obtain ⟨γ2, hl2, hd2⟩ := ih2 + refine ⟨γ1 ++ γ2, LexAssign.append hl1 hl2, ?_⟩ + have h1 := ABDerives.append hd1 hd2 + have h2 : ABStep [Cat.rslash A B, B] [A] := by + simpa using ABStep.fwd [] [] A B + exact ABDerives.trans h1 (ABDerives.single h2) + | @bwd A B w1 w2 _ _ ih1 ih2 => + obtain ⟨γ1, hl1, hd1⟩ := ih1 + obtain ⟨γ2, hl2, hd2⟩ := ih2 + refine ⟨γ1 ++ γ2, LexAssign.append hl1 hl2, ?_⟩ + have h1 := ABDerives.append hd1 hd2 + have h2 : ABStep [B, Cat.lslash B A] [A] := by + simpa using ABStep.bwd [] [] A B + exact ABDerives.trans h1 (ABDerives.single h2) + · rintro ⟨γ, hlex, hder⟩ + have hlist := ABTreeList.of_derives (ABTreeList.of_lexAssign hlex) hder + cases hlist with + | cons ht hnil => + cases hnil + simpa using ht + +theorem lang_iff_abtree {G : ABG P T} {w : List T} : + G.Lang w ↔ ABTree G (Cat.atom G.distinguished) w := + abtree_iff_derives.symm + +end ABG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/ABGtoCFG.lean b/LeanPool/FormalLinguistics/ABGtoCFG.lean new file mode 100644 index 0000000000..d2f50c137f --- /dev/null +++ b/LeanPool/FormalLinguistics/ABGtoCFG.lean @@ -0,0 +1,180 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.CFG +public import LeanPool.FormalLinguistics.ABG + +/-! + Direction 1 of Bar-Hillel, Gaifman & Shamir (1960): + Every AB Basic Categorial Grammar has a weakly equivalent Context-Free Grammar. +-/ + +@[expose] public section + +namespace FormalLinguistics + +namespace Cat + +variable {P : Type} + +/-- All sub-categories (subformulas) of a category `C`. -/ +def subcats : Cat P → List (Cat P) + | Cat.atom p => [Cat.atom p] + | Cat.rslash A B => Cat.rslash A B :: (subcats A ++ subcats B) + | Cat.lslash B A => Cat.lslash B A :: (subcats B ++ subcats A) + +theorem mem_subcats_self (C : Cat P) : C ∈ C.subcats := by + cases C <;> simp [subcats] + +theorem subcats_trans {C D E : Cat P} (h1 : C ∈ D.subcats) (h2 : D ∈ E.subcats) : + C ∈ E.subcats := by + induction E with + | atom p => + simp [subcats] at h2 + subst h2 + exact h1 + | rslash A B ihA ihB => + simp [subcats] at h2 + rcases h2 with rfl | hA | hB + · exact h1 + · exact List.mem_cons_of_mem _ (List.mem_append_left _ (ihA hA)) + · exact List.mem_cons_of_mem _ (List.mem_append_right _ (ihB hB)) + | lslash B A ihB ihA => + simp [subcats] at h2 + rcases h2 with rfl | hB | hA + · exact h1 + · exact List.mem_cons_of_mem _ (List.mem_append_left _ (ihB hB)) + · exact List.mem_cons_of_mem _ (List.mem_append_right _ (ihA hA)) + +theorem rslash_mem_subcats_left {A B E : Cat P} (h : Cat.rslash A B ∈ E.subcats) : + A ∈ E.subcats := + subcats_trans (D := Cat.rslash A B) + (List.mem_cons_of_mem _ (List.mem_append_left _ (mem_subcats_self A))) h + +theorem lslash_mem_subcats_right {B A E : Cat P} (h : Cat.lslash B A ∈ E.subcats) : + A ∈ E.subcats := + subcats_trans (D := Cat.lslash B A) + (List.mem_cons_of_mem _ (List.mem_append_right _ (mem_subcats_self A))) h + +end Cat + +namespace ABG + +variable {P T : Type} + +/-- Finite list of all sub-categories appearing in the lexicon of `G`. -/ +def allSubcats (G : ABG P T) : List (Cat P) := + G.lexicon.flatMap (fun entry => entry.2.subcats) + +/-- Subformula property: every category derivable by an `ABTree` is a lexical sub-category. -/ +theorem ABTree.mem_allSubcats {G : ABG P T} {C : Cat P} {w : List T} + (h : ABTree G C w) : C ∈ G.allSubcats := by + induction h with + | @lex a c ha => + exact List.mem_flatMap.mpr ⟨(a, c), ha, Cat.mem_subcats_self c⟩ + | @fwd A B w1 w2 _ _ ih1 _ => + obtain ⟨entry, hentry, hsub⟩ := List.mem_flatMap.mp ih1 + exact List.mem_flatMap.mpr ⟨entry, hentry, Cat.rslash_mem_subcats_left hsub⟩ + | @bwd A B w1 w2 _ _ _ ih2 => + obtain ⟨entry, hentry, hsub⟩ := List.mem_flatMap.mp ih2 + exact List.mem_flatMap.mpr ⟨entry, hentry, Cat.lslash_mem_subcats_right hsub⟩ + +/-- Convert a finite AB Categorial Grammar into a finite Context-Free Grammar. -/ +def toCFG (G : ABG P T) : CFG (Cat P) T where + start := Cat.atom G.distinguished + rules := + (G.lexicon.map fun entry => (entry.2, [Symbol.tm entry.1])) ++ + (G.allSubcats.filterMap fun c => + match c with + | Cat.rslash A B => some (A, [Symbol.nt (Cat.rslash A B), Symbol.nt B]) + | Cat.lslash B A => some (A, [Symbol.nt B, Symbol.nt (Cat.lslash B A)]) + | Cat.atom _ => none) + +/-- Helper list-level predicate for mutual structural recursion on `CFG.Yield` / `CFG.YieldList`. -/ +inductive ABYieldList (G : ABG P T) : List (Symbol (Cat P) T) → List T → Prop where + | nil : ABYieldList G [] [] + | cons_tm {a : T} {rhs : List (Symbol (Cat P) T)} {w : List T} : + ABYieldList G rhs w → ABYieldList G (Symbol.tm a :: rhs) (a :: w) + | cons_nt {C : Cat P} {rhs : List (Symbol (Cat P) T)} {w1 w2 : List T} : + ABTree G C w1 → ABYieldList G rhs w2 → ABYieldList G (Symbol.nt C :: rhs) (w1 ++ w2) + +mutual + theorem toCFG_sound {G : ABG P T} {C : Cat P} {w : List T} : + CFG.Yield (G.toCFG) C w → ABTree G C w + | CFG.Yield.rule hr hyl_raw => by + have hyl := toCFG_sound_list hyl_raw + simp [toCFG] at hr + rcases hr with ⟨a, c, hlex, rfl, rfl⟩ | ⟨c, hsub, hmatch⟩ + · cases hyl with + | cons_tm hnil => + cases hnil + exact ABTree.lex hlex + · cases c with + | atom p => simp at hmatch + | rslash X Y => + simp at hmatch + obtain ⟨rfl, rfl⟩ := hmatch + cases hyl with + | cons_nt h1 hrest => + cases hrest with + | cons_nt h2 hnil => + cases hnil + simpa using ABTree.fwd h1 h2 + | lslash Y X => + simp at hmatch + obtain ⟨rfl, rfl⟩ := hmatch + cases hyl with + | cons_nt h1 hrest => + cases hrest with + | cons_nt h2 hnil => + cases hnil + simpa using ABTree.bwd h1 h2 + + theorem toCFG_sound_list {G : ABG P T} {α : List (Symbol (Cat P) T)} {w : List T} : + CFG.YieldList (G.toCFG) α w → ABYieldList G α w + | CFG.YieldList.nil => ABYieldList.nil + | CFG.YieldList.cons_tm h => ABYieldList.cons_tm (toCFG_sound_list h) + | CFG.YieldList.cons_nt hy hyl => + ABYieldList.cons_nt (toCFG_sound hy) (toCFG_sound_list hyl) +end + +theorem toCFG_complete {G : ABG P T} {C : Cat P} {w : List T} + (h : ABTree G C w) : CFG.Yield (G.toCFG) C w := by + induction h with + | @lex a c ha => + have hr : (c, [Symbol.tm a]) ∈ G.toCFG.rules := by + simp [toCFG] + left + exact ⟨a, c, ha, rfl, rfl⟩ + exact CFG.Yield.rule hr (CFG.YieldList.cons_tm CFG.YieldList.nil) + | @fwd A B w1 w2 h1 h2 ih1 ih2 => + have hsub : Cat.rslash A B ∈ G.allSubcats := h1.mem_allSubcats + have hr : (A, [Symbol.nt (Cat.rslash A B), Symbol.nt B]) ∈ G.toCFG.rules := by + simp [toCFG] + exact ⟨Cat.rslash A B, hsub, rfl⟩ + have hyl : CFG.YieldList (G.toCFG) [Symbol.nt (Cat.rslash A B), Symbol.nt B] (w1 ++ w2) := by + simpa using CFG.YieldList.cons_nt ih1 (CFG.YieldList.cons_nt ih2 CFG.YieldList.nil) + exact CFG.Yield.rule hr hyl + | @bwd A B w1 w2 h1 h2 ih1 ih2 => + have hsub : Cat.lslash B A ∈ G.allSubcats := h2.mem_allSubcats + have hr : (A, [Symbol.nt B, Symbol.nt (Cat.lslash B A)]) ∈ G.toCFG.rules := by + simp [toCFG] + exact ⟨Cat.lslash B A, hsub, rfl⟩ + have hyl : CFG.YieldList (G.toCFG) [Symbol.nt B, Symbol.nt (Cat.lslash B A)] (w1 ++ w2) := by + simpa using CFG.YieldList.cons_nt ih1 (CFG.YieldList.cons_nt ih2 CFG.YieldList.nil) + exact CFG.Yield.rule hr hyl + +/-- Bar-Hillel, Gaifman & Shamir (1960), Direction 1: + Every AB Categorial Grammar generates a context-free language. -/ +theorem toCFG_lang (G : ABG P T) (w : List T) : + G.toCFG.Lang w ↔ G.Lang w := by + rw [CFG.lang_iff_yield, ABG.lang_iff_abtree] + exact ⟨toCFG_sound, toCFG_complete⟩ + +end ABG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/BarHillel.lean b/LeanPool/FormalLinguistics/BarHillel.lean new file mode 100644 index 0000000000..93b04ec7b1 --- /dev/null +++ b/LeanPool/FormalLinguistics/BarHillel.lean @@ -0,0 +1,135 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.ABGtoCFG +public import LeanPool.FormalLinguistics.CFGtoABG + +/-! + ============================================================================== + Bar-Hillel, Gaifman & Shamir (1960) Equivalence Theorem in Lean 4 + ============================================================================== + "On Categorial and Phrase-Structure Grammars", + Bulletin of the Research Council of Israel, 9F(1), 1–16 (1960). + + Main machine-checked theorems (zero `sorry`, standard Lean 4 core only): + 1. `abg_to_cfg_equiv`: Every AB Categorial Grammar generates a context-free + language (and never generates the empty string). + 2. `cfg_to_abg_equiv`: Every finite Context-Free Grammar has a finite AB + Categorial Grammar generating precisely its non-empty strings. + 3. `bar_hillel_gaifman_shamir`: A formal language `L` is generated by an + AB Categorial Grammar if and only if `L` is an ε-free Context-Free + Language! + 4. Bonus corollary (`cfg_to_abg_unidirectional_depth2`): Every ε-free CFL is even + generated by a unidirectional (right-slash only) AB grammar of slash + depth ≤ 2. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Full computable translation: arbitrary finite CFG → finite AB Categorial Grammar. -/ +def cfgToABG [DecidableEq N] [DecidableEq T] (G : CFG N T) : ABG (GNFNT (BinNT N T)) T := + GNFtoABG.toABG (CNFtoGNF.cnfToGNF (cfgToCNF G)) + +/-- Direction 1 (ABG → CFG): + Every AB Categorial Grammar has a weakly equivalent Context-Free Grammar, + and its language is ε-free. -/ +theorem abg_to_cfg_equiv {P T : Type} (G : ABG P T) : + (∀ w, G.toCFG.Lang w ↔ G.Lang w) ∧ ¬ G.Lang [] := + ⟨ABG.toCFG_lang G, fun h => ABG.lang_nonempty h rfl⟩ + +/-- Direction 2 (CFG → ABG): + Every finite Context-Free Grammar has a finite AB Categorial Grammar + generating precisely its non-empty strings. -/ +theorem cfg_to_abg_equiv {N T : Type} [DecidableEq N] [DecidableEq T] (G : CFG N T) : + ∀ w, (cfgToABG G).Lang w ↔ G.Lang w ∧ w ≠ [] := by + intro w + unfold cfgToABG + rw [GNFtoABG.toABG_lang, CNFtoGNF.cnfToGNF_lang, cfgToCNF_lang] + +/-- **Bar-Hillel, Gaifman & Shamir Theorem (1960)** for ε-free Context-Free Grammars: + If `G` does not generate the empty string, then `cfgToABG G` is weakly equivalent to `G`. -/ +theorem cfg_to_abg_eps_free {N T : Type} [DecidableEq N] [DecidableEq T] + (G : CFG N T) (heps : ¬ G.Lang []) : + ∀ w, (cfgToABG G).Lang w ↔ G.Lang w := by + intro w + rw [cfg_to_abg_equiv G w] + constructor + · exact And.left + · intro h + refine ⟨h, ?_⟩ + intro hnil + subst hnil + exact heps h + +/-- Slash-nesting depth of a categorial type. -/ +def Cat.depth {P : Type} : Cat P → Nat + | Cat.atom _ => 0 + | Cat.rslash A B => 1 + max A.depth B.depth + | Cat.lslash B A => 1 + max B.depth A.depth + +/-- Whether a category uses only right slashes (`/`), i.e. unidirectional forward application. -/ +def Cat.isRightOnly {P : Type} : Cat P → Prop + | Cat.atom _ => True + | Cat.rslash A B => A.isRightOnly ∧ B.isRightOnly + | Cat.lslash _ _ => False + +/-- Corollary (unidirectional normal form, after Bar-Hillel, Gaifman & Shamir 1960): + Every ε-free Context-Free Language is generated by a *unidirectional* (right-slash only) + AB Categorial Grammar whose lexical categories all have slash depth ≤ 2! -/ +theorem cfg_to_abg_unidirectional_depth2 {N T : Type} [DecidableEq N] [DecidableEq T] + (G : CFG N T) : + ∀ a C, (a, C) ∈ (cfgToABG G).lexicon → C.isRightOnly ∧ C.depth ≤ 2 := by + intro a C hmem + rcases GNFtoABG.lex_shapes hmem with + ⟨U, rfl, _⟩ | ⟨U, V, rfl, _⟩ | ⟨U, V, W, rfl, _⟩ + · simp [Cat.isRightOnly, Cat.depth] + · simp [Cat.isRightOnly, Cat.depth] + · simp [Cat.isRightOnly, Cat.depth] + +/-- **Main Classification Theorem (Bar-Hillel, Gaifman & Shamir, 1960)**: + For any alphabet `T` with decidable equality, a language `L : List T → Prop` + is an AB Categorial Language if and only if `L` is an ε-free Context-Free Language. -/ +theorem bar_hillel_gaifman_shamir {T : Type} [DecidableEq T] (L : List T → Prop) : + (∃ (P : Type) (G : ABG P T), ∀ w, G.Lang w ↔ L w) ↔ + ((∃ (N : Type) (_ : DecidableEq N) (G : CFG N T), ∀ w, G.Lang w ↔ L w) ∧ ¬ L []) := by + constructor + · rintro ⟨P, G, hG⟩ + refine ⟨⟨Cat P, Classical.typeDecidableEq (Cat P), G.toCFG, ?_⟩, ?_⟩ + · intro w + rw [ABG.toCFG_lang, hG] + · intro hnil + exact ABG.lang_nonempty ((hG []).mpr hnil) rfl + · rintro ⟨⟨N, _, G, hG⟩, hne⟩ + refine ⟨GNFNT (BinNT N T), cfgToABG G, ?_⟩ + intro w + have hGeps : ¬ G.Lang [] := fun h => hne ((hG []).mp h) + rw [cfg_to_abg_eps_free G hGeps w, hG] + +/-- Clean version where primitive categories / nonterminals carry `DecidableEq`. -/ +theorem bar_hillel_gaifman_shamir_decidable {T : Type} [DecidableEq T] (L : List T → Prop) : + (∃ (P : Type) (_ : DecidableEq P) (G : ABG P T), ∀ w, G.Lang w ↔ L w) ↔ + ((∃ (N : Type) (_ : DecidableEq N) (G : CFG N T), ∀ w, G.Lang w ↔ L w) ∧ ¬ L []) := by + constructor + · rintro ⟨P, _, G, hG⟩ + refine ⟨⟨Cat P, inferInstance, G.toCFG, ?_⟩, ?_⟩ + · intro w + rw [ABG.toCFG_lang, hG] + · intro hnil + exact ABG.lang_nonempty ((hG []).mpr hnil) rfl + · rintro ⟨⟨N, _, G, hG⟩, hne⟩ + refine ⟨GNFNT (BinNT N T), inferInstance, cfgToABG G, ?_⟩ + intro w + have hGeps : ¬ G.Lang [] := fun h => hne ((hG []).mp h) + rw [cfg_to_abg_eps_free G hGeps w, hG] + +/-! ### Axiom Audit (just like verifying a formal proof release!) -/ + + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/BinMCFG.lean b/LeanPool/FormalLinguistics/BinMCFG.lean new file mode 100644 index 0000000000..7e2e8a689e --- /dev/null +++ b/LeanPool/FormalLinguistics/BinMCFG.lean @@ -0,0 +1,811 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.MCFG + +/-! + MCFG / LCFRS Binarization (Rank-≤-2 Normal Form) + Every finite Linear Non-Erasing MCFG `G` of arbitrary rank is computably + transformed into a weakly equivalent Linear Non-Erasing MCFG `binarizeMCFG G` + whose every rule has at most 2 RHS nonterminals (`r.rhs.length ≤ 2`). +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Nonterminals of the binarized MCFG: + `orig A` represents `A`; + `join Bs` (used for `Bs.length ≥ 2`) represents the flattened concatenation of the tuples of `Bs`. -/ +inductive BinMCFGNT (N : Type) where + | orig : N → BinMCFGNT N + | join : List N → BinMCFGNT N + deriving DecidableEq, Repr + +namespace BinMCFG + +variable {N T : Type} + +/-- Number of components in the concatenated tuples for a list of nonterminals. -/ +def sumDim (dim : N → Nat) : List N → Nat + | [] => 0 + | B :: Bs => dim B + sumDim dim Bs + +/-- Arity of an original nonterminal or of the tuple joining a suffix of a rule. -/ +def binDim (dim : N → Nat) : BinMCFGNT N → Nat + | BinMCFGNT.orig A => dim A + | BinMCFGNT.join Bs => max 1 (sumDim dim Bs) + +theorem sumDim_pos_of_cons {dim : N → Nat} (hpos : ∀ A, 1 ≤ dim A) (B : N) (Bs : List N) : + 1 ≤ sumDim dim (B :: Bs) := by + have := hpos B + simp [sumDim]; omega + +theorem binDim_join_cons {dim : N → Nat} (hpos : ∀ A, 1 ≤ dim A) (B : N) (Bs : List N) : + binDim dim (BinMCFGNT.join (B :: Bs)) = sumDim dim (B :: Bs) := by + have h1 := sumDim_pos_of_cons hpos B Bs + simp [binDim]; omega + +theorem binDim_pos {dim : N → Nat} (hpos : ∀ A, 1 ≤ dim A) (A : BinMCFGNT N) : + 1 ≤ binDim dim A := by + cases A with + | orig X => exact hpos X + | join Bs => simp [binDim]; omega + +/-- Cumulative dimension offset of index `i` inside `Bs`. -/ +def offset (dim : N → Nat) (Bs : List N) (i : Nat) : Nat := + sumDim dim (Bs.take i) + +theorem offset_lt_sumDim {dim : N → Nat} {Bs : List N} {i j : Nat} {B : N} + (hget : Bs[i]? = some B) (hj : j < dim B) : + offset dim Bs i + j < sumDim dim Bs := by + induction Bs generalizing i with + | nil => simp at hget + | cons hd tl ih => + cases i with + | zero => + simp at hget; subst hget + simp [offset, sumDim]; omega + | succ i' => + have h' : tl[i']? = some B := by simpa using hget + have ih' := ih h' + simp only [offset, List.take_succ_cons, sumDim] at ih' ⊢ + omega + +theorem offset_injective {dim : N → Nat} {Bs : List N} {i1 i2 j1 j2 : Nat} {B1 B2 : N} + (h1 : Bs[i1]? = some B1) (hj1 : j1 < dim B1) + (h2 : Bs[i2]? = some B2) (hj2 : j2 < dim B2) + (heq : offset dim Bs i1 + j1 = offset dim Bs i2 + j2) : + i1 = i2 ∧ j1 = j2 := by + induction Bs generalizing i1 i2 with + | nil => simp at h1 + | cons hd tl ih => + cases i1 with + | zero => + simp at h1; subst h1 + cases i2 with + | zero => + simp [offset, sumDim] at heq + exact ⟨rfl, heq⟩ + | succ i2' => + simp [offset, sumDim] at heq + omega + | succ i1' => + cases i2 with + | zero => + simp at h2; subst h2 + simp [offset, sumDim] at heq + omega + | succ i2' => + simp only [offset, List.take_succ_cons, sumDim] at heq + have h1' : tl[i1']? = some B1 := by simpa using h1 + have h2' : tl[i2']? = some B2 := by simpa using h2 + have ⟨hi, hj⟩ := ih h1' h2' (by simp only [offset]; omega) + exact ⟨by omega, hj⟩ + +theorem offset_surjective {dim : N → Nat} {Bs : List N} {k : Nat} + (hk : k < sumDim dim Bs) : + ∃ i B j, Bs[i]? = some B ∧ j < dim B ∧ offset dim Bs i + j = k := by + induction Bs generalizing k with + | nil => simp [sumDim] at hk + | cons hd tl ih => + simp only [sumDim] at hk + by_cases hlt : k < dim hd + · exact ⟨0, hd, k, rfl, hlt, by simp [offset, sumDim]⟩ + · obtain ⟨i, B, j, hget, hj, heq⟩ := ih (k := k - dim hd) (by omega) + refine ⟨i + 1, B, j, by simpa using hget, hj, ?_⟩ + simp only [offset, List.take_succ_cons, sumDim] at heq ⊢ + omega + +/-- Remap variables `(0, j) ↦ (0, j)` and `(i + 1, j) ↦ (1, offset dim tailBs i + j)`. -/ +def remapAtom (dim : N → Nat) (tailBs : List N) : MCFGAtom T → MCFGAtom T + | MCFGAtom.tm a => MCFGAtom.tm a + | MCFGAtom.var 0 j => MCFGAtom.var 0 j + | MCFGAtom.var (i + 1) j => MCFGAtom.var 1 (offset dim tailBs i + j) + +/-- Reindex rule templates after packing the tail arguments into one tuple. -/ +def remapYield (dim : N → Nat) (tailBs : List N) (y : List (List (MCFGAtom T))) : + List (List (MCFGAtom T)) := + y.map fun comp => comp.map (remapAtom dim tailBs) + +/-- Identity tuple-concatenation rule joining two nonterminals of dimensions `d1` and `d2`. -/ +def joinYield (d1 d2 : Nat) : List (List (MCFGAtom T)) := + ((List.range d1).map fun j => [MCFGAtom.var 0 j]) ++ + ((List.range d2).map fun j => [MCFGAtom.var 1 j]) + +/-- Generate all rank-2 join rules for a tail of length ≥ 2. -/ +def tailJoinRules (dim : N → Nat) : List N → List (MCFGRule (BinMCFGNT N) T) + | [] => [] + | [_] => [] + | [X, Y] => + [{ lhs := BinMCFGNT.join [X, Y] + rhs := [BinMCFGNT.orig X, BinMCFGNT.orig Y] + yield := joinYield (dim X) (dim Y) }] + | X :: Y :: Z :: rest => + { lhs := BinMCFGNT.join (X :: Y :: Z :: rest) + rhs := [BinMCFGNT.orig X, BinMCFGNT.join (Y :: Z :: rest)] + yield := joinYield (dim X) (sumDim dim (Y :: Z :: rest)) } :: + tailJoinRules dim (Y :: Z :: rest) + +/-- Replace a production with rules of rank at most two, joining its tail arguments. -/ +def binarizeRule (dim : N → Nat) (r : MCFGRule N T) : List (MCFGRule (BinMCFGNT N) T) := + match r.rhs with + | [] => [{ lhs := BinMCFGNT.orig r.lhs, rhs := [], yield := r.yield }] + | [B0] => [{ lhs := BinMCFGNT.orig r.lhs, rhs := [BinMCFGNT.orig B0], yield := r.yield }] + | [B0, B1] => + [{ lhs := BinMCFGNT.orig r.lhs, rhs := [BinMCFGNT.orig B0, BinMCFGNT.orig B1], yield := r.yield }] + | B0 :: B1 :: B2 :: rest => + { lhs := BinMCFGNT.orig r.lhs + rhs := [BinMCFGNT.orig B0, BinMCFGNT.join (B1 :: B2 :: rest)] + yield := remapYield dim (B1 :: B2 :: rest) r.yield } :: + tailJoinRules dim (B1 :: B2 :: rest) + +/-! ### Well-Formedness & Rank-≤-2 Proofs -/ + +theorem range_var0_props (d : Nat) : + let vs : List (List (MCFGAtom T)) := (List.range d).map fun j => [MCFGAtom.var 0 j] + vs.length = d ∧ + (vs.flatMap fun c => c.filterMap fun | MCFGAtom.tm _ => none | MCFGAtom.var i j => some (i, j)).Nodup ∧ + (∀ i j, (i, j) ∈ (vs.flatMap fun c => c.filterMap fun | MCFGAtom.tm _ => none | MCFGAtom.var i j => some (i, j)) ↔ + i = 0 ∧ j < d) := by + induction d with + | zero => + refine ⟨rfl, List.nodup_nil, ?_⟩ + intro i j; simp + | succ d ih => + obtain ⟨hlen, hnd, hmem⟩ := ih + rw [List.range_succ, List.map_append, List.map_singleton] + refine ⟨by simp [hlen], ?_, ?_⟩ + · rw [List.flatMap_append, List.nodup_append] + refine ⟨hnd, by simp, ?_⟩ + intro a ha b hb + simp at hb; subst hb + intro heq; subst heq + have := (hmem 0 d).mp ha; omega + · intro i j + rw [List.flatMap_append, List.mem_append, hmem i j] + simp only [List.flatMap_cons, List.flatMap_nil, List.filterMap_cons, List.filterMap_nil, + List.append_nil, List.mem_singleton, Prod.mk.injEq] + omega + +theorem range_var1_props (d : Nat) : + let vs : List (List (MCFGAtom T)) := (List.range d).map fun j => [MCFGAtom.var 1 j] + vs.length = d ∧ + (vs.flatMap fun c => c.filterMap fun | MCFGAtom.tm _ => none | MCFGAtom.var i j => some (i, j)).Nodup ∧ + (∀ i j, (i, j) ∈ (vs.flatMap fun c => c.filterMap fun | MCFGAtom.tm _ => none | MCFGAtom.var i j => some (i, j)) ↔ + i = 1 ∧ j < d) := by + induction d with + | zero => + refine ⟨rfl, List.nodup_nil, ?_⟩ + intro i j; simp + | succ d ih => + obtain ⟨hlen, hnd, hmem⟩ := ih + rw [List.range_succ, List.map_append, List.map_singleton] + refine ⟨by simp [hlen], ?_, ?_⟩ + · rw [List.flatMap_append, List.nodup_append] + refine ⟨hnd, by simp, ?_⟩ + intro a ha b hb + simp at hb; subst hb + intro heq; subst heq + have := (hmem 1 d).mp ha; omega + · intro i j + rw [List.flatMap_append, List.mem_append, hmem i j] + simp only [List.flatMap_cons, List.flatMap_nil, List.filterMap_cons, List.filterMap_nil, + List.append_nil, List.mem_singleton, Prod.mk.injEq] + omega + +theorem joinRule_wf {dim : N → Nat} {A B C : BinMCFGNT N} + (hA : binDim dim A = binDim dim B + binDim dim C) : + MCFGRule.WellFormed (binDim dim) + ({ lhs := A, rhs := [B, C], yield := joinYield (T := T) (binDim dim B) (binDim dim C) } : + MCFGRule (BinMCFGNT N) T) := by + obtain ⟨hl0, hnd0, hm0⟩ := range_var0_props (T := T) (binDim dim B) + obtain ⟨hl1, hnd1, hm1⟩ := range_var1_props (T := T) (binDim dim C) + refine ⟨?_, ?_, ?_⟩ + · simp [joinYield, hA] + · unfold MCFGRule.isLinear MCFGRule.varOccurrences + simp only [joinYield, List.flatMap_append] + rw [List.nodup_append] + refine ⟨hnd0, hnd1, ?_⟩ + intro ⟨i1, j1⟩ h1 ⟨i2, j2⟩ h2 heq + have := (hm0 i1 j1).mp h1 + have := (hm1 i2 j2).mp h2 + simp at heq; omega + · intro i j + unfold MCFGRule.varOccurrences + simp only [joinYield, List.flatMap_append, List.mem_append] + constructor + · rintro (h0 | h1) + · obtain ⟨rfl, hj⟩ := (hm0 i j).mp h0; exact ⟨B, rfl, hj⟩ + · obtain ⟨rfl, hj⟩ := (hm1 i j).mp h1; exact ⟨C, rfl, hj⟩ + · rintro ⟨X, hget, hj⟩ + cases i with + | zero => simp at hget; subst hget; left; exact (hm0 0 j).mpr ⟨rfl, hj⟩ + | succ i' => + cases i' with + | zero => simp at hget; subst hget; right; exact (hm1 1 j).mpr ⟨rfl, hj⟩ + | succ _ => simp at hget + +theorem tailJoinRules_wf {dim : N → Nat} (hpos : ∀ A, 1 ≤ dim A) : + ∀ Bs r, r ∈ tailJoinRules (T := T) dim Bs → + r.WellFormed (binDim dim) ∧ r.rhs.length ≤ 2 := by + intro Bs + match Bs with + | [] => intro _ h; simp [tailJoinRules] at h + | [_] => intro _ h; simp [tailJoinRules] at h + | [X, Y] => + intro r h + simp [tailJoinRules] at h; subst h + refine ⟨?_, by simp⟩ + have hA : binDim dim (BinMCFGNT.join [X, Y]) = + binDim dim (BinMCFGNT.orig X) + binDim dim (BinMCFGNT.orig Y) := by + rw [binDim_join_cons hpos]; simp [binDim, sumDim] + simpa [binDim] using joinRule_wf (T := T) hA + | X :: Y :: Z :: rest => + intro r h + simp only [tailJoinRules, List.mem_cons] at h + rcases h with rfl | ht + · refine ⟨?_, by simp⟩ + have hA : binDim dim (BinMCFGNT.join (X :: Y :: Z :: rest)) = + binDim dim (BinMCFGNT.orig X) + binDim dim (BinMCFGNT.join (Y :: Z :: rest)) := by + rw [binDim_join_cons hpos, binDim_join_cons hpos]; simp [binDim, sumDim] + have hstep := joinRule_wf (T := T) hA + rw [binDim_join_cons hpos] at hstep + simpa [binDim] using hstep + · exact tailJoinRules_wf hpos (Y :: Z :: rest) r ht + +/-- Mapping helper: `varOccurrences` of a remapped rule equals mapping `(0,j)↦(0,j), (i+1,j)↦(1,offset+j)`. -/ +def remapCoord (dim : N → Nat) (tailBs : List N) : Nat × Nat → Nat × Nat + | (0, j) => (0, j) + | (i + 1, j) => (1, offset dim tailBs i + j) + +theorem varOccurrences_remapYield (dim : N → Nat) (tailBs : List N) + (lhs : BinMCFGNT N) (rhs : List (BinMCFGNT N)) (y : List (List (MCFGAtom T))) : + MCFGRule.varOccurrences { lhs := lhs, rhs := rhs, yield := remapYield dim tailBs y } = + (y.flatMap fun comp => comp.filterMap fun + | MCFGAtom.tm _ => none + | MCFGAtom.var i j => some (i, j)).map (remapCoord dim tailBs) := by + simp only [MCFGRule.varOccurrences, remapYield] + induction y with + | nil => rfl + | cons comp rest ih => + simp only [List.map_cons, List.flatMap_cons, List.map_append] + rw [ih] + congr 1 + induction comp with + | nil => rfl + | cons a t iha => + cases a with + | tm x => simp [remapAtom, iha] + | var i j => + cases i <;> simp [remapAtom, remapCoord, iha] + +theorem binarizeRule_wf {dim : N → Nat} (hpos : ∀ A, 1 ≤ dim A) + {r : MCFGRule N T} (hwf : r.WellFormed dim) : + ∀ r', r' ∈ binarizeRule dim r → r'.WellFormed (binDim dim) ∧ r'.rhs.length ≤ 2 := by + obtain ⟨hlen, hlin, hne⟩ := hwf + intro r' hr' + unfold binarizeRule at hr' + match hrhs : r.rhs with + | [] => + simp [hrhs] at hr'; subst hr' + refine ⟨⟨by simpa [binDim] using hlen, hlin, ?_⟩, by simp⟩ + intro i j + have := hne i j + simp [hrhs] at this ⊢ + exact this + | [B0] => + simp [hrhs] at hr'; subst hr' + refine ⟨⟨by simpa [binDim] using hlen, hlin, ?_⟩, by simp⟩ + intro i j + change (i, j) ∈ r.varOccurrences ↔ _ + rw [hne i j] + simp only [hrhs] + constructor + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => simp at hget; subst hget; exact ⟨BinMCFGNT.orig B0, rfl, hj⟩ + | succ _ => simp at hget + · rintro ⟨B', hget, hj⟩ + cases i with + | zero => simp at hget; subst hget; exact ⟨B0, rfl, hj⟩ + | succ _ => simp at hget + | [B0, B1] => + simp [hrhs] at hr'; subst hr' + refine ⟨⟨by simpa [binDim] using hlen, hlin, ?_⟩, by simp⟩ + intro i j + change (i, j) ∈ r.varOccurrences ↔ _ + rw [hne i j] + simp only [hrhs] + constructor + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => simp at hget; subst hget; exact ⟨BinMCFGNT.orig B0, rfl, hj⟩ + | succ i' => + cases i' with + | zero => simp at hget; subst hget; exact ⟨BinMCFGNT.orig B1, rfl, hj⟩ + | succ _ => simp at hget + · rintro ⟨B', hget, hj⟩ + cases i with + | zero => simp at hget; subst hget; exact ⟨B0, rfl, hj⟩ + | succ i' => + cases i' with + | zero => simp at hget; subst hget; exact ⟨B1, rfl, hj⟩ + | succ _ => simp at hget + | B0 :: B1 :: B2 :: rest => + simp only [hrhs, List.mem_cons] at hr' + rcases hr' with rfl | htail + · let tailBs := B1 :: B2 :: rest + refine ⟨⟨by simp [remapYield, binDim, hlen], ?_, ?_⟩, by simp⟩ + · -- Linearity: remapCoord is injective on r.varOccurrences! + unfold MCFGRule.isLinear + rw [varOccurrences_remapYield] + have hinj : ∀ p1 p2, p1 ∈ r.varOccurrences → p2 ∈ r.varOccurrences → + remapCoord dim tailBs p1 = remapCoord dim tailBs p2 → p1 = p2 := by + rintro ⟨i1, j1⟩ ⟨i2, j2⟩ hp1 hp2 heq + obtain ⟨X1, hX1, hj1⟩ := (hne i1 j1).mp hp1 + obtain ⟨X2, hX2, hj2⟩ := (hne i2 j2).mp hp2 + rw [hrhs] at hX1 hX2 + cases i1 with + | zero => + cases i2 with + | zero => simp [remapCoord] at heq; exact Prod.ext rfl heq + | succ _ => simp [remapCoord] at heq + | succ i1' => + cases i2 with + | zero => simp [remapCoord] at heq + | succ i2' => + simp only [remapCoord, Prod.mk.injEq, true_and] at heq + have h1' : tailBs[i1']? = some X1 := by simpa [tailBs] using hX1 + have h2' : tailBs[i2']? = some X2 := by simpa [tailBs] using hX2 + obtain ⟨hi, hj⟩ := offset_injective h1' hj1 h2' hj2 heq + exact Prod.ext (by omega) hj + -- Nodup of map under injection on list elements + have hnd_map : ∀ {α β : Type} {f : α → β} {l : List α}, + l.Nodup → (∀ x y, x ∈ l → y ∈ l → f x = f y → x = y) → (l.map f).Nodup := by + intro α β f l hnd hi + induction l with + | nil => exact List.nodup_nil + | cons a t iht => + rw [List.nodup_cons] at hnd + rw [List.map_cons, List.nodup_cons] + refine ⟨?_, iht hnd.2 (fun x y hx hy => hi x y (List.mem_cons_of_mem _ hx) (List.mem_cons_of_mem _ hy))⟩ + intro hm + obtain ⟨b, hb, hfb⟩ := List.mem_map.mp hm + have heq := hi b a (List.mem_cons_of_mem _ hb) (List.mem_cons_self ..) hfb + exact hnd.1 (heq ▸ hb) + exact hnd_map hlin hinj + · -- Non-erasing bijection + intro i j + rw [varOccurrences_remapYield, List.mem_map] + constructor + · rintro ⟨⟨i0, j0⟩, hmem, heq⟩ + obtain ⟨X, hX, hj0⟩ := (hne i0 j0).mp hmem + rw [hrhs] at hX + cases i0 with + | zero => + simp [remapCoord] at heq; obtain ⟨rfl, rfl⟩ := heq + simp at hX; subst hX + exact ⟨BinMCFGNT.orig B0, rfl, hj0⟩ + | succ i0' => + simp [remapCoord] at heq; obtain ⟨rfl, rfl⟩ := heq + have hX' : tailBs[i0']? = some X := by simpa [tailBs] using hX + refine ⟨BinMCFGNT.join tailBs, rfl, ?_⟩ + rw [binDim_join_cons hpos] + exact offset_lt_sumDim hX' hj0 + · rintro ⟨B', hget, hj⟩ + cases i with + | zero => + simp at hget; subst hget + exact ⟨(0, j), (hne 0 j).mpr ⟨B0, by simp [hrhs], hj⟩, rfl⟩ + | succ i' => + cases i' with + | zero => + simp at hget; subst hget + rw [binDim_join_cons hpos] at hj + obtain ⟨i0, X, j0, hX, hj0, hoff⟩ := offset_surjective hj + refine ⟨(i0 + 1, j0), (hne (i0 + 1) j0).mpr ⟨X, ?_, hj0⟩, ?_⟩ + · rw [hrhs]; simpa [tailBs] using hX + · simp [remapCoord, hoff] + | succ _ => simp at hget + · exact tailJoinRules_wf hpos (B1 :: B2 :: rest) r' htail + +/-- Construct the binarized (rank-≤-2) Linear Non-Erasing MCFG from `G`. -/ +def binarizeMCFG (G : MCFG N T) : MCFG (BinMCFGNT N) T where + start := BinMCFGNT.orig G.start + dim := binDim G.dim + dim_pos := binDim_pos G.dim_pos + dim_start := G.dim_start + rules := G.rules.flatMap (binarizeRule G.dim) + rules_wf := by + intro r' hr' + obtain ⟨r, hr, hbin⟩ := List.mem_flatMap.mp hr' + exact (binarizeRule_wf G.dim_pos (G.rules_wf r hr) r' hbin).1 + +theorem binarizeMCFG_rank_le_two (G : MCFG N T) : + ∀ r', r' ∈ (binarizeMCFG G).rules → r'.rhs.length ≤ 2 := by + intro r' hr' + obtain ⟨r, hr, hbin⟩ := List.mem_flatMap.mp hr' + exact (binarizeRule_wf G.dim_pos (G.rules_wf r hr) r' hbin).2 + +/-! ### Semantic Equivalence (`(binarizeMCFG G).Lang ↔ G.Lang`) -/ + +/-- Flattened lookup lemma: indexing `args.flatten` at `offset G.dim Bs i + j` recovers `args[i][j]`. -/ +theorem flatten_getElem?_offset {G : MCFG N T} {Bs : List N} {args : List (List (List T))} : + MCFG.YieldList G Bs args → + ∀ i j B, Bs[i]? = some B → j < G.dim B → + args.flatten[offset G.dim Bs i + j]? = + match args[i]? with + | some tup => tup[j]? + | none => none + | MCFG.YieldList.nil, _, _, _, hget, _ => by simp at hget + | MCFG.YieldList.cons (B := hd) (Bs := tl) (tup := tup) hy hrest, i, j, B, hget, hj => by + have htup_len : tup.length = G.dim hd := hy.length_eq + cases i with + | zero => + simp at hget; subst hget + have hlt : j < tup.length := by omega + simp only [List.flatten_cons, offset, List.take_zero, sumDim, Nat.zero_add, + List.getElem?_cons_zero, List.getElem?_append_left hlt] + | succ i' => + have h' : tl[i']? = some B := by simpa using hget + have ih' := flatten_getElem?_offset hrest i' j B h' hj + simp only [List.flatten_cons, offset, List.take_succ_cons, sumDim, List.getElem?_cons_succ] + rw [Nat.add_assoc, ← htup_len, List.getElem?_append_right (Nat.le_add_right _ _)] + simpa [offset, Nat.add_sub_cancel_left] using ih' + +theorem evalComp_remap {G : MCFG N T} {tailBs : List N} + {tup0 : List (List T)} {tailArgs : List (List (List T))} + (hyl : MCFG.YieldList G tailBs tailArgs) + (comp : List (MCFGAtom T)) + (hwf : ∀ i j, MCFGAtom.var (i + 1) j ∈ comp → ∃ B, tailBs[i]? = some B ∧ j < G.dim B) : + MCFG.evalComp [tup0, tailArgs.flatten] (comp.map (remapAtom G.dim tailBs)) = + MCFG.evalComp (tup0 :: tailArgs) comp := by + induction comp with + | nil => rfl + | cons a t ih => + have ih' := ih (fun i j hm => hwf i j (List.mem_cons_of_mem _ hm)) + cases a with + | tm x => simp [remapAtom, MCFG.evalComp, ih'] + | var i j => + cases i with + | zero => simp [remapAtom, MCFG.evalComp, ih'] + | succ i' => + obtain ⟨B, hB, hj⟩ := hwf i' j (List.mem_cons_self ..) + have hfl := flatten_getElem?_offset hyl i' j B hB hj + simp only [List.map_cons, remapAtom, MCFG.evalComp, List.getElem?_cons_succ, + List.getElem?_cons_zero, hfl, ih'] + cases tailArgs[i']? <;> rfl + +theorem evalYield_joinYield (tup1 tup2 : List (List T)) : + MCFG.evalYield [tup1, tup2] (joinYield tup1.length tup2.length) = tup1 ++ tup2 := by + unfold joinYield MCFG.evalYield + rw [List.map_append] + congr 1 + · have h0 : ∀ (pre mid : List (List T)), + (List.range mid.length).map (fun k => MCFG.evalComp [pre ++ mid, tup2] [MCFGAtom.var 0 (pre.length + k)]) = mid := by + intro pre mid + induction mid generalizing pre with + | nil => rfl + | cons a tl ih => + have hr : List.range (tl.length + 1) = 0 :: (List.range tl.length).map Nat.succ := + List.range_succ_eq_map (n := tl.length) + simp only [List.length_cons, hr, List.map_cons, List.map_map] + have hh : MCFG.evalComp [pre ++ a :: tl, tup2] [MCFGAtom.var 0 (pre.length + 0)] = a := by + simp [MCFG.evalComp] + rw [hh]; congr 1 + have htl := ih (pre ++ [a]) + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append] at htl + refine Eq.trans ?_ htl + apply List.map_congr_left + intro k _ + have hidx : pre.length + k.succ = pre.length + 1 + k := by omega + simp [Function.comp, hidx] + have h0' := h0 [] tup1 + simp only [List.nil_append, List.length_nil, Nat.zero_add] at h0' + rw [List.map_map]; exact h0' + · have h1 : ∀ (pre mid : List (List T)), + (List.range mid.length).map (fun k => MCFG.evalComp [tup1, pre ++ mid] [MCFGAtom.var 1 (pre.length + k)]) = mid := by + intro pre mid + induction mid generalizing pre with + | nil => rfl + | cons a tl ih => + have hr : List.range (tl.length + 1) = 0 :: (List.range tl.length).map Nat.succ := + List.range_succ_eq_map (n := tl.length) + simp only [List.length_cons, hr, List.map_cons, List.map_map] + have hh : MCFG.evalComp [tup1, pre ++ a :: tl] [MCFGAtom.var 1 (pre.length + 0)] = a := by + simp [MCFG.evalComp] + rw [hh]; congr 1 + have htl := ih (pre ++ [a]) + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append] at htl + refine Eq.trans ?_ htl + apply List.map_congr_left + intro k _ + have hidx : pre.length + k.succ = pre.length + 1 + k := by omega + simp [Function.comp, hidx] + have h1' := h1 [] tup2 + simp only [List.nil_append, List.length_nil, Nat.zero_add] at h1' + rw [List.map_map]; exact h1' + +/-- Interpret a binarized nonterminal by a yield or a concatenation of yields in the original +grammar. -/ +def binInterp (G : MCFG N T) : BinMCFGNT N → List (List T) → Prop + | BinMCFGNT.orig A, tup => MCFG.Yield G A tup + | BinMCFGNT.join Bs, tup => ∃ args, MCFG.YieldList G Bs args ∧ tup = args.flatten + +/-- Relate a list of binarized nonterminals to tuples interpreted in the original grammar. -/ +inductive BinInterpList (G : MCFG N T) : List (BinMCFGNT N) → List (List (List T)) → Prop where + | nil : BinInterpList G [] [] + | cons {A : BinMCFGNT N} {As : List (BinMCFGNT N)} + {tup : List (List T)} {tups : List (List (List T))} : + binInterp G A tup → BinInterpList G As tups → BinInterpList G (A :: As) (tup :: tups) + +theorem tailJoinRules_sound {dim : N → Nat} {Bs : List N} {r' : MCFGRule (BinMCFGNT N) T} + (h : r' ∈ tailJoinRules dim Bs) : + (∃ X Y, r' = { lhs := BinMCFGNT.join [X, Y], rhs := [BinMCFGNT.orig X, BinMCFGNT.orig Y], + yield := joinYield (dim X) (dim Y) }) ∨ + (∃ X Y Z rest, r' = { lhs := BinMCFGNT.join (X :: Y :: Z :: rest), + rhs := [BinMCFGNT.orig X, BinMCFGNT.join (Y :: Z :: rest)], + yield := joinYield (dim X) (sumDim dim (Y :: Z :: rest)) }) := by + match Bs with + | [] => simp [tailJoinRules] at h + | [_] => simp [tailJoinRules] at h + | [X, Y] => + simp [tailJoinRules] at h; subst h + left; exact ⟨X, Y, rfl⟩ + | X :: Y :: Z :: rest => + simp only [tailJoinRules, List.mem_cons] at h + rcases h with rfl | ht + · right; exact ⟨X, Y, Z, rest, rfl⟩ + · exact tailJoinRules_sound ht + +theorem flatten_length_eq_sumDim {G : MCFG N T} {Bs : List N} {args : List (List (List T))} : + MCFG.YieldList G Bs args → args.flatten.length = sumDim G.dim Bs + | MCFG.YieldList.nil => rfl + | MCFG.YieldList.cons hy hrest => by + simp [List.flatten_cons, sumDim, hy.length_eq, flatten_length_eq_sumDim hrest] + +mutual + theorem binarizeMCFG_sound {G : MCFG N T} {A : BinMCFGNT N} {tup : List (List T)} : + MCFG.Yield (binarizeMCFG G) A tup → binInterp G A tup + | MCFG.Yield.rule hr' hargs_raw => by + have hargs := binarizeMCFG_sound_list hargs_raw + obtain ⟨r, hr, hbin⟩ := List.mem_flatMap.mp hr' + unfold binarizeRule at hbin + match hrhs : r.rhs with + | [] => + simp [hrhs] at hbin; subst hbin + cases hargs + have hyl : MCFG.YieldList G r.rhs [] := by rw [hrhs]; exact MCFG.YieldList.nil + exact MCFG.Yield.rule hr hyl + | [B0] => + simp [hrhs] at hbin; subst hbin + cases hargs with + | @cons _ _ tup0 _ h0 hnil => + cases hnil + have hyl : MCFG.YieldList G r.rhs [tup0] := by + rw [hrhs]; exact MCFG.YieldList.cons h0 MCFG.YieldList.nil + exact MCFG.Yield.rule hr hyl + | [B0, B1] => + simp [hrhs] at hbin; subst hbin + cases hargs with + | @cons _ _ tup0 _ h0 hrest => + cases hrest with + | @cons _ _ tup1 _ h1 hnil => + cases hnil + have hyl : MCFG.YieldList G r.rhs [tup0, tup1] := by + rw [hrhs]; exact MCFG.YieldList.cons h0 (MCFG.YieldList.cons h1 MCFG.YieldList.nil) + exact MCFG.Yield.rule hr hyl + | B0 :: B1 :: B2 :: rest => + simp only [hrhs, List.mem_cons] at hbin + rcases hbin with rfl | htail + · cases hargs with + | @cons _ _ tup0 _ h0 hrest => + cases hrest with + | cons h1 hnil => + cases hnil + obtain ⟨tailArgs, htailY, rfl⟩ := h1 + have hne := (G.rules_wf r hr).2.2 + have hev : MCFG.evalYield [tup0, tailArgs.flatten] (remapYield G.dim (B1 :: B2 :: rest) r.yield) = + MCFG.evalYield (tup0 :: tailArgs) r.yield := by + unfold MCFG.evalYield remapYield + rw [List.map_map] + apply List.map_congr_left + intro comp hcomp + apply evalComp_remap htailY comp + intro i j hm + have hvar : (i + 1, j) ∈ r.varOccurrences := by + simp only [MCFGRule.varOccurrences, List.mem_flatMap, List.mem_filterMap] + exact ⟨comp, hcomp, MCFGAtom.var (i + 1) j, hm, rfl⟩ + obtain ⟨B, hB, hj⟩ := (hne (i + 1) j).mp hvar + rw [hrhs] at hB + exact ⟨B, by simpa using hB, hj⟩ + rw [hev] + have hyl : MCFG.YieldList G r.rhs (tup0 :: tailArgs) := by + rw [hrhs]; exact MCFG.YieldList.cons h0 htailY + exact MCFG.Yield.rule hr hyl + · rcases tailJoinRules_sound htail with ⟨X, Y, rfl⟩ | ⟨X, Y, Z, more, rfl⟩ + · cases hargs with + | @cons _ _ tupX _ hX hrest => + cases hrest with + | @cons _ _ tupY _ hY hnil => + cases hnil + refine ⟨[tupX, tupY], MCFG.YieldList.cons hX (MCFG.YieldList.cons hY MCFG.YieldList.nil), ?_⟩ + rw [← hX.length_eq, ← hY.length_eq, evalYield_joinYield] + simp + · cases hargs with + | @cons _ _ tupX _ hX hrest => + cases hrest with + | cons hRest hnil => + cases hnil + obtain ⟨tailArgs, htailY, rfl⟩ := hRest + refine ⟨tupX :: tailArgs, MCFG.YieldList.cons hX htailY, ?_⟩ + rw [← hX.length_eq, ← flatten_length_eq_sumDim htailY, evalYield_joinYield] + simp + + theorem binarizeMCFG_sound_list {G : MCFG N T} {As : List (BinMCFGNT N)} + {args : List (List (List T))} : + MCFG.YieldList (binarizeMCFG G) As args → BinInterpList G As args + | MCFG.YieldList.nil => BinInterpList.nil + | MCFG.YieldList.cons hy hrest => + BinInterpList.cons (binarizeMCFG_sound hy) (binarizeMCFG_sound_list hrest) +end + +/-- Helper predicate for completeness: `YieldList` where every element has already been lifted to `binarizeMCFG`. -/ +inductive BinYieldList (G : MCFG N T) : List N → List (List (List T)) → Prop where + | nil : BinYieldList G [] [] + | cons {B : N} {Bs : List N} {tup : List (List T)} {tups : List (List (List T))} : + MCFG.Yield (binarizeMCFG G) (BinMCFGNT.orig B) tup → + MCFG.Yield G B tup → + BinYieldList G Bs tups → + BinYieldList G (B :: Bs) (tup :: tups) + +theorem binYieldList_to_orig {G : MCFG N T} {Bs : List N} {args : List (List (List T))} : + BinYieldList G Bs args → MCFG.YieldList G Bs args + | BinYieldList.nil => MCFG.YieldList.nil + | BinYieldList.cons _ hy hrest => MCFG.YieldList.cons hy (binYieldList_to_orig hrest) + +theorem binYieldList_join {G : MCFG N T} : + ∀ Bs args, + (∀ r', r' ∈ tailJoinRules G.dim Bs → r' ∈ (binarizeMCFG G).rules) → + BinYieldList G Bs args → + Bs.length ≥ 2 → + MCFG.Yield (binarizeMCFG G) (BinMCFGNT.join Bs) args.flatten := by + intro Bs + match Bs with + | [] => intro _ _ _ hlen; simp at hlen + | [_] => intro _ _ _ hlen; simp at hlen + | [X, Y] => + intro args hrules hyl _ + cases hyl with + | cons hXb hX hrest => + cases hrest with + | cons hYb hY hnil => + cases hnil + have hr : { lhs := BinMCFGNT.join [X, Y], rhs := [BinMCFGNT.orig X, BinMCFGNT.orig Y], + yield := joinYield (T := T) (G.dim X) (G.dim Y) } ∈ (binarizeMCFG G).rules := + hrules _ (by simp [tailJoinRules]) + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons hXb (MCFG.YieldList.cons hYb MCFG.YieldList.nil)) + rw [← hX.length_eq, ← hY.length_eq, evalYield_joinYield] at hy + simpa using hy + | X :: Y :: Z :: rest => + intro args hrules hyl _ + cases hyl with + | cons hXb hX hrest => + have htail := binYieldList_join (Y :: Z :: rest) _ + (fun r' hm => hrules r' (by simp [tailJoinRules, hm])) hrest (by simp) + have hr : { lhs := BinMCFGNT.join (X :: Y :: Z :: rest), + rhs := [BinMCFGNT.orig X, BinMCFGNT.join (Y :: Z :: rest)], + yield := joinYield (T := T) (G.dim X) (sumDim G.dim (Y :: Z :: rest)) } ∈ + (binarizeMCFG G).rules := + hrules _ (by simp [tailJoinRules]) + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons hXb (MCFG.YieldList.cons htail MCFG.YieldList.nil)) + have hfl_len := flatten_length_eq_sumDim (binYieldList_to_orig hrest) + rw [← hX.length_eq, ← hfl_len, evalYield_joinYield] at hy + simpa using hy + +mutual + theorem binarizeMCFG_complete {G : MCFG N T} {A : N} {tup : List (List T)} : + MCFG.Yield G A tup → MCFG.Yield (binarizeMCFG G) (BinMCFGNT.orig A) tup + | MCFG.Yield.rule (r := r) hr hargs_raw => by + have hargs := binarizeMCFG_complete_list hargs_raw + match hrhs : r.rhs with + | [] => + rw [hrhs] at hargs + cases hargs + have hr' : { lhs := BinMCFGNT.orig r.lhs, rhs := [], yield := r.yield } ∈ (binarizeMCFG G).rules := + List.mem_flatMap.mpr ⟨r, hr, by simp [binarizeRule, hrhs]⟩ + exact MCFG.Yield.rule hr' MCFG.YieldList.nil + | [B0] => + rw [hrhs] at hargs + cases hargs with + | cons h0b _ hnil => + cases hnil + have hr' : { lhs := BinMCFGNT.orig r.lhs, rhs := [BinMCFGNT.orig B0], yield := r.yield } ∈ + (binarizeMCFG G).rules := + List.mem_flatMap.mpr ⟨r, hr, by simp [binarizeRule, hrhs]⟩ + exact MCFG.Yield.rule hr' (MCFG.YieldList.cons h0b MCFG.YieldList.nil) + | [B0, B1] => + rw [hrhs] at hargs + cases hargs with + | cons h0b _ hrest => + cases hrest with + | cons h1b _ hnil => + cases hnil + have hr' : { lhs := BinMCFGNT.orig r.lhs, rhs := [BinMCFGNT.orig B0, BinMCFGNT.orig B1], + yield := r.yield } ∈ (binarizeMCFG G).rules := + List.mem_flatMap.mpr ⟨r, hr, by simp [binarizeRule, hrhs]⟩ + exact MCFG.Yield.rule hr' (MCFG.YieldList.cons h0b (MCFG.YieldList.cons h1b MCFG.YieldList.nil)) + | B0 :: B1 :: B2 :: rest => + rw [hrhs] at hargs + cases hargs with + | @cons _ _ tup0 tailArgs h0b _ hrest => + have htail_rules : ∀ r', r' ∈ tailJoinRules G.dim (B1 :: B2 :: rest) → + r' ∈ (binarizeMCFG G).rules := fun r' hm => + List.mem_flatMap.mpr ⟨r, hr, by simp [binarizeRule, hrhs, hm]⟩ + have hjoin := binYieldList_join (B1 :: B2 :: rest) tailArgs htail_rules hrest (by simp) + have hr' : { lhs := BinMCFGNT.orig r.lhs, + rhs := [BinMCFGNT.orig B0, BinMCFGNT.join (B1 :: B2 :: rest)], + yield := remapYield G.dim (B1 :: B2 :: rest) r.yield } ∈ (binarizeMCFG G).rules := + List.mem_flatMap.mpr ⟨r, hr, by simp [binarizeRule, hrhs]⟩ + have hy := MCFG.Yield.rule hr' (MCFG.YieldList.cons h0b (MCFG.YieldList.cons hjoin MCFG.YieldList.nil)) + have hne := (G.rules_wf r hr).2.2 + have hev : MCFG.evalYield [tup0, tailArgs.flatten] (remapYield G.dim (B1 :: B2 :: rest) r.yield) = + MCFG.evalYield (tup0 :: tailArgs) r.yield := by + unfold MCFG.evalYield remapYield + rw [List.map_map] + apply List.map_congr_left + intro comp hcomp + apply evalComp_remap (binYieldList_to_orig hrest) comp + intro i j hm + have hvar : (i + 1, j) ∈ r.varOccurrences := by + simp only [MCFGRule.varOccurrences, List.mem_flatMap, List.mem_filterMap] + exact ⟨comp, hcomp, MCFGAtom.var (i + 1) j, hm, rfl⟩ + obtain ⟨B, hB, hj⟩ := (hne (i + 1) j).mp hvar + rw [hrhs] at hB + exact ⟨B, by simpa using hB, hj⟩ + rw [hev] at hy + exact hy + + theorem binarizeMCFG_complete_list {G : MCFG N T} {Bs : List N} {args : List (List (List T))} : + MCFG.YieldList G Bs args → BinYieldList G Bs args + | MCFG.YieldList.nil => BinYieldList.nil + | MCFG.YieldList.cons hy hrest => + BinYieldList.cons (binarizeMCFG_complete hy) hy (binarizeMCFG_complete_list hrest) +end + +/-- MCFG Binarization Theorem: every Linear Non-Erasing MCFG has a weakly equivalent + rank-≤-2 Linear Non-Erasing MCFG. -/ +theorem binarizeMCFG_lang (G : MCFG N T) (w : List T) : + (binarizeMCFG G).Lang w ↔ G.Lang w := + ⟨binarizeMCFG_sound, binarizeMCFG_complete⟩ + +end BinMCFG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/CFG.lean b/LeanPool/FormalLinguistics/CFG.lean new file mode 100644 index 0000000000..9e16da4ccb --- /dev/null +++ b/LeanPool/FormalLinguistics/CFG.lean @@ -0,0 +1,206 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import Init + +/-! + Context-Free Grammars (Chomsky, 1956/1959) + Standard string-rewriting definition + equivalence with parse-tree derivations (`Yield`). +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Grammar symbols: either a nonterminal `N` or a terminal `T`. -/ +inductive Symbol (N T : Type) where + | nt : N → Symbol N T + | tm : T → Symbol N T + deriving DecidableEq, Repr + +/-- A finite Context-Free Grammar over nonterminals `N` and terminals `T`. -/ +structure CFG (N T : Type) where + /-- Nonterminal from which complete words are derived. -/ + start : N + /-- Finite list of pairs of a nonterminal and its replacement word. -/ + rules : List (N × List (Symbol N T)) + +namespace CFG + +variable {N T : Type} + +/-- Single-step context-free rewriting: `u A v ⇒ u rhs v` when `(A, rhs) ∈ G.rules`. -/ +inductive Step (G : CFG N T) : List (Symbol N T) → List (Symbol N T) → Prop where + | mk (u v rhs : List (Symbol N T)) (A : N) : + (A, rhs) ∈ G.rules → + Step G (u ++ [Symbol.nt A] ++ v) (u ++ rhs ++ v) + +/-- Multi-step derivation: reflexive-transitive closure of `Step`. -/ +inductive Derives (G : CFG N T) : List (Symbol N T) → List (Symbol N T) → Prop where + | refl (u : List (Symbol N T)) : Derives G u u + | tail {u v w : List (Symbol N T)} : Derives G u v → Step G v w → Derives G u w + +/-- The string language generated by a CFG. -/ +def Lang (G : CFG N T) (w : List T) : Prop := + Derives G [Symbol.nt G.start] (w.map Symbol.tm) + +theorem Derives.single {G : CFG N T} {u v : List (Symbol N T)} (h : Step G u v) : + Derives G u v := + Derives.tail (Derives.refl u) h + +theorem Derives.trans {G : CFG N T} {u v w : List (Symbol N T)} + (h1 : Derives G u v) (h2 : Derives G v w) : Derives G u w := by + induction h2 with + | refl => exact h1 + | tail _ hstep ih => exact Derives.tail ih hstep + +theorem Step.append_left {G : CFG N T} (p : List (Symbol N T)) {u v : List (Symbol N T)} + (h : Step G u v) : Step G (p ++ u) (p ++ v) := by + cases h with + | mk l r rhs A hr => + have h1 : p ++ (l ++ [Symbol.nt A] ++ r) = (p ++ l) ++ [Symbol.nt A] ++ r := by + simp [List.append_assoc] + have h2 : p ++ (l ++ rhs ++ r) = (p ++ l) ++ rhs ++ r := by + simp [List.append_assoc] + rw [h1, h2] + exact Step.mk (p ++ l) r rhs A hr + +theorem Step.append_right {G : CFG N T} (s : List (Symbol N T)) {u v : List (Symbol N T)} + (h : Step G u v) : Step G (u ++ s) (v ++ s) := by + cases h with + | mk l r rhs A hr => + have h1 : (l ++ [Symbol.nt A] ++ r) ++ s = l ++ [Symbol.nt A] ++ (r ++ s) := by + simp [List.append_assoc] + have h2 : (l ++ rhs ++ r) ++ s = l ++ rhs ++ (r ++ s) := by + simp [List.append_assoc] + rw [h1, h2] + exact Step.mk l (r ++ s) rhs A hr + +theorem Derives.append_left {G : CFG N T} (p : List (Symbol N T)) {u v : List (Symbol N T)} + (h : Derives G u v) : Derives G (p ++ u) (p ++ v) := by + induction h with + | refl => exact Derives.refl _ + | tail _ hstep ih => exact Derives.tail ih (Step.append_left p hstep) + +theorem Derives.append_right {G : CFG N T} (s : List (Symbol N T)) {u v : List (Symbol N T)} + (h : Derives G u v) : Derives G (u ++ s) (v ++ s) := by + induction h with + | refl => exact Derives.refl _ + | tail _ hstep ih => exact Derives.tail ih (Step.append_right s hstep) + +theorem Derives.append {G : CFG N T} {u1 v1 u2 v2 : List (Symbol N T)} + (h1 : Derives G u1 v1) (h2 : Derives G u2 v2) : Derives G (u1 ++ u2) (v1 ++ v2) := + Derives.trans (Derives.append_right u2 h1) (Derives.append_left v1 h2) + +/- Structural parse-tree derivations (mutually inductive for single nonterminals and sentential forms). -/ +mutual + /-- Parse-tree derivations from one nonterminal. -/ + inductive Yield (G : CFG N T) : N → List T → Prop where + | rule {A : N} {rhs : List (Symbol N T)} {w : List T} : + (A, rhs) ∈ G.rules → YieldList G rhs w → Yield G A w + + /-- Parse-forest derivations from a sentential form. -/ + inductive YieldList (G : CFG N T) : List (Symbol N T) → List T → Prop where + | nil : YieldList G [] [] + | cons_tm {a : T} {rhs : List (Symbol N T)} {w : List T} : + YieldList G rhs w → YieldList G (Symbol.tm a :: rhs) (a :: w) + | cons_nt {B : N} {rhs : List (Symbol N T)} {w1 w2 : List T} : + Yield G B w1 → YieldList G rhs w2 → YieldList G (Symbol.nt B :: rhs) (w1 ++ w2) +end + +theorem YieldList.append {G : CFG N T} {α β : List (Symbol N T)} {w1 w2 : List T} : + YieldList G α w1 → YieldList G β w2 → YieldList G (α ++ β) (w1 ++ w2) + | YieldList.nil, h2 => by simpa using h2 + | YieldList.cons_tm h1, h2 => YieldList.cons_tm (YieldList.append h1 h2) + | YieldList.cons_nt hy h1, h2 => by + simpa [List.append_assoc] using YieldList.cons_nt hy (YieldList.append h1 h2) + +theorem YieldList.of_terminals {G : CFG N T} (w : List T) : + YieldList G (w.map Symbol.tm) w := by + induction w with + | nil => exact YieldList.nil + | cons a t ih => exact YieldList.cons_tm ih + +theorem YieldList.split_append {G : CFG N T} {α β : List (Symbol N T)} {w : List T} + (h : YieldList G (α ++ β) w) : + ∃ w1 w2, w = w1 ++ w2 ∧ YieldList G α w1 ∧ YieldList G β w2 := by + induction α generalizing w with + | nil => + exact ⟨[], w, rfl, YieldList.nil, h⟩ + | cons s t ih => + cases s with + | tm a => + cases h with + | cons_tm ht => + obtain ⟨w1, w2, hw, h1, h2⟩ := ih ht + exact ⟨a :: w1, w2, by simp [hw], YieldList.cons_tm h1, h2⟩ + | nt B => + cases h with + | cons_nt hy ht => + obtain ⟨w1, w2, hw, h1, h2⟩ := ih ht + refine ⟨_ ++ w1, w2, ?_, YieldList.cons_nt hy h1, h2⟩ + simp [hw, List.append_assoc] + +theorem YieldList.step_back {G : CFG N T} {u v : List (Symbol N T)} {w : List T} + (hs : Step G u v) (hv : YieldList G v w) : YieldList G u w := by + cases hs with + | mk l r rhs A hr => + rw [List.append_assoc] at hv + obtain ⟨w1, w23, hw1, hl, h23⟩ := YieldList.split_append hv + obtain ⟨w2, w3, hw2, hrhs, hr'⟩ := YieldList.split_append h23 + have hA : Yield G A w2 := Yield.rule hr hrhs + have hAs : YieldList G [Symbol.nt A] w2 := by + simpa using YieldList.cons_nt hA YieldList.nil + have hres := YieldList.append (YieldList.append hl hAs) hr' + simpa [hw1, hw2, List.append_assoc] using hres + +theorem Derives.yieldList_back {G : CFG N T} {u v : List (Symbol N T)} {w : List T} + (h : Derives G u v) (hv : YieldList G v w) : YieldList G u w := by + induction h with + | refl => exact hv + | tail _ hstep ih => exact ih (YieldList.step_back hstep hv) + +theorem Derives.to_yieldList {G : CFG N T} {u : List (Symbol N T)} {w : List T} + (h : Derives G u (w.map Symbol.tm)) : YieldList G u w := + Derives.yieldList_back h (YieldList.of_terminals w) + +mutual + theorem derives_of_yield {G : CFG N T} {A : N} {w : List T} : + Yield G A w → Derives G [Symbol.nt A] (w.map Symbol.tm) + | Yield.rule (rhs := rhs) hr hyl => + have hstep : Step G [Symbol.nt A] rhs := by + simpa using Step.mk [] [] rhs A hr + Derives.trans (Derives.single hstep) (derives_of_yieldList hyl) + + theorem derives_of_yieldList {G : CFG N T} {α : List (Symbol N T)} {w : List T} : + YieldList G α w → Derives G α (w.map Symbol.tm) + | YieldList.nil => Derives.refl [] + | YieldList.cons_tm (a := a) h => by + simpa using Derives.append_left [Symbol.tm a] (derives_of_yieldList h) + | YieldList.cons_nt hy hyl => by + simpa [List.map_append] using Derives.append (derives_of_yield hy) (derives_of_yieldList hyl) +end + +/-- Fundamental equivalence: rewriting derivations ↔ structural parse trees. -/ +theorem derives_iff_yield {G : CFG N T} {A : N} {w : List T} : + Derives G [Symbol.nt A] (w.map Symbol.tm) ↔ Yield G A w := by + constructor + · intro h + have hyl := Derives.to_yieldList h + cases hyl with + | cons_nt hy hnil => + cases hnil + simpa using hy + · exact derives_of_yield + +theorem lang_iff_yield {G : CFG N T} {w : List T} : + G.Lang w ↔ Yield G G.start w := + derives_iff_yield + +end CFG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/CFGtoABG.lean b/LeanPool/FormalLinguistics/CFGtoABG.lean new file mode 100644 index 0000000000..03df722c68 --- /dev/null +++ b/LeanPool/FormalLinguistics/CFGtoABG.lean @@ -0,0 +1,138 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.GNF +public import LeanPool.FormalLinguistics.ABG + +/-! + 2-Standard Greibach Normal Form → AB Categorial Grammar + (the hard direction of Bar-Hillel, Gaifman & Shamir 1960, reached here via Greibach normal form) + Every rule in 2-GNF maps directly to a lexical category of slash-depth ≤ 2: + • U → a ↦ (a, atom U) + • U → a V ↦ (a, atom U / atom V) + • U → a V W ↦ (a, (atom U / atom W) / atom V) +-/ + +@[expose] public section + +namespace FormalLinguistics + +namespace GNFtoABG + +variable {N T : Type} + +/-- Give each Greibach-normal-form rule a categorial lexical entry headed by its terminal. -/ +def toABG (G : GNF2 N T) : ABG N T where + distinguished := G.start + lexicon := + (G.rules0.map fun (U, a) => (a, Cat.atom U)) ++ + (G.rules1.map fun (U, a, V) => (a, Cat.rslash (Cat.atom U) (Cat.atom V))) ++ + (G.rules2.map fun (U, a, V, W) => + (a, Cat.rslash (Cat.rslash (Cat.atom U) (Cat.atom W)) (Cat.atom V))) + +/-- Every category in `(toABG G).lexicon` is one of the 3 right-slash shapes of depth ≤ 2. -/ +theorem lex_shapes {G : GNF2 N T} {a : T} {C : Cat N} (h : (a, C) ∈ (toABG G).lexicon) : + (∃ U, C = Cat.atom U ∧ (U, a) ∈ G.rules0) ∨ + (∃ U V, C = Cat.rslash (Cat.atom U) (Cat.atom V) ∧ (U, a, V) ∈ G.rules1) ∨ + (∃ U V W, C = Cat.rslash (Cat.rslash (Cat.atom U) (Cat.atom W)) (Cat.atom V) ∧ + (U, a, V, W) ∈ G.rules2) := by + simp only [toABG, List.mem_append, List.mem_map] at h + rcases h with (⟨⟨U, a'⟩, hr, heq⟩ | ⟨⟨U, a', V⟩, hr, heq⟩) | ⟨⟨U, a', V, W⟩, hr, heq⟩ + · simp at heq; obtain ⟨rfl, rfl⟩ := heq + left; exact ⟨U, rfl, hr⟩ + · simp at heq; obtain ⟨rfl, rfl⟩ := heq + right; left; exact ⟨U, V, rfl, hr⟩ + · simp at heq; obtain ⟨rfl, rfl⟩ := heq + right; right; exact ⟨U, V, W, rfl, hr⟩ + +/-- Semantic invariant for all derivable ABTrees in `toABG G`: + - No `lslash` category is ever derivable. + - No category of depth ≥ 3 is ever derivable. + - Depth-2 `((U / W) / V)` only comes directly from a `rules2` lexical item. + - Depth-1 `(U / W)` comes either from a `rules1` lexical item or a `rules2` item applied to `V`. + - Depth-0 `(U)` yields a valid `GNF2.Yield G U w`. -/ +def treeInv (G : GNF2 N T) : Cat N → List T → Prop + | Cat.atom U, w => GNF2.Yield G U w + | Cat.rslash (Cat.atom U) (Cat.atom W), w => + (∃ a, w = [a] ∧ (U, a, W) ∈ G.rules1) ∨ + (∃ a V wv, w = a :: wv ∧ (U, a, V, W) ∈ G.rules2 ∧ GNF2.Yield G V wv) + | Cat.rslash (Cat.rslash (Cat.atom U) (Cat.atom W)) (Cat.atom V), w => + ∃ a, w = [a] ∧ (U, a, V, W) ∈ G.rules2 + | _, _ => False + +theorem toABG_sound_inv {G : GNF2 N T} {C : Cat N} {w : List T} + (h : ABG.ABTree (toABG G) C w) : treeInv G C w := by + induction h with + | @lex a C hlex => + rcases lex_shapes hlex with + ⟨U, rfl, hr⟩ | ⟨U, V, rfl, hr⟩ | ⟨U, V, W, rfl, hr⟩ + · exact GNF2.Yield.r0 hr + · left; exact ⟨a, rfl, hr⟩ + · exact ⟨a, rfl, hr⟩ + | @fwd A B w1 w2 _ _ ih1 ih2 => + cases A with + | atom U => + cases B with + | atom W => + rcases ih1 with ⟨a, rfl, hr1⟩ | ⟨a, V, wv, rfl, hr2, hV⟩ + · exact GNF2.Yield.r1 hr1 ih2 + · exact GNF2.Yield.r2 hr2 hV ih2 + | rslash _ _ => simp [treeInv] at ih1 + | lslash _ _ => simp [treeInv] at ih1 + | rslash A1 A2 => + cases A1 with + | atom U => + cases A2 with + | atom W => + cases B with + | atom V => + obtain ⟨a, rfl, hr2⟩ := ih1 + right; exact ⟨a, V, w2, rfl, hr2, ih2⟩ + | rslash _ _ => simp [treeInv] at ih1 + | lslash _ _ => simp [treeInv] at ih1 + | rslash _ _ => simp [treeInv] at ih1 + | lslash _ _ => simp [treeInv] at ih1 + | rslash _ _ => simp [treeInv] at ih1 + | lslash _ _ => simp [treeInv] at ih1 + | lslash _ _ => simp [treeInv] at ih1 + | @bwd A B w1 w2 _ _ _ ih2 => + simp [treeInv] at ih2 + +theorem toABG_complete {G : GNF2 N T} {U : N} {w : List T} + (h : GNF2.Yield G U w) : ABG.ABTree (toABG G) (Cat.atom U) w := by + induction h with + | @r0 U a hr => + apply ABG.ABTree.lex + simp only [toABG, List.mem_append, List.mem_map] + left; left + exact ⟨(U, a), hr, rfl⟩ + | @r1 U V a w hr _ ih => + have hlex : ABG.ABTree (toABG G) (Cat.rslash (Cat.atom U) (Cat.atom V)) [a] := by + apply ABG.ABTree.lex + simp only [toABG, List.mem_append, List.mem_map] + left; right + exact ⟨(U, a, V), hr, rfl⟩ + exact ABG.ABTree.fwd hlex ih + | @r2 U V W a w1 w2 hr _ _ ih1 ih2 => + have hlex : ABG.ABTree (toABG G) + (Cat.rslash (Cat.rslash (Cat.atom U) (Cat.atom W)) (Cat.atom V)) [a] := by + apply ABG.ABTree.lex + simp only [toABG, List.mem_append, List.mem_map] + right + exact ⟨(U, a, V, W), hr, rfl⟩ + have h1 : ABG.ABTree (toABG G) (Cat.rslash (Cat.atom U) (Cat.atom W)) (a :: w1) := + ABG.ABTree.fwd hlex ih1 + simpa [List.cons_append] using ABG.ABTree.fwd h1 ih2 + +theorem toABG_lang (G : GNF2 N T) (w : List T) : + (toABG G).Lang w ↔ G.Lang w := by + rw [ABG.lang_iff_abtree] + exact ⟨toABG_sound_inv, toABG_complete⟩ + +end GNFtoABG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/CNF.lean b/LeanPool/FormalLinguistics/CNF.lean new file mode 100644 index 0000000000..db9be6b2fc --- /dev/null +++ b/LeanPool/FormalLinguistics/CNF.lean @@ -0,0 +1,812 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.CFG +public import LeanPool.FormalLinguistics.Fixpoint + +/-! + Chomsky Normal Form (Chomsky, 1959) + Complete computable pipeline: CFG → BinCFG → NoEpsCFG → CNF, + preserving all non-empty strings (`CNF.Lang w ↔ CFG.Lang w ∧ w ≠ []`). +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Simple self-contained deduplication on lists (independent of Lean/Mathlib version). -/ +def dedupList [DecidableEq α] : List α → List α + | [] => [] + | a :: t => + let r := dedupList t + if a ∈ r then r else a :: r + +theorem mem_dedupList [DecidableEq α] {x : α} {l : List α} : + x ∈ dedupList l ↔ x ∈ l := by + induction l with + | nil => simp [dedupList] + | cons a t ih => + simp only [dedupList] + split + · next h => + rw [ih] + constructor + · intro hx; exact List.mem_cons_of_mem a hx + · intro hx + rcases List.mem_cons.mp hx with rfl | ht + · exact ih.mp h + · exact ht + · next h => + simp [ih] + +theorem nodup_dedupList [DecidableEq α] (l : List α) : (dedupList l).Nodup := by + induction l with + | nil => exact List.nodup_nil + | cons a t ih => + simp only [dedupList] + split + · exact ih + · next h => exact List.nodup_cons.mpr ⟨h, ih⟩ + +/-! ### Stage 1: Binarized CFG (all RHS have length ≤ 2, terminals isolated) -/ + +/-- An original nonterminal, a lifted terminal, or a symbol naming a rule suffix. -/ +inductive BinNT (N T : Type) where + | orig : N → BinNT N T + | tm : T → BinNT N T + | tail : List (Symbol N T) → BinNT N T + deriving DecidableEq, Repr + +/-- A grammar whose productions have only empty, terminal, unary, or binary right-hand sides. -/ +structure BinCFG (N T : Type) where + /-- Start nonterminal of the binarized grammar. -/ + start : N + /-- Sources of productions with an empty right-hand side. -/ + epsRules : List N + /-- Terminal productions, encoded as a source and a terminal. -/ + termRules : List (N × T) + /-- Unary productions, encoded as a source and a replacement nonterminal. -/ + unitRules : List (N × N) + /-- Binary productions, encoded as a source and two replacement nonterminals. -/ + binRules : List (N × N × N) + +namespace BinCFG + +variable {N T : Type} + +/-- Parse-tree derivations for the four forms of binarized productions. -/ +inductive Yield (G : BinCFG N T) : N → List T → Prop where + | eps {A : N} : A ∈ G.epsRules → Yield G A [] + | tm {A : N} {a : T} : (A, a) ∈ G.termRules → Yield G A [a] + | unit {A B : N} {w : List T} : (A, B) ∈ G.unitRules → Yield G B w → Yield G A w + | bin {A B C : N} {w1 w2 : List T} : + (A, B, C) ∈ G.binRules → Yield G B w1 → Yield G C w2 → Yield G A (w1 ++ w2) + +end BinCFG + +namespace CFGtoBin + +variable {N T : Type} + +/-- Lift each symbol to the corresponding nonterminal of the binarized grammar. -/ +def symNT : Symbol N T → BinNT N T + | Symbol.nt A => BinNT.orig A + | Symbol.tm a => BinNT.tm a + +/-- Binary rules generated when expanding a tail of length ≥ 2. -/ +def tailBinRules : List (Symbol N T) → List (BinNT N T × BinNT N T × BinNT N T) + | [] => [] + | [_] => [] + | [s1, s2] => [(BinNT.tail [s1, s2], symNT s1, symNT s2)] + | s1 :: s2 :: s3 :: rest => + (BinNT.tail (s1 :: s2 :: s3 :: rest), symNT s1, BinNT.tail (s2 :: s3 :: rest)) :: + tailBinRules (s2 :: s3 :: rest) + +/-- Encode a right-hand side of length at least two as a chain of binary productions. -/ +def ruleBinRules (A : N) : List (Symbol N T) → List (BinNT N T × BinNT N T × BinNT N T) + | [] => [] + | [_] => [] + | [s1, s2] => [(BinNT.orig A, symNT s1, symNT s2)] + | s1 :: s2 :: s3 :: rest => + (BinNT.orig A, symNT s1, BinNT.tail (s2 :: s3 :: rest)) :: + tailBinRules (s2 :: s3 :: rest) + +/-- Collect the terminal symbols occurring in a right-hand side. -/ +def rhsTerminals (rhs : List (Symbol N T)) : List T := + rhs.filterMap fun + | Symbol.tm a => some a + | Symbol.nt _ => none + +/-- Binarize a context-free grammar by introducing names for terminals and rule suffixes. -/ +def toBinCFG (G : CFG N T) : BinCFG (BinNT N T) T where + start := BinNT.orig G.start + epsRules := G.rules.filterMap fun (A, rhs) => + match rhs with + | [] => some (BinNT.orig A) + | _ => none + termRules := + (G.rules.filterMap fun (A, rhs) => + match rhs with + | [Symbol.tm a] => some (BinNT.orig A, a) + | _ => none) ++ + (G.rules.flatMap fun (_, rhs) => (rhsTerminals rhs).map fun a => (BinNT.tm a, a)) + unitRules := G.rules.filterMap fun (A, rhs) => + match rhs with + | [Symbol.nt B] => some (BinNT.orig A, BinNT.orig B) + | _ => none + binRules := G.rules.flatMap fun (A, rhs) => ruleBinRules A rhs + +theorem tailBinRules_sound {rhs : List (Symbol N T)} {X Y Z : BinNT N T} + (h : (X, Y, Z) ∈ tailBinRules rhs) : + (∃ s1 s2, X = BinNT.tail [s1, s2] ∧ Y = symNT s1 ∧ Z = symNT s2) ∨ + (∃ s1 s2 s3 rest, X = BinNT.tail (s1 :: s2 :: s3 :: rest) ∧ + Y = symNT s1 ∧ Z = BinNT.tail (s2 :: s3 :: rest)) := by + match rhs with + | [] => simp [tailBinRules] at h + | [_] => simp [tailBinRules] at h + | [s1, s2] => + simp [tailBinRules] at h + obtain ⟨rfl, rfl, rfl⟩ := h + left; exact ⟨s1, s2, rfl, rfl, rfl⟩ + | s1 :: s2 :: s3 :: rest => + simp only [tailBinRules, List.mem_cons] at h + rcases h with h1 | h2 + · obtain ⟨rfl, rfl, rfl⟩ := h1 + right; exact ⟨s1, s2, s3, rest, rfl, rfl, rfl⟩ + · exact tailBinRules_sound h2 + +theorem ruleBinRules_sound {A : N} {rhs : List (Symbol N T)} {X Y Z : BinNT N T} + (h : (X, Y, Z) ∈ ruleBinRules A rhs) : + (X = BinNT.orig A ∧ + ((∃ s1 s2, rhs = [s1, s2] ∧ Y = symNT s1 ∧ Z = symNT s2) ∨ + (∃ s1 s2 s3 rest, rhs = s1 :: s2 :: s3 :: rest ∧ + Y = symNT s1 ∧ Z = BinNT.tail (s2 :: s3 :: rest)))) ∨ + (∃ s1 s2, X = BinNT.tail [s1, s2] ∧ Y = symNT s1 ∧ Z = symNT s2) ∨ + (∃ s1 s2 s3 rest, X = BinNT.tail (s1 :: s2 :: s3 :: rest) ∧ + Y = symNT s1 ∧ Z = BinNT.tail (s2 :: s3 :: rest)) := by + match rhs with + | [] => simp [ruleBinRules] at h + | [_] => simp [ruleBinRules] at h + | [s1, s2] => + simp [ruleBinRules] at h + obtain ⟨rfl, rfl, rfl⟩ := h + left; exact ⟨rfl, Or.inl ⟨s1, s2, rfl, rfl, rfl⟩⟩ + | s1 :: s2 :: s3 :: rest => + simp only [ruleBinRules, List.mem_cons] at h + rcases h with h1 | h2 + · obtain ⟨rfl, rfl, rfl⟩ := h1 + left; exact ⟨rfl, Or.inr ⟨s1, s2, s3, rest, rfl, rfl, rfl⟩⟩ + · right; exact tailBinRules_sound h2 + +/-- Interpret lifted nonterminals, terminal names, and rule suffixes as their original yields. -/ +def interp (G : CFG N T) : BinNT N T → List T → Prop + | BinNT.orig A, w => CFG.Yield G A w + | BinNT.tm a, w => w = [a] + | BinNT.tail rhs, w => CFG.YieldList G rhs w + +theorem interp_symNT {G : CFG N T} {s : Symbol N T} {w : List T} + (h : interp G (symNT s) w) : CFG.YieldList G [s] w := by + cases s with + | nt A => simpa using CFG.YieldList.cons_nt h CFG.YieldList.nil + | tm a => + simp [symNT, interp] at h + subst h + exact CFG.YieldList.cons_tm CFG.YieldList.nil + +theorem toBinCFG_sound {G : CFG N T} {X : BinNT N T} {w : List T} + (h : BinCFG.Yield (toBinCFG G) X w) : interp G X w := by + induction h with + | @eps X hmem => + simp [toBinCFG] at hmem + obtain ⟨A, rhs, hr, hmatch⟩ := hmem + cases rhs with + | nil => + simp at hmatch; subst hmatch + exact CFG.Yield.rule hr CFG.YieldList.nil + | cons _ _ => simp at hmatch + | @tm X a hmem => + simp [toBinCFG] at hmem + rcases hmem with ⟨A, rhs, hr, hmatch⟩ | ⟨A, rhs, _, ha, rfl, rfl⟩ + · cases rhs with + | nil => simp at hmatch + | cons s t => + cases s with + | nt _ => simp at hmatch + | tm b => + cases t with + | nil => + simp at hmatch; obtain ⟨rfl, rfl⟩ := hmatch + exact CFG.Yield.rule hr (CFG.YieldList.cons_tm CFG.YieldList.nil) + | cons _ _ => simp at hmatch + · rfl + | @unit X Y w hmem _ ih => + simp [toBinCFG] at hmem + obtain ⟨A, rhs, hr, hmatch⟩ := hmem + cases rhs with + | nil => simp at hmatch + | cons s t => + cases s with + | tm _ => simp at hmatch + | nt B => + cases t with + | nil => + simp at hmatch; obtain ⟨rfl, rfl⟩ := hmatch + exact CFG.Yield.rule hr (by simpa using CFG.YieldList.cons_nt ih CFG.YieldList.nil) + | cons _ _ => simp at hmatch + | @bin X Y Z w1 w2 hmem _ _ ih1 ih2 => + simp [toBinCFG] at hmem + obtain ⟨A, rhs, hr, hrb⟩ := hmem + rcases ruleBinRules_sound hrb with + ⟨rfl, ⟨s1, s2, rfl, rfl, rfl⟩ | ⟨s1, s2, s3, rest, rfl, rfl, rfl⟩⟩ | + ⟨s1, s2, rfl, rfl, rfl⟩ | + ⟨s1, s2, s3, rest, rfl, rfl, rfl⟩ + · exact CFG.Yield.rule hr (by simpa using CFG.YieldList.append (interp_symNT ih1) (interp_symNT ih2)) + · exact CFG.Yield.rule hr (by simpa using CFG.YieldList.append (interp_symNT ih1) ih2) + · simpa [interp] using CFG.YieldList.append (interp_symNT ih1) (interp_symNT ih2) + · simpa [interp] using CFG.YieldList.append (interp_symNT ih1) ih2 + +theorem mem_rhsTerminals {a : T} {rhs : List (Symbol N T)} (h : Symbol.tm a ∈ rhs) : + a ∈ rhsTerminals rhs := by + induction rhs with + | nil => simp at h + | cons s t ih => + rcases List.mem_cons.mp h with rfl | ht + · simp [rhsTerminals] + · simp only [rhsTerminals, List.filterMap_cons] + cases s with + | tm b => exact List.mem_cons_of_mem b (ih ht) + | nt B => exact ih ht + +theorem term_yield_of_mem {G : CFG N T} {A : N} {rhs : List (Symbol N T)} {a : T} + (hr : (A, rhs) ∈ G.rules) (ha : Symbol.tm a ∈ rhs) : + BinCFG.Yield (toBinCFG G) (BinNT.tm a) [a] := by + apply BinCFG.Yield.tm + simp [toBinCFG] + right + exact ⟨A, rhs, hr, mem_rhsTerminals ha⟩ + +/-- Helper inductive capturing `YieldList` where every NT has already been translated into `BinCFG.Yield`. -/ +inductive YieldListBin (BG : BinCFG (BinNT N T) T) : List (Symbol N T) → List T → Prop where + | nil : YieldListBin BG [] [] + | cons_tm {a : T} {rhs : List (Symbol N T)} {w : List T} : + YieldListBin BG rhs w → YieldListBin BG (Symbol.tm a :: rhs) (a :: w) + | cons_nt {B : N} {rhs : List (Symbol N T)} {w1 w2 : List T} : + BinCFG.Yield BG (BinNT.orig B) w1 → YieldListBin BG rhs w2 → + YieldListBin BG (Symbol.nt B :: rhs) (w1 ++ w2) + +theorem yieldListBin_head {G : CFG N T} {s : Symbol N T} {rhs : List (Symbol N T)} {w : List T} + (h : YieldListBin (toBinCFG G) (s :: rhs) w) + (htm : ∀ a, s = Symbol.tm a → BinCFG.Yield (toBinCFG G) (BinNT.tm a) [a]) : + ∃ w1 w2, w = w1 ++ w2 ∧ + BinCFG.Yield (toBinCFG G) (symNT s) w1 ∧ + YieldListBin (toBinCFG G) rhs w2 := by + cases s with + | tm a => + cases h with + | cons_tm hrest => + exact ⟨[a], _, rfl, htm a rfl, hrest⟩ + | nt B => + cases h with + | cons_nt hy hrest => + exact ⟨_, _, rfl, hy, hrest⟩ + +theorem yieldListBin_tail {G : CFG N T} {A0 : N} {rhs0 : List (Symbol N T)} + (hr0 : (A0, rhs0) ∈ G.rules) : + ∀ rhs w, + (∀ s, s ∈ rhs → s ∈ rhs0) → + (∀ r, r ∈ tailBinRules rhs → r ∈ (toBinCFG G).binRules) → + YieldListBin (toBinCFG G) rhs w → + rhs.length ≥ 2 → + BinCFG.Yield (toBinCFG G) (BinNT.tail rhs) w := by + intro rhs + induction rhs with + | nil => intro _ _ _ _ hlen; simp at hlen + | cons s1 t ih => + intro w hsub hrules hyl hlen + cases t with + | nil => simp at hlen + | cons s2 t2 => + cases t2 with + | nil => + have hbin : (BinNT.tail [s1, s2], symNT s1, symNT s2) ∈ (toBinCFG G).binRules := + hrules _ (by simp [tailBinRules]) + obtain ⟨w1, w23, hw1, hy1, hrest1⟩ := yieldListBin_head hyl (fun a ha => + term_yield_of_mem hr0 (hsub (Symbol.tm a) (by simp [ha]))) + obtain ⟨w2, w3, hw2, hy2, hrest2⟩ := yieldListBin_head hrest1 (fun a ha => + term_yield_of_mem hr0 (hsub (Symbol.tm a) (by simp [ha]))) + cases hrest2 + rw [hw1, hw2, List.append_nil] + exact BinCFG.Yield.bin hbin hy1 hy2 + | cons s3 rest => + have hbin : (BinNT.tail (s1 :: s2 :: s3 :: rest), symNT s1, BinNT.tail (s2 :: s3 :: rest)) ∈ + (toBinCFG G).binRules := + hrules _ (by simp [tailBinRules]) + obtain ⟨w1, w2, hw1, hy1, hrest1⟩ := yieldListBin_head hyl (fun a ha => + term_yield_of_mem hr0 (hsub (Symbol.tm a) (by simp [ha]))) + have htail := ih w2 + (fun s hs => hsub s (List.mem_cons_of_mem s1 hs)) + (fun r hr => hrules r (by simp [tailBinRules, hr])) + hrest1 (by simp) + rw [hw1] + exact BinCFG.Yield.bin hbin hy1 htail + +mutual + theorem toBinCFG_complete {G : CFG N T} {A : N} {w : List T} : + CFG.Yield G A w → BinCFG.Yield (toBinCFG G) (BinNT.orig A) w + | CFG.Yield.rule (rhs := rhs) hr hyl_raw => + let hyl := toBinCFG_complete_list hyl_raw + match rhs, hyl with + | [], YieldListBin.nil => + BinCFG.Yield.eps (by + simp [toBinCFG] + exact ⟨A, [], hr, rfl⟩) + | [Symbol.tm a], YieldListBin.cons_tm YieldListBin.nil => + BinCFG.Yield.tm (by + simp [toBinCFG] + exact ⟨A, [Symbol.tm a], hr, rfl⟩) + | [Symbol.nt B], YieldListBin.cons_nt hy YieldListBin.nil => by + rw [List.append_nil] + apply BinCFG.Yield.unit _ hy + simp [toBinCFG] + exact ⟨A, [Symbol.nt B], hr, rfl⟩ + | [s1, s2], hyl => by + have hbin : (BinNT.orig A, symNT s1, symNT s2) ∈ (toBinCFG G).binRules := by + simp [toBinCFG] + exact ⟨A, [s1, s2], hr, by simp [ruleBinRules]⟩ + obtain ⟨w1, w23, hw1, hy1, hrest1⟩ := yieldListBin_head hyl (fun a ha => + term_yield_of_mem hr (by simp [ha])) + obtain ⟨w2, w3, hw2, hy2, hrest2⟩ := yieldListBin_head hrest1 (fun a ha => + term_yield_of_mem hr (by simp [ha])) + cases hrest2 + rw [hw1, hw2, List.append_nil] + exact BinCFG.Yield.bin hbin hy1 hy2 + | s1 :: s2 :: s3 :: rest, hyl => by + have hbin : (BinNT.orig A, symNT s1, BinNT.tail (s2 :: s3 :: rest)) ∈ (toBinCFG G).binRules := by + simp [toBinCFG] + exact ⟨A, s1 :: s2 :: s3 :: rest, hr, by simp [ruleBinRules]⟩ + obtain ⟨w1, w2, hw1, hy1, hrest1⟩ := yieldListBin_head hyl (fun a ha => + term_yield_of_mem hr (by simp [ha])) + have htail_rules : ∀ r, r ∈ tailBinRules (s2 :: s3 :: rest) → r ∈ (toBinCFG G).binRules := by + intro r hrm + simp [toBinCFG] + exact ⟨A, s1 :: s2 :: s3 :: rest, hr, by simp [ruleBinRules, hrm]⟩ + have htail := yieldListBin_tail hr (s2 :: s3 :: rest) w2 + (fun s hs => List.mem_cons_of_mem s1 hs) + htail_rules hrest1 (by simp) + rw [hw1] + exact BinCFG.Yield.bin hbin hy1 htail + + theorem toBinCFG_complete_list {G : CFG N T} {rhs : List (Symbol N T)} {w : List T} : + CFG.YieldList G rhs w → YieldListBin (toBinCFG G) rhs w + | CFG.YieldList.nil => YieldListBin.nil + | CFG.YieldList.cons_tm h => YieldListBin.cons_tm (toBinCFG_complete_list h) + | CFG.YieldList.cons_nt hy hyl => + YieldListBin.cons_nt (toBinCFG_complete hy) (toBinCFG_complete_list hyl) +end + +theorem toBinCFG_yield_iff (G : CFG N T) (A : N) (w : List T) : + BinCFG.Yield (toBinCFG G) (BinNT.orig A) w ↔ CFG.Yield G A w := + ⟨toBinCFG_sound, toBinCFG_complete⟩ + +end CFGtoBin + +/-! ### Stage 2: Eliminating ε-rules (`BinCFG → NoEpsCFG`) -/ + +/-- A binarized grammar with terminal, unary, and binary productions. -/ +structure NoEpsCFG (N T : Type) where + /-- Start nonterminal of the epsilon-free grammar. -/ + start : N + /-- Terminal productions of the epsilon-free grammar. -/ + termRules : List (N × T) + /-- Unary productions of the epsilon-free grammar. -/ + unitRules : List (N × N) + /-- Binary productions of the epsilon-free grammar. -/ + binRules : List (N × N × N) + +namespace NoEpsCFG + +variable {N T : Type} + +/-- Parse-tree derivations in an epsilon-free binarized grammar. -/ +inductive Yield (G : NoEpsCFG N T) : N → List T → Prop where + | tm {A : N} {a : T} : (A, a) ∈ G.termRules → Yield G A [a] + | unit {A B : N} {w : List T} : (A, B) ∈ G.unitRules → Yield G B w → Yield G A w + | bin {A B C : N} {w1 w2 : List T} : + (A, B, C) ∈ G.binRules → Yield G B w1 → Yield G C w2 → Yield G A (w1 ++ w2) + +theorem yield_nonempty {G : NoEpsCFG N T} {A : N} {w : List T} (h : Yield G A w) : w ≠ [] := by + induction h with + | tm _ => simp + | unit _ _ ih => exact ih + | bin _ _ _ ih1 _ => + intro hnil + exact ih1 (List.append_eq_nil_iff.mp hnil).1 + +end NoEpsCFG + +namespace BinToNoEps + +variable {N T : Type} [DecidableEq N] + +/-- List the start symbol and all nonterminals occurring in the rules. -/ +def allNTsRaw (G : BinCFG N T) : List N := + G.start :: + (G.epsRules ++ + G.termRules.map Prod.fst ++ + G.unitRules.flatMap (fun (A, B) => [A, B]) ++ + G.binRules.flatMap (fun (A, B, C) => [A, B, C])) + +/-- Enumerate the nonterminals that appear in the grammar, without repetition. -/ +def allNTs (G : BinCFG N T) : List N := + dedupList (allNTsRaw G) + +/-- Test whether one step can establish nullability using already nullable nonterminals. -/ +def nullPred (G : BinCFG N T) (s : List N) (A : N) : Bool := + (A ∈ s) || + (A ∈ G.epsRules) || + G.unitRules.any (fun (X, Y) => X == A && Y ∈ s) || + G.binRules.any (fun (X, Y, Z) => X == A && Y ∈ s && Z ∈ s) + +/-- Compute the nullability fixed point by bounded iteration over the finite symbol list. -/ +def nullableList (G : BinCFG N T) : List N := + iterN (stepFilter (allNTs G) (nullPred G)) (allNTs G).length [] + +theorem nullPred_mono (G : BinCFG N T) : + ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, nullPred G s1 x = true → nullPred G s2 x = true := by + intro s1 s2 hsub x hx + simp only [nullPred, Bool.or_eq_true, decide_eq_true_eq, List.any_eq_true, + Bool.and_eq_true, beq_iff_eq] at hx ⊢ + rcases hx with ((h1 | h2) | ⟨⟨X, Y⟩, hm, rfl, hy⟩) | ⟨⟨X, Y, Z⟩, hm, ⟨rfl, hy⟩, hz⟩ + · left; left; left; exact hsub x h1 + · left; left; right; exact h2 + · left; right; exact ⟨(X, Y), hm, rfl, hsub Y hy⟩ + · right; exact ⟨(X, Y, Z), hm, ⟨rfl, hsub Y hy⟩, hsub Z hz⟩ + +theorem nullPred_infl (G : BinCFG N T) : + ∀ s x, x ∈ s → x ∈ allNTs G → nullPred G s x = true := by + intro s x hx _ + simp [nullPred, hx] + +theorem nullableList_sound {G : BinCFG N T} {A : N} (h : A ∈ nullableList G) : + BinCFG.Yield G A [] := by + apply fixpoint_sound (Q := fun X => BinCFG.Yield G X []) _ (allNTs G).length [] (by simp) A h + intro s hs x _ hpx + simp only [nullPred, Bool.or_eq_true, decide_eq_true_eq, List.any_eq_true, + Bool.and_eq_true, beq_iff_eq] at hpx + rcases hpx with ((h1 | h2) | ⟨⟨X, Y⟩, hm, rfl, hy⟩) | ⟨⟨X, Y, Z⟩, hm, ⟨rfl, hy⟩, hz⟩ + · exact hs x h1 + · exact BinCFG.Yield.eps h2 + · exact BinCFG.Yield.unit hm (hs Y hy) + · simpa using BinCFG.Yield.bin hm (hs Y hy) (hs Z hz) + +theorem mem_allNTs_of_eps {G : BinCFG N T} {A : N} (h : A ∈ G.epsRules) : A ∈ allNTs G := by + rw [allNTs, mem_dedupList] + simp [allNTsRaw, h] + +theorem mem_allNTs_of_unit_left {G : BinCFG N T} {A B : N} (h : (A, B) ∈ G.unitRules) : + A ∈ allNTs G := by + rw [allNTs, mem_dedupList] + simp only [allNTsRaw, List.mem_cons, List.mem_append, List.mem_flatMap] + right; left; right + exact ⟨(A, B), h, by simp⟩ + +theorem mem_allNTs_of_bin_left {G : BinCFG N T} {A B C : N} (h : (A, B, C) ∈ G.binRules) : + A ∈ allNTs G := by + rw [allNTs, mem_dedupList] + simp only [allNTsRaw, List.mem_cons, List.mem_append, List.mem_flatMap] + right; right + exact ⟨(A, B, C), h, by simp⟩ + +theorem nullableList_complete {G : BinCFG N T} {A : N} (h : BinCFG.Yield G A []) : + A ∈ nullableList G := by + generalize hw : ([] : List T) = w at h + induction h with + | @eps X heps => + apply fixpoint_closed (nodup_dedupList _) (nullPred_mono G) (nullPred_infl G) X + (mem_allNTs_of_eps heps) + simp [nullPred, heps] + | tm _ => simp at hw + | @unit X Y w' hu _ ih => + have hY := ih hw + apply fixpoint_closed (nodup_dedupList _) (nullPred_mono G) (nullPred_infl G) X + (mem_allNTs_of_unit_left hu) + simp only [nullPred, Bool.or_eq_true, List.any_eq_true, Bool.and_eq_true, + beq_iff_eq, decide_eq_true_eq] + left; right + exact ⟨(X, Y), hu, rfl, hY⟩ + | @bin X Y Z w1 w2 hb _ _ ih1 ih2 => + have ⟨h1, h2⟩ := List.append_eq_nil_iff.mp hw.symm + have hY := ih1 h1.symm + have hZ := ih2 h2.symm + apply fixpoint_closed (nodup_dedupList _) (nullPred_mono G) (nullPred_infl G) X + (mem_allNTs_of_bin_left hb) + simp only [nullPred, Bool.or_eq_true, List.any_eq_true, Bool.and_eq_true, + beq_iff_eq, decide_eq_true_eq] + right + exact ⟨(X, Y, Z), hb, ⟨rfl, hY⟩, hZ⟩ + +/-- Remove empty productions, adding unary rules when a binary child can disappear. -/ +def toNoEps (G : BinCFG N T) : NoEpsCFG N T where + start := G.start + termRules := G.termRules + unitRules := + G.unitRules ++ + (G.binRules.filterMap fun (A, B, C) => + if B ∈ nullableList G then some (A, C) else none) ++ + (G.binRules.filterMap fun (A, B, C) => + if C ∈ nullableList G then some (A, B) else none) + binRules := G.binRules + +theorem toNoEps_sound {G : BinCFG N T} {A : N} {w : List T} + (h : NoEpsCFG.Yield (toNoEps G) A w) : BinCFG.Yield G A w ∧ w ≠ [] := by + refine ⟨?_, NoEpsCFG.yield_nonempty h⟩ + induction h with + | tm htm => exact BinCFG.Yield.tm htm + | @unit A B w hu _ ih => + simp only [toNoEps, List.mem_append, List.mem_filterMap] at hu + rcases hu with (hu1 | ⟨⟨X, Y, Z⟩, hb, hif⟩) | ⟨⟨X, Y, Z⟩, hb, hif⟩ + · exact BinCFG.Yield.unit hu1 ih + · split at hif + · next hnull => + simp at hif; obtain ⟨rfl, rfl⟩ := hif + simpa using BinCFG.Yield.bin hb (nullableList_sound hnull) ih + · simp at hif + · split at hif + · next hnull => + simp at hif; obtain ⟨rfl, rfl⟩ := hif + simpa using BinCFG.Yield.bin hb ih (nullableList_sound hnull) + · simp at hif + | bin hb _ _ ih1 ih2 => + exact BinCFG.Yield.bin hb ih1 ih2 + +theorem toNoEps_complete {G : BinCFG N T} {A : N} {w : List T} + (h : BinCFG.Yield G A w) (hne : w ≠ []) : NoEpsCFG.Yield (toNoEps G) A w := by + induction h with + | eps _ => exact absurd rfl hne + | tm htm => exact NoEpsCFG.Yield.tm htm + | @unit A B w' hu _ ih => + have hu' : (A, B) ∈ (toNoEps G).unitRules := by + simp [toNoEps, hu] + exact NoEpsCFG.Yield.unit hu' (ih hne) + | @bin A B C w1 w2 hb hB hC ih1 ih2 => + by_cases hw1 : w1 = [] + · subst hw1 + simp at hne + have hnull : B ∈ nullableList G := nullableList_complete hB + have hu : (A, C) ∈ (toNoEps G).unitRules := by + simp only [toNoEps, List.mem_append, List.mem_filterMap] + left; right + exact ⟨(A, B, C), hb, by simp [hnull]⟩ + simpa using NoEpsCFG.Yield.unit hu (ih2 hne) + · by_cases hw2 : w2 = [] + · subst hw2 + simp at hne + have hnull : C ∈ nullableList G := nullableList_complete hC + have hu : (A, B) ∈ (toNoEps G).unitRules := by + simp only [toNoEps, List.mem_append, List.mem_filterMap] + right + exact ⟨(A, B, C), hb, by simp [hnull]⟩ + simpa using NoEpsCFG.Yield.unit hu (ih1 hne) + · exact NoEpsCFG.Yield.bin hb (ih1 hw1) (ih2 hw2) + +theorem toNoEps_yield_iff (G : BinCFG N T) (A : N) (w : List T) : + NoEpsCFG.Yield (toNoEps G) A w ↔ BinCFG.Yield G A w ∧ w ≠ [] := + ⟨toNoEps_sound, fun ⟨h, hne⟩ => toNoEps_complete h hne⟩ + +end BinToNoEps + +/-! ### Stage 3: Eliminating unit rules (`NoEpsCFG → CNF`) -/ + +/-- A Context-Free Grammar in Chomsky Normal Form: + every rule is either `A → a` (`termRules`) or `A → B C` (`binRules`). -/ +structure CNF (N T : Type) where + /-- Start nonterminal of the grammar in Chomsky normal form. -/ + start : N + /-- Productions whose right-hand side consists of one terminal. -/ + termRules : List (N × T) + /-- Productions whose right-hand side consists of two nonterminals. -/ + binRules : List (N × N × N) + +namespace CNF + +variable {N T : Type} + +/-- Parse-tree derivations in epsilon-free Chomsky normal form. -/ +inductive Yield (G : CNF N T) : N → List T → Prop where + | tm {A : N} {a : T} : (A, a) ∈ G.termRules → Yield G A [a] + | bin {A B C : N} {w1 w2 : List T} : + (A, B, C) ∈ G.binRules → Yield G B w1 → Yield G C w2 → Yield G A (w1 ++ w2) + +/-- Words derived from the start nonterminal in Chomsky normal form. -/ +def Lang (G : CNF N T) (w : List T) : Prop := + Yield G G.start w + +end CNF + +namespace NoEpsToCNF + +variable {N T : Type} [DecidableEq N] + +/-- Reflexive transitive closure of the unary productions. -/ +inductive UnitStar (G : NoEpsCFG N T) : N → N → Prop where + | refl (A : N) : UnitStar G A A + | step {A B C : N} : (A, B) ∈ G.unitRules → UnitStar G B C → UnitStar G A C + +/-- List the start symbol and the nonterminals occurring in the epsilon-free rules. -/ +def allNTsRaw (G : NoEpsCFG N T) : List N := + G.start :: + (G.termRules.map Prod.fst ++ + G.unitRules.flatMap (fun (A, B) => [A, B]) ++ + G.binRules.flatMap (fun (A, B, C) => [A, B, C])) + +/-- Enumerate the nonterminals used by the epsilon-free grammar. -/ +def allNTs (G : NoEpsCFG N T) : List N := + dedupList (allNTsRaw G) + +/-- Enumerate ordered pairs of nonterminals that can participate in a unary path. -/ +def allPairs (G : NoEpsCFG N T) : List (N × N) := + dedupList ((allNTs G).flatMap fun A => (allNTs G).map fun B => (A, B)) + +/-- Test whether a pair is reflexive, a direct unary rule, or reachable by extending a known path. +-/ +def unitPred (G : NoEpsCFG N T) (s : List (N × N)) (p : N × N) : Bool := + (p ∈ s) || + (p.1 == p.2) || + G.unitRules.any (fun (X, Y) => X == p.1 && (Y, p.2) ∈ s) + +/-- Compute all unary paths by bounded finite fixed-point iteration. -/ +def unitReach (G : NoEpsCFG N T) : List (N × N) := + iterN (stepFilter (allPairs G) (unitPred G)) (allPairs G).length [] + +theorem unitPred_mono (G : NoEpsCFG N T) : + ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, unitPred G s1 x = true → unitPred G s2 x = true := by + intro s1 s2 hsub ⟨A, B⟩ hx + simp only [unitPred, Bool.or_eq_true, decide_eq_true_eq, List.any_eq_true, + Bool.and_eq_true, beq_iff_eq] at hx ⊢ + rcases hx with (h1 | h2) | ⟨⟨X, Y⟩, hu, rfl, hy⟩ + · left; left; exact hsub (A, B) h1 + · left; right; exact h2 + · right; exact ⟨(X, Y), hu, rfl, hsub (Y, B) hy⟩ + +theorem unitPred_infl (G : NoEpsCFG N T) : + ∀ s x, x ∈ s → x ∈ allPairs G → unitPred G s x = true := by + intro s x hx _ + simp [unitPred, hx] + +theorem unitReach_sound {G : NoEpsCFG N T} {A B : N} (h : (A, B) ∈ unitReach G) : + UnitStar G A B := by + apply fixpoint_sound (Q := fun p => UnitStar G p.1 p.2) _ (allPairs G).length [] (by simp) (A, B) h + intro s hs ⟨X, Y⟩ _ hpx + simp only [unitPred, Bool.or_eq_true, decide_eq_true_eq, List.any_eq_true, + Bool.and_eq_true, beq_iff_eq] at hpx + rcases hpx with (h1 | h2) | ⟨⟨U, V⟩, hu, hUX, hVY⟩ + · exact hs (X, Y) h1 + · subst h2; exact UnitStar.refl X + · subst hUX; exact UnitStar.step hu (hs (V, Y) hVY) + +theorem mem_allPairs {G : NoEpsCFG N T} {A B : N} + (hA : A ∈ allNTs G) (hB : B ∈ allNTs G) : (A, B) ∈ allPairs G := by + rw [allPairs, mem_dedupList] + exact List.mem_flatMap.mpr ⟨A, hA, List.mem_map.mpr ⟨B, hB, rfl⟩⟩ + +theorem mem_allNTs_of_term {G : NoEpsCFG N T} {A : N} {a : T} (h : (A, a) ∈ G.termRules) : + A ∈ allNTs G := by + rw [allNTs, mem_dedupList] + simp only [allNTsRaw, List.mem_cons, List.mem_append, List.mem_map] + right; left; left + exact ⟨(A, a), h, rfl⟩ + +theorem mem_allNTs_of_unit_left {G : NoEpsCFG N T} {A B : N} (h : (A, B) ∈ G.unitRules) : + A ∈ allNTs G := by + rw [allNTs, mem_dedupList] + simp only [allNTsRaw, List.mem_cons, List.mem_append, List.mem_flatMap] + right; left; right + exact ⟨(A, B), h, by simp⟩ + +theorem mem_allNTs_of_bin_left {G : NoEpsCFG N T} {A B C : N} (h : (A, B, C) ∈ G.binRules) : + A ∈ allNTs G := by + rw [allNTs, mem_dedupList] + simp only [allNTsRaw, List.mem_cons, List.mem_append, List.mem_flatMap] + right; right + exact ⟨(A, B, C), h, by simp⟩ + +theorem unitReach_complete {G : NoEpsCFG N T} {A B : N} + (h : UnitStar G A B) (hB : B ∈ allNTs G) : (A, B) ∈ unitReach G := by + induction h with + | refl X => + apply fixpoint_closed (nodup_dedupList _) (unitPred_mono G) (unitPred_infl G) (X, X) + (mem_allPairs hB hB) + simp [unitPred] + | @step X Y Z hu _ ih => + have hYZ := ih hB + have hX : X ∈ allNTs G := mem_allNTs_of_unit_left hu + apply fixpoint_closed (nodup_dedupList _) (unitPred_mono G) (unitPred_infl G) (X, Z) + (mem_allPairs hX hB) + simp only [unitPred, Bool.or_eq_true, List.any_eq_true, Bool.and_eq_true, + beq_iff_eq, decide_eq_true_eq] + right + exact ⟨(X, Y), hu, rfl, hYZ⟩ + +/-- Eliminate unary productions by copying terminal and binary rules along unary paths. -/ +def toCNF (G : NoEpsCFG N T) : CNF N T where + start := G.start + termRules := (unitReach G).flatMap fun (A, B) => + G.termRules.filterMap fun (B', a) => if B' = B then some (A, a) else none + binRules := (unitReach G).flatMap fun (A, B) => + G.binRules.filterMap fun (B', C, D) => if B' = B then some (A, C, D) else none + +omit [DecidableEq N] in +theorem yield_of_unitStar {G : NoEpsCFG N T} {A B : N} {w : List T} + (hu : UnitStar G A B) (hy : NoEpsCFG.Yield G B w) : NoEpsCFG.Yield G A w := by + induction hu with + | refl _ => exact hy + | step hstep _ ih => exact NoEpsCFG.Yield.unit hstep (ih hy) + +theorem toCNF_sound {G : NoEpsCFG N T} {A : N} {w : List T} + (h : CNF.Yield (toCNF G) A w) : NoEpsCFG.Yield G A w := by + induction h with + | @tm A a htm => + simp only [toCNF, List.mem_flatMap, List.mem_filterMap] at htm + obtain ⟨⟨X, B⟩, hreach, ⟨B', a'⟩, htmG, hif⟩ := htm + split at hif + · next hEq => + simp at hif; obtain ⟨rfl, rfl⟩ := hif; subst hEq + exact yield_of_unitStar (unitReach_sound hreach) (NoEpsCFG.Yield.tm htmG) + · simp at hif + | @bin A C D w1 w2 hb _ _ ih1 ih2 => + simp only [toCNF, List.mem_flatMap, List.mem_filterMap] at hb + obtain ⟨⟨X, B⟩, hreach, ⟨B', C', D'⟩, hbG, hif⟩ := hb + split at hif + · next hEq => + simp at hif; obtain ⟨rfl, rfl, rfl⟩ := hif; subst hEq + exact yield_of_unitStar (unitReach_sound hreach) (NoEpsCFG.Yield.bin hbG ih1 ih2) + · simp at hif + +theorem toCNF_complete_aux {G : NoEpsCFG N T} {A B : N} {w : List T} + (hu : UnitStar G A B) (hy : NoEpsCFG.Yield G B w) : CNF.Yield (toCNF G) A w := by + induction hy generalizing A with + | @tm X a htm => + have hreach := unitReach_complete hu (mem_allNTs_of_term htm) + apply CNF.Yield.tm + simp only [toCNF, List.mem_flatMap, List.mem_filterMap] + exact ⟨(A, X), hreach, (X, a), htm, by simp⟩ + | @unit X Y w' hstep _ ih => + exact ih (by + clear ih + induction hu with + | refl _ => exact UnitStar.step hstep (UnitStar.refl _) + | step h1 _ ihu => exact UnitStar.step h1 (ihu hstep)) + | @bin X C D w1 w2 hb _ _ ih1 ih2 => + have hreach := unitReach_complete hu (mem_allNTs_of_bin_left hb) + have hb' : (A, C, D) ∈ (toCNF G).binRules := by + simp only [toCNF, List.mem_flatMap, List.mem_filterMap] + exact ⟨(A, X), hreach, (X, C, D), hb, by simp⟩ + exact CNF.Yield.bin hb' (ih1 (UnitStar.refl C)) (ih2 (UnitStar.refl D)) + +theorem toCNF_yield_iff (G : NoEpsCFG N T) (A : N) (w : List T) : + CNF.Yield (toCNF G) A w ↔ NoEpsCFG.Yield G A w := + ⟨toCNF_sound, toCNF_complete_aux (UnitStar.refl A)⟩ + +end NoEpsToCNF + +/-! ### Full CFG → CNF Conversion Theorem -/ + +/-- Convert any finite Context-Free Grammar into Chomsky Normal Form. -/ +def cfgToCNF [DecidableEq N] [DecidableEq T] (G : CFG N T) : CNF (BinNT N T) T := + NoEpsToCNF.toCNF (BinToNoEps.toNoEps (CFGtoBin.toBinCFG G)) + +/-- Chomsky Normal Form Theorem: + For any finite CFG `G`, `cfgToCNF G` generates exactly the non-empty strings of `G`. -/ +theorem cfgToCNF_lang [DecidableEq N] [DecidableEq T] (G : CFG N T) (w : List T) : + (cfgToCNF G).Lang w ↔ G.Lang w ∧ w ≠ [] := by + unfold CNF.Lang cfgToCNF + rw [NoEpsToCNF.toCNF_yield_iff, BinToNoEps.toNoEps_yield_iff] + change BinCFG.Yield (CFGtoBin.toBinCFG G) (BinNT.orig G.start) w ∧ w ≠ [] ↔ G.Lang w ∧ w ≠ [] + rw [CFGtoBin.toBinCFG_yield_iff, CFG.lang_iff_yield] + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/Fixpoint.lean b/LeanPool/FormalLinguistics/Fixpoint.lean new file mode 100644 index 0000000000..dca6e412a7 --- /dev/null +++ b/LeanPool/FormalLinguistics/Fixpoint.lean @@ -0,0 +1,188 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import Init + +/-! + Lightweight finite-universe monotone fixpoint helper (pure Lean 4, no Mathlib needed). + The iteration is a computable function. Its soundness proof (`fixpoint_sound`) is + choice-free; its convergence proof (`fixpoint_closed`) depends on `Classical.choice`. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- If `l1` has no duplicates and every element of `l1` lies in `l2`, then `l1.length ≤ l2.length`. -/ +theorem nodup_length_le [DecidableEq α] {l1 l2 : List α} + (hnd : l1.Nodup) (hsub : ∀ x, x ∈ l1 → x ∈ l2) : l1.length ≤ l2.length := by + induction l1 generalizing l2 with + | nil => simp + | cons a t ih => + rw [List.nodup_cons] at hnd + obtain ⟨ha_not, ht_nd⟩ := hnd + have ha_in : a ∈ l2 := hsub a (List.mem_cons_self ..) + have hsub' : ∀ x, x ∈ t → x ∈ l2.erase a := by + intro x hx + have hne : x ≠ a := fun h => ha_not (h ▸ hx) + exact List.mem_erase_of_ne hne |>.mpr (hsub x (List.mem_cons_of_mem a hx)) + have hle := ih ht_nd hsub' + have herase : (l2.erase a).length + 1 = l2.length := by + rw [List.length_erase_of_mem ha_in] + have hpos : 0 < l2.length := List.length_pos_of_mem ha_in + omega + simp + omega + +/-- Repeatedly apply a function `n` times. -/ +def iterN (f : α → α) : Nat → α → α + | 0, x => x + | n + 1, x => iterN f n (f x) + +section Fixpoint + +variable {α : Type} + +/-- One step of monotone closure inside a fixed universe `U`. -/ +def stepFilter (U : List α) (p : List α → α → Bool) (s : List α) : List α := + U.filter (p s) + +theorem stepFilter_nodup {U : List α} (hU : U.Nodup) (p : List α → α → Bool) (s : List α) : + (stepFilter U p s).Nodup := + hU.filter _ + +theorem stepFilter_subset_U {U : List α} (p : List α → α → Bool) (s : List α) : + ∀ x, x ∈ stepFilter U p s → x ∈ U := by + intro x hx + exact (List.mem_filter.mp hx).1 + +theorem stepFilter_mono {U : List α} {p : List α → α → Bool} + (hmono : ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, p s1 x = true → p s2 x = true) + {s1 s2 : List α} (hsub : ∀ x, x ∈ s1 → x ∈ s2) : + ∀ x, x ∈ stepFilter U p s1 → x ∈ stepFilter U p s2 := by + intro x hx + obtain ⟨hxU, hpx⟩ := List.mem_filter.mp hx + exact List.mem_filter.mpr ⟨hxU, hmono s1 s2 hsub x hpx⟩ + +theorem stepFilter_infl {U : List α} {p : List α → α → Bool} + (hinfl : ∀ s x, x ∈ s → x ∈ U → p s x = true) + {s : List α} (hsU : ∀ x, x ∈ s → x ∈ U) : + ∀ x, x ∈ s → x ∈ stepFilter U p s := by + intro x hx + exact List.mem_filter.mpr ⟨hsU x hx, hinfl s x hx (hsU x hx)⟩ + +theorem iterN_stepFilter_closed_of_closed {U : List α} {p : List α → α → Bool} + (hmono : ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, p s1 x = true → p s2 x = true) + (hinfl : ∀ s x, x ∈ s → x ∈ U → p s x = true) + {s : List α} (hsU : ∀ x, x ∈ s → x ∈ U) + (hclosed : ∀ x, x ∈ stepFilter U p s → x ∈ s) (k : Nat) : + (∀ x, x ∈ iterN (stepFilter U p) k s ↔ x ∈ s) := by + induction k generalizing s with + | zero => intro x; rfl + | succ k ih => + simp only [iterN] + have hstep_sub : ∀ x, x ∈ stepFilter U p s → x ∈ s := hclosed + have hs_sub : ∀ x, x ∈ s → x ∈ stepFilter U p s := stepFilter_infl hinfl hsU + have hstep_closed : ∀ x, x ∈ stepFilter U p (stepFilter U p s) → x ∈ stepFilter U p s := by + intro x hx + exact hs_sub x (hstep_sub x (stepFilter_mono hmono hstep_sub x hx)) + have hstepU : ∀ x, x ∈ stepFilter U p s → x ∈ U := stepFilter_subset_U p s + intro x + rw [ih hstepU hstep_closed] + exact ⟨hstep_sub x, hs_sub x⟩ + +/-- Constructive search for an element in `l1` not belonging to `l2`. -/ +theorem list_subset_or_exists_not_mem [DecidableEq α] (l1 l2 : List α) : + (∀ y, y ∈ l1 → y ∈ l2) ∨ (∃ y, y ∈ l1 ∧ y ∉ l2) := by + induction l1 with + | nil => left; intro _ h; simp at h + | cons a t ih => + if ha : a ∈ l2 then + rcases ih with hsub | ⟨y, hy1, hy2⟩ + · left + intro y hy + rcases List.mem_cons.mp hy with rfl | ht + · exact ha + · exact hsub y ht + · right + exact ⟨y, List.mem_cons_of_mem a hy1, hy2⟩ + else + right + exact ⟨a, List.mem_cons_self .., ha⟩ + +theorem iterN_stepFilter_fixpoint_aux [DecidableEq α] {U : List α} (hU : U.Nodup) + {p : List α → α → Bool} + (hmono : ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, p s1 x = true → p s2 x = true) + (hinfl : ∀ s x, x ∈ s → x ∈ U → p s x = true) : + ∀ k (s : List α), s.Nodup → (∀ x, x ∈ s → x ∈ U) → U.length ≤ s.length + k → + ∀ x, x ∈ stepFilter U p (iterN (stepFilter U p) k s) → x ∈ iterN (stepFilter U p) k s := by + intro k + induction k with + | zero => + intro s hsnd hsU hlen x hx + simp only [iterN] at hx ⊢ + if hxin : x ∈ s then + exact hxin + else + have hnd' : (x :: s).Nodup := List.nodup_cons.mpr ⟨hxin, hsnd⟩ + have hsub' : ∀ y, y ∈ x :: s → y ∈ U := by + intro y hy + rcases List.mem_cons.mp hy with rfl | hy' + · exact stepFilter_subset_U p s y hx + · exact hsU y hy' + have hle := nodup_length_le hnd' hsub' + simp at hle + omega + | succ k ih => + intro s hsnd hsU hlen + rcases list_subset_or_exists_not_mem (stepFilter U p s) s with hclosed | ⟨y, hy_in, hy_not⟩ + · intro x hx + have heq := iterN_stepFilter_closed_of_closed hmono hinfl hsU hclosed (k + 1) + have hsub1 : ∀ y, y ∈ iterN (stepFilter U p) (k + 1) s → y ∈ s := fun y hy => (heq y).mp hy + have hx_step_s : x ∈ stepFilter U p s := stepFilter_mono hmono hsub1 x hx + exact (heq x).mpr (hclosed x hx_step_s) + · simp only [iterN] + have hnd_ys : (y :: s).Nodup := List.nodup_cons.mpr ⟨hy_not, hsnd⟩ + have hsub_ys : ∀ z, z ∈ y :: s → z ∈ stepFilter U p s := by + intro z hz + rcases List.mem_cons.mp hz with rfl | hz' + · exact hy_in + · exact stepFilter_infl hinfl hsU z hz' + have hle := nodup_length_le hnd_ys hsub_ys + simp at hle + exact ih (stepFilter U p s) (stepFilter_nodup hU p s) (stepFilter_subset_U p s) (by omega) + +/-- Main finite-universe fixpoint theorem: starting from `[]`, after `U.length` steps, + `iterN (stepFilter U p) U.length []` is a fixpoint of `stepFilter U p`. -/ +theorem fixpoint_closed [DecidableEq α] {U : List α} (hU : U.Nodup) {p : List α → α → Bool} + (hmono : ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, p s1 x = true → p s2 x = true) + (hinfl : ∀ s x, x ∈ s → x ∈ U → p s x = true) : + let fp := iterN (stepFilter U p) U.length [] + ∀ x, x ∈ U → p fp x = true → x ∈ fp := by + intro fp x hxU hpx + have hcl := iterN_stepFilter_fixpoint_aux hU hmono hinfl U.length [] + List.nodup_nil (fun _ h => by simp at h) (by simp) + exact hcl x (List.mem_filter.mpr ⟨hxU, hpx⟩) + +/-- Least-fixpoint soundness: any predicate `Q` closed under `p` holds on all elements of `fp`. -/ +theorem fixpoint_sound {U : List α} {p : List α → α → Bool} {Q : α → Prop} + (hQ : ∀ s, (∀ y, y ∈ s → Q y) → ∀ x, x ∈ U → p s x = true → Q x) : + ∀ k (s : List α), (∀ y, y ∈ s → Q y) → + ∀ x, x ∈ iterN (stepFilter U p) k s → Q x := by + intro k + induction k with + | zero => intro s hs x hx; exact hs x hx + | succ k ih => + intro s hs x hx + apply ih (stepFilter U p s) _ x hx + intro y hy + obtain ⟨hyU, hpy⟩ := List.mem_filter.mp hy + exact hQ s hs y hyU hpy + +end Fixpoint +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/GNF.lean b/LeanPool/FormalLinguistics/GNF.lean new file mode 100644 index 0000000000..e24c8f5356 --- /dev/null +++ b/LeanPool/FormalLinguistics/GNF.lean @@ -0,0 +1,277 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.CNF + +/-! + 2-Standard Greibach Normal Form via a left-corner construction + (in the tradition of Rosenkrantz 1967 and Rosenkrantz & Lewis 1970; cf. Blum & Koch 1999) + Every CNF grammar is converted into an equivalent 2-GNF grammar whose rules all have the shape: + • U → a + • U → a V + • U → a V W + Every proof is pure structural induction / length induction — zero nonterminal ordering hacks. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- A grammar in 2-Standard Greibach Normal Form (each rule starts with a terminal + followed by 0, 1, or 2 nonterminals). -/ +structure GNF2 (N T : Type) where + /-- Start nonterminal. -/ + start : N + /-- Productions with a terminal and no trailing nonterminal. -/ + rules0 : List (N × T) -- U → a + /-- Productions with a terminal followed by one nonterminal. -/ + rules1 : List (N × T × N) -- U → a V + /-- Productions with a terminal followed by two nonterminals. -/ + rules2 : List (N × T × N × N) -- U → a V W + +namespace GNF2 + +variable {N T : Type} + +/-- Parse-tree derivations in binary Greibach normal form. -/ +inductive Yield (G : GNF2 N T) : N → List T → Prop where + | r0 {U : N} {a : T} : + (U, a) ∈ G.rules0 → Yield G U [a] + | r1 {U V : N} {a : T} {w : List T} : + (U, a, V) ∈ G.rules1 → Yield G V w → Yield G U (a :: w) + | r2 {U V W : N} {a : T} {w1 w2 : List T} : + (U, a, V, W) ∈ G.rules2 → Yield G V w1 → Yield G W w2 → Yield G U (a :: (w1 ++ w2)) + +/-- Words derivable from the start nonterminal in binary Greibach normal form. -/ +def Lang (G : GNF2 N T) (w : List T) : Prop := + Yield G G.start w + +end GNF2 + +/-- Nonterminals of the left-corner construction: + `orig A` represents `A`; + `diff A X` represents the suffix remaining to the right of a left-corner `X` inside an `A`-tree. -/ +inductive GNFNT (N : Type) where + | orig : N → GNFNT N + | diff : N → N → GNFNT N + deriving DecidableEq, Repr + +namespace CNFtoGNF + +variable {N T : Type} + +/-- Left-spine relation in CNF: `LeftChain G A X w` means `A ⇒⁺ X w` along the left spine. -/ +inductive LeftChain (G : CNF N T) : N → N → List T → Prop where + | one {A X Y : N} {w : List T} : + (A, X, Y) ∈ G.binRules → CNF.Yield G Y w → LeftChain G A X w + | step {A P X Y : N} {w1 w2 : List T} : + LeftChain G A P w2 → (P, X, Y) ∈ G.binRules → CNF.Yield G Y w1 → + LeftChain G A X (w1 ++ w2) + +theorem cnf_yield_pos {G : CNF N T} {A : N} {w : List T} (h : CNF.Yield G A w) : + 0 < w.length := by + induction h with + | tm _ => simp + | bin _ _ _ ih1 ih2 => simp; omega + +theorem leftChain_pos {G : CNF N T} {A X : N} {w : List T} (h : LeftChain G A X w) : + 0 < w.length := by + induction h with + | one _ hy => exact cnf_yield_pos hy + | step _ _ hy _ => + have h1 := cnf_yield_pos hy + simp; omega + +theorem leftChain_snoc {G : CNF N T} {A B C X : N} {w1 w2 : List T} + (hb : (A, B, C) ∈ G.binRules) (hC : CNF.Yield G C w2) (hlc : LeftChain G B X w1) : + LeftChain G A X (w1 ++ w2) := by + induction hlc with + | one hB hY => + exact LeftChain.step (LeftChain.one hb hC) hB hY + | step _ hP hY ih => + simpa [List.append_assoc] using LeftChain.step ih hP hY + +/-- Every CNF parse tree decomposes along its leftmost spine into either a direct terminal rule + or a leftmost terminal leaf `X → a` plus a `LeftChain G A X w'`. -/ +theorem cnf_yield_split {G : CNF N T} {A : N} {w : List T} (h : CNF.Yield G A w) : + (∃ a, (A, a) ∈ G.termRules ∧ w = [a]) ∨ + (∃ X a w', (X, a) ∈ G.termRules ∧ LeftChain G A X w' ∧ w = a :: w') := by + induction h with + | @tm A a htm => + left; exact ⟨a, htm, rfl⟩ + | @bin A B C w1 w2 hb _ hC ihB _ => + rcases ihB with ⟨a, htmB, rfl⟩ | ⟨X, a, w1', htmX, hlc, rfl⟩ + · right + exact ⟨B, a, w2, htmB, LeftChain.one hb hC, rfl⟩ + · right + exact ⟨X, a, w1' ++ w2, htmX, leftChain_snoc hb hC hlc, rfl⟩ + +/-- Plugging a `CNF.Yield G X wx` into the left-corner hole of `LeftChain G A X w` yields `CNF.Yield G A (wx ++ w)`. -/ +theorem cnf_yield_of_leftChain_yield {G : CNF N T} {A X : N} {wx w : List T} + (hlc : LeftChain G A X w) (hx : CNF.Yield G X wx) : + CNF.Yield G A (wx ++ w) := by + induction hlc generalizing wx with + | one hb hY => + exact CNF.Yield.bin hb hx hY + | step _ hP hY ih => + have hP_yield : CNF.Yield G _ (wx ++ _) := CNF.Yield.bin hP hx hY + simpa [List.append_assoc] using ih hP_yield + +theorem cnf_yield_of_leftChain {G : CNF N T} {A X : N} {a : T} {w : List T} + (htm : (X, a) ∈ G.termRules) (hlc : LeftChain G A X w) : + CNF.Yield G A (a :: w) := + cnf_yield_of_leftChain_yield hlc (CNF.Yield.tm htm) + +/-- Finite list of all nonterminals appearing as LHS of a binary rule in `G`. -/ +def allBinLHS (G : CNF N T) : List N := + G.binRules.map fun (A, _, _) => A + +theorem leftChain_mem_allBinLHS {G : CNF N T} {A X : N} {w : List T} + (hlc : LeftChain G A X w) : A ∈ allBinLHS G := by + induction hlc with + | @one X Y _ hb _ => + exact List.mem_map.mpr ⟨(A, X, Y), hb, rfl⟩ + | step _ _ _ ih => exact ih + +/-- The left-corner construction: CNF → 2-Standard GNF. -/ +def cnfToGNF [DecidableEq N] (G : CNF N T) : GNF2 (GNFNT N) T where + start := GNFNT.orig G.start + -- Rule 1: orig A → a (when A → a) + -- Rule 3: diff A X → b (when A → X Y and Y → b) + rules0 := + (G.termRules.map fun (A, a) => (GNFNT.orig A, a)) ++ + (G.binRules.flatMap fun (A, X, Y) => + G.termRules.filterMap fun (Y', b) => + if Y' = Y then some (GNFNT.diff A X, b) else none) + -- Rule 2: orig A → a (diff A X) (when X → a, A ∈ allBinLHS G) + -- Rule 4: diff A X → b (diff Y Z) (when A → X Y and Z → b) + -- Rule 5: diff A X → b (diff A P) (when P → X Y, Y → b, A ∈ allBinLHS G) + rules1 := + ((allBinLHS G).flatMap fun A => + G.termRules.map fun (X, a) => (GNFNT.orig A, a, GNFNT.diff A X)) ++ + (G.binRules.flatMap fun (A, X, Y) => + G.termRules.map fun (Z, b) => (GNFNT.diff A X, b, GNFNT.diff Y Z)) ++ + ((allBinLHS G).flatMap fun A => + G.binRules.flatMap fun (P, X, Y) => + G.termRules.filterMap fun (Y', b) => + if Y' = Y then some (GNFNT.diff A X, b, GNFNT.diff A P) else none) + -- Rule 6: diff A X → b (diff Y Z) (diff A P) (when P → X Y, Z → b, A ∈ allBinLHS G) + rules2 := + (allBinLHS G).flatMap fun A => + G.binRules.flatMap fun (P, X, Y) => + G.termRules.map fun (Z, b) => + (GNFNT.diff A X, b, GNFNT.diff Y Z, GNFNT.diff A P) + +/-- Semantic interpretation of `GNFNT N` back in the CNF grammar `G`. -/ +def interp (G : CNF N T) : GNFNT N → List T → Prop + | GNFNT.orig A, w => CNF.Yield G A w + | GNFNT.diff A X, w => LeftChain G A X w + +theorem cnfToGNF_sound [DecidableEq N] {G : CNF N T} {U : GNFNT N} {w : List T} + (h : GNF2.Yield (cnfToGNF G) U w) : interp G U w := by + induction h with + | @r0 U a hr => + simp only [cnfToGNF, List.mem_append, List.mem_map, List.mem_flatMap, List.mem_filterMap] at hr + rcases hr with ⟨⟨A, a'⟩, htm, heq⟩ | ⟨⟨A, X, Y⟩, hb, ⟨Y', b⟩, htm, hif⟩ + · simp at heq; obtain ⟨rfl, rfl⟩ := heq + exact CNF.Yield.tm htm + · split at hif + · next hEq => + simp at hif; obtain ⟨rfl, rfl⟩ := hif; subst hEq + exact LeftChain.one hb (CNF.Yield.tm htm) + · simp at hif + | @r1 U V a w hr _ ih => + simp only [cnfToGNF, List.mem_append, List.mem_flatMap, List.mem_map, List.mem_filterMap] at hr + rcases hr with + (⟨A, _, ⟨X, a'⟩, htm, heq⟩ | ⟨⟨A, X, Y⟩, hb, ⟨Z, b⟩, htm, heq⟩) | + ⟨A, _, ⟨P, X, Y⟩, hb, ⟨Y', b⟩, htm, hif⟩ + · simp at heq; obtain ⟨rfl, rfl, rfl⟩ := heq + exact cnf_yield_of_leftChain htm ih + · simp at heq; obtain ⟨rfl, rfl, rfl⟩ := heq + exact LeftChain.one hb (cnf_yield_of_leftChain htm ih) + · split at hif + · next hEq => + simp at hif; obtain ⟨rfl, rfl, rfl⟩ := hif; subst hEq + exact LeftChain.step ih hb (CNF.Yield.tm htm) + · simp at hif + | @r2 U V W a w1 w2 hr _ _ ih1 ih2 => + simp only [cnfToGNF, List.mem_flatMap, List.mem_map] at hr + obtain ⟨A, _, ⟨P, X, Y⟩, hb, ⟨Z, b⟩, htm, heq⟩ := hr + simp at heq; obtain ⟨rfl, rfl, rfl, rfl⟩ := heq + have hY : CNF.Yield G Y (b :: w1) := cnf_yield_of_leftChain htm ih1 + exact LeftChain.step ih2 hb hY + +/-- Strong induction on string length proves completeness of `diff A X` for all `LeftChain`s! -/ +theorem cnfToGNF_complete_leftChain [DecidableEq N] {G : CNF N T} : + ∀ n (A X : N) (w : List T), w.length ≤ n → LeftChain G A X w → + GNF2.Yield (cnfToGNF G) (GNFNT.diff A X) w := by + intro n + induction n with + | zero => + intro A X w hlen hlc + have hpos := leftChain_pos hlc + omega + | succ n ih => + intro A X w hlen hlc + have hA_in : A ∈ allBinLHS G := leftChain_mem_allBinLHS hlc + cases hlc with + | @one X Y w hb hY => + rcases cnf_yield_split hY with ⟨b, htmY, rfl⟩ | ⟨Z, b, w', htmZ, hlcY, rfl⟩ + · -- Rule 3: diff A X → b + apply GNF2.Yield.r0 + simp only [cnfToGNF, List.mem_append, List.mem_flatMap, List.mem_filterMap] + right + exact ⟨(A, X, Y), hb, (Y, b), htmY, by simp⟩ + · -- Rule 4: diff A X → b (diff Y Z) + have hlen' : w'.length ≤ n := by simp at hlen; omega + have hYZ := ih Y Z w' hlen' hlcY + apply GNF2.Yield.r1 _ hYZ + simp only [cnfToGNF, List.mem_append, List.mem_flatMap, List.mem_map] + left; right + exact ⟨(A, X, Y), hb, (Z, b), htmZ, rfl⟩ + | @step P X Y w1 w2 hlcAP hb hY => + have hpos1 : 0 < w1.length := cnf_yield_pos hY + have hpos2 : 0 < w2.length := leftChain_pos hlcAP + have hlen2 : w2.length ≤ n := by simp at hlen; omega + have hAP := ih A P w2 hlen2 hlcAP + rcases cnf_yield_split hY with ⟨b, htmY, rfl⟩ | ⟨Z, b, w1', htmZ, hlcY, rfl⟩ + · -- Rule 5: diff A X → b (diff A P) + apply GNF2.Yield.r1 _ hAP + simp only [cnfToGNF, List.mem_append, List.mem_flatMap, List.mem_filterMap] + right + exact ⟨A, hA_in, (P, X, Y), hb, (Y, b), htmY, by simp⟩ + · -- Rule 6: diff A X → b (diff Y Z) (diff A P) + have hlen1' : w1'.length ≤ n := by simp at hlen; omega + have hYZ := ih Y Z w1' hlen1' hlcY + apply GNF2.Yield.r2 _ hYZ hAP + simp only [cnfToGNF, List.mem_flatMap, List.mem_map] + exact ⟨A, hA_in, (P, X, Y), hb, (Z, b), htmZ, rfl⟩ + +theorem cnfToGNF_complete [DecidableEq N] {G : CNF N T} {A : N} {w : List T} + (h : CNF.Yield G A w) : GNF2.Yield (cnfToGNF G) (GNFNT.orig A) w := by + rcases cnf_yield_split h with ⟨a, htmA, rfl⟩ | ⟨X, a, w', htmX, hlc, rfl⟩ + · -- Rule 1: orig A → a + apply GNF2.Yield.r0 + simp only [cnfToGNF, List.mem_append, List.mem_map] + left + exact ⟨(A, a), htmA, rfl⟩ + · -- Rule 2: orig A → a (diff A X) + have hA_in : A ∈ allBinLHS G := leftChain_mem_allBinLHS hlc + have hdiff := cnfToGNF_complete_leftChain w'.length A X w' (Nat.le_refl _) hlc + apply GNF2.Yield.r1 _ hdiff + simp only [cnfToGNF, List.mem_append, List.mem_flatMap, List.mem_map] + left; left + exact ⟨A, hA_in, (X, a), htmX, rfl⟩ + +/-- 2-GNF theorem: `cnfToGNF G` generates the exact same language as `G`. -/ +theorem cnfToGNF_lang [DecidableEq N] (G : CNF N T) (w : List T) : + (cnfToGNF G).Lang w ↔ G.Lang w := + ⟨cnfToGNF_sound, cnfToGNF_complete⟩ + +end CNFtoGNF +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/Imports.lean b/LeanPool/FormalLinguistics/Imports.lean new file mode 100644 index 0000000000..098aa28c3d --- /dev/null +++ b/LeanPool/FormalLinguistics/Imports.lean @@ -0,0 +1,32 @@ +/- +Copyright (c) 2026 Lean Pool contributors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Lean Pool contributors +-/ +module -- shake: keep-all --deprecated_module: ignore + +-- Generated project imports; run `lake exe mk_all`. +public import LeanPool.FormalLinguistics +public import LeanPool.FormalLinguistics.ABG +public import LeanPool.FormalLinguistics.ABGtoCFG +public import LeanPool.FormalLinguistics.BarHillel +public import LeanPool.FormalLinguistics.BinMCFG +public import LeanPool.FormalLinguistics.CFG +public import LeanPool.FormalLinguistics.CFGtoABG +public import LeanPool.FormalLinguistics.CNF +public import LeanPool.FormalLinguistics.Fixpoint +public import LeanPool.FormalLinguistics.GNF +public import LeanPool.FormalLinguistics.Lambek +public import LeanPool.FormalLinguistics.LambekCore +public import LeanPool.FormalLinguistics.LambekCut +public import LeanPool.FormalLinguistics.LambekFreeGroup +public import LeanPool.FormalLinguistics.LambekInterpolation +public import LeanPool.FormalLinguistics.LambekPentus +public import LeanPool.FormalLinguistics.LambekThin +public import LeanPool.FormalLinguistics.MCFG +public import LeanPool.FormalLinguistics.MCFGtoMG +public import LeanPool.FormalLinguistics.MG +public import LeanPool.FormalLinguistics.MGMCFGEquiv +public import LeanPool.FormalLinguistics.MGOriginal +public import LeanPool.FormalLinguistics.MGtoMCFG +public import LeanPool.FormalLinguistics.MathlibBridge diff --git a/LeanPool/FormalLinguistics/Lambek.lean b/LeanPool/FormalLinguistics/Lambek.lean new file mode 100644 index 0000000000..ae1f8f476f --- /dev/null +++ b/LeanPool/FormalLinguistics/Lambek.lean @@ -0,0 +1,319 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.BarHillel + +/-! + The Lambek calculus `L` (Lambek 1958) and Lambek grammars. + + This file contains the easy half of the Chomsky–Pentus theorem: every ε-free + context-free language is generated by a Lambek grammar. It reuses the AB grammar + obtained from 2-Greibach normal form in `BarHillel.lean`: + + • every AB derivation is a derivation in `L`, so the Lambek grammar with the same + lexicon generates at least the AB language (`ABG.lang_sub_lambek`); + • `L` is sound for language models (`LDer.sound`), which shows that for the + Greibach-derived lexicon it generates nothing more (`GNFtoABG.lambek_sub`). + + The hard half (Pentus 1993: every Lambek grammar generates a context-free language) + is not in this file. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Types of the Lambek calculus with product: `over A B` is `A / B`, + `under B A` is `B \ A`, and `mul A B` is `A • B`. -/ +inductive LType (P : Type) where + | prim : P → LType P + | over : LType P → LType P → LType P + | under : LType P → LType P → LType P + | mul : LType P → LType P → LType P + deriving DecidableEq, Repr + +namespace LType + +variable {P T : Type} + +/-- AB categories are the product-free Lambek types. -/ +def ofCat : Cat P → LType P + | Cat.atom p => prim p + | Cat.rslash A B => over (ofCat A) (ofCat B) + | Cat.lslash B A => under (ofCat B) (ofCat A) + +/-- Interpretation of types in a language model: primitive types are interpreted by + arbitrary languages, and the connectives by the residuated operations on languages. -/ +def sem (I : P → List T → Prop) : LType P → List T → Prop + | prim p => I p + | over A B => fun x => ∀ y, sem I B y → sem I A (x ++ y) + | under B A => fun x => ∀ y, sem I B y → sem I A (y ++ x) + | mul A B => fun x => ∃ y z, x = y ++ z ∧ sem I A y ∧ sem I B z + +end LType + +/-- Derivability in the Lambek calculus `L`: sequents `Γ → C` with the axiom, the left and + right rules for `/`, `\` and `•`, and cut. As in Lambek (1958), the right rules for the + two divisions require a non-empty antecedent, so no sequent with an empty antecedent is + derivable. -/ +inductive LDer {P : Type} : List (LType P) → LType P → Prop where + | ax (A : LType P) : LDer [A] A + | overR {Γ : List (LType P)} {A B : LType P} : + Γ ≠ [] → LDer (Γ ++ [B]) A → LDer Γ (LType.over A B) + | underR {Γ : List (LType P)} {A B : LType P} : + Γ ≠ [] → LDer (B :: Γ) A → LDer Γ (LType.under B A) + | overL {Γ Δ Θ : List (LType P)} {A B C : LType P} : + LDer Θ B → LDer (Γ ++ [A] ++ Δ) C → LDer (Γ ++ [LType.over A B] ++ Θ ++ Δ) C + | underL {Γ Δ Θ : List (LType P)} {A B C : LType P} : + LDer Θ B → LDer (Γ ++ [A] ++ Δ) C → LDer (Γ ++ Θ ++ [LType.under B A] ++ Δ) C + | mulR {Γ Δ : List (LType P)} {A B : LType P} : + LDer Γ A → LDer Δ B → LDer (Γ ++ Δ) (LType.mul A B) + | mulL {Γ Δ : List (LType P)} {A B C : LType P} : + LDer (Γ ++ [A, B] ++ Δ) C → LDer (Γ ++ [LType.mul A B] ++ Δ) C + | cut {Γ Δ Θ : List (LType P)} {A C : LType P} : + LDer Θ A → LDer (Γ ++ [A] ++ Δ) C → LDer (Γ ++ Θ ++ Δ) C + +/-- A finite Lambek grammar over primitive types `P` and alphabet `T`. -/ +structure LambekGrammar (P T : Type) where + /-- Primitive goal type for complete strings. -/ + distinguished : P + /-- Finite list of assigned Lambek types for individual terminals. -/ + lexicon : List (T × LType P) + +namespace LambekGrammar + +variable {P T : Type} + +/-- Lexical assignment of one type to each letter of a word. -/ +inductive LexAssign (G : LambekGrammar P T) : List T → List (LType P) → Prop where + | nil : LexAssign G [] [] + | cons {a : T} {A : LType P} {w : List T} {Γ : List (LType P)} : + (a, A) ∈ G.lexicon → LexAssign G w Γ → LexAssign G (a :: w) (A :: Γ) + +/-- The string language generated by a Lambek grammar. -/ +def Lang (G : LambekGrammar P T) (w : List T) : Prop := + ∃ Γ, LexAssign G w Γ ∧ LDer Γ (LType.prim G.distinguished) + +end LambekGrammar + +/-! ### Soundness of `L` for language models -/ + +section Soundness + +variable {P T : Type} + +/-- A string belongs to the interpretation of a sequence of types if it is a concatenation + of strings belonging to the interpretations of the types, in order. -/ +inductive SeqSem (I : P → List T → Prop) : List (LType P) → List T → Prop where + | nil : SeqSem I [] [] + | cons {A : LType P} {Γ : List (LType P)} {x y : List T} : + A.sem I x → SeqSem I Γ y → SeqSem I (A :: Γ) (x ++ y) + +theorem SeqSem.single {I : P → List T → Prop} {A : LType P} {x : List T} + (h : A.sem I x) : SeqSem I [A] x := by + simpa using SeqSem.cons h SeqSem.nil + +theorem SeqSem.of_single {I : P → List T → Prop} {A : LType P} {x : List T} + (h : SeqSem I [A] x) : A.sem I x := by + cases h with + | cons hA hnil => + cases hnil + simpa using hA + +theorem SeqSem.append {I : P → List T → Prop} {Γ Δ : List (LType P)} {x y : List T} + (h1 : SeqSem I Γ x) (h2 : SeqSem I Δ y) : SeqSem I (Γ ++ Δ) (x ++ y) := by + induction h1 with + | nil => simpa using h2 + | cons hA _ ih => simpa [List.append_assoc] using SeqSem.cons hA ih + +theorem SeqSem.split {I : P → List T → Prop} {Γ Δ : List (LType P)} {x : List T} + (h : SeqSem I (Γ ++ Δ) x) : + ∃ y z, x = y ++ z ∧ SeqSem I Γ y ∧ SeqSem I Δ z := by + induction Γ generalizing x with + | nil => exact ⟨[], x, rfl, SeqSem.nil, h⟩ + | cons A Γ ih => + cases h with + | cons hA hrest => + obtain ⟨y, z, hyz, hy, hz⟩ := ih hrest + refine ⟨_ ++ y, z, ?_, SeqSem.cons hA hy, hz⟩ + simp [hyz, List.append_assoc] + +/-- Soundness: if `Γ → C` is derivable in `L`, then in every language model the + interpretation of `Γ` is included in the interpretation of `C`. -/ +theorem LDer.sound {I : P → List T → Prop} {Γ : List (LType P)} {C : LType P} + (h : LDer Γ C) : ∀ x, SeqSem I Γ x → C.sem I x := by + induction h with + | ax A => + intro x hx + exact SeqSem.of_single hx + | overR _ _ ih => + intro x hx + simp only [LType.sem] + intro y hy + exact ih (x ++ y) (SeqSem.append hx (SeqSem.single hy)) + | underR _ _ ih => + intro x hx + simp only [LType.sem] + intro y hy + exact ih (y ++ x) (SeqSem.cons hy hx) + | overL _ _ ih1 ih2 => + intro x hx + obtain ⟨x1, xΔ, rfl, h1, hΔ⟩ := SeqSem.split hx + obtain ⟨x2, xΘ, rfl, h2, hΘ⟩ := SeqSem.split h1 + obtain ⟨xΓ, xo, rfl, hΓ, ho⟩ := SeqSem.split h2 + have ho' := SeqSem.of_single ho + simp only [LType.sem] at ho' + have hA := ho' xΘ (ih1 xΘ hΘ) + have := ih2 _ (SeqSem.append (SeqSem.append hΓ (SeqSem.single hA)) hΔ) + simpa [List.append_assoc] using this + | underL _ _ ih1 ih2 => + intro x hx + obtain ⟨x1, xΔ, rfl, h1, hΔ⟩ := SeqSem.split hx + obtain ⟨x2, xu, rfl, h2, hu⟩ := SeqSem.split h1 + obtain ⟨xΓ, xΘ, rfl, hΓ, hΘ⟩ := SeqSem.split h2 + have hu' := SeqSem.of_single hu + simp only [LType.sem] at hu' + have hA := hu' xΘ (ih1 xΘ hΘ) + have := ih2 _ (SeqSem.append (SeqSem.append hΓ (SeqSem.single hA)) hΔ) + simpa [List.append_assoc] using this + | mulR _ _ ih1 ih2 => + intro x hx + obtain ⟨y, z, rfl, hy, hz⟩ := SeqSem.split hx + simp only [LType.sem] + exact ⟨y, z, rfl, ih1 y hy, ih2 z hz⟩ + | mulL _ ih => + intro x hx + obtain ⟨x1, xΔ, rfl, h1, hΔ⟩ := SeqSem.split hx + obtain ⟨xΓ, xm, rfl, hΓ, hm⟩ := SeqSem.split h1 + have hm' := SeqSem.of_single hm + simp only [LType.sem] at hm' + obtain ⟨y, z, rfl, hy, hz⟩ := hm' + have hAB : SeqSem I [_, _] (y ++ z) := SeqSem.cons hy (SeqSem.single hz) + have := ih _ (SeqSem.append (SeqSem.append hΓ hAB) hΔ) + simpa [List.append_assoc] using this + | cut _ _ ih1 ih2 => + intro x hx + obtain ⟨x1, xΔ, rfl, h1, hΔ⟩ := SeqSem.split hx + obtain ⟨xΓ, xΘ, rfl, hΓ, hΘ⟩ := SeqSem.split h1 + have := ih2 _ (SeqSem.append (SeqSem.append hΓ (SeqSem.single (ih1 xΘ hΘ))) hΔ) + simpa [List.append_assoc] using this + +end Soundness + +/-! ### AB grammars as Lambek grammars -/ + +namespace ABG + +variable {P T : Type} + +/-- The Lambek grammar with the same lexicon as an AB grammar. -/ +def toLambek (G : ABG P T) : LambekGrammar P T where + distinguished := G.distinguished + lexicon := G.lexicon.map fun (a, C) => (a, LType.ofCat C) + +/-- An AB cancellation step is admissible in `L`. -/ +theorem LDer_of_abStep {γ δ : List (Cat P)} (h : ABStep γ δ) {C : LType P} + (hC : LDer (δ.map LType.ofCat) C) : LDer (γ.map LType.ofCat) C := by + cases h with + | fwd u v A B => + have h1 : (u ++ [A] ++ v).map LType.ofCat + = u.map LType.ofCat ++ [LType.ofCat A] ++ v.map LType.ofCat := by simp + have h2 : (u ++ [Cat.rslash A B, B] ++ v).map LType.ofCat + = u.map LType.ofCat ++ [LType.over (LType.ofCat A) (LType.ofCat B)] + ++ [LType.ofCat B] ++ v.map LType.ofCat := by + simp [LType.ofCat, List.append_assoc] + rw [h1] at hC + rw [h2] + exact LDer.overL (LDer.ax _) hC + | bwd u v A B => + have h1 : (u ++ [A] ++ v).map LType.ofCat + = u.map LType.ofCat ++ [LType.ofCat A] ++ v.map LType.ofCat := by simp + have h2 : (u ++ [B, Cat.lslash B A] ++ v).map LType.ofCat + = u.map LType.ofCat ++ [LType.ofCat B] + ++ [LType.under (LType.ofCat B) (LType.ofCat A)] ++ v.map LType.ofCat := by + simp [LType.ofCat, List.append_assoc] + rw [h1] at hC + rw [h2] + exact LDer.underL (LDer.ax _) hC + +theorem LDer_of_abDerives {γ δ : List (Cat P)} (h : ABDerives γ δ) {C : LType P} : + LDer (δ.map LType.ofCat) C → LDer (γ.map LType.ofCat) C := by + induction h with + | refl => exact id + | tail _ hstep ih => exact fun hC => ih (LDer_of_abStep hstep hC) + +theorem lexAssign_toLambek {G : ABG P T} {w : List T} {γ : List (Cat P)} + (h : LexAssign G w γ) : LambekGrammar.LexAssign G.toLambek w (γ.map LType.ofCat) := by + induction h with + | nil => exact LambekGrammar.LexAssign.nil + | cons ha _ ih => + refine LambekGrammar.LexAssign.cons ?_ ih + exact List.mem_map.mpr ⟨_, ha, rfl⟩ + +/-- Every string generated by an AB grammar is generated by the Lambek grammar with the + same lexicon. -/ +theorem lang_sub_lambek (G : ABG P T) {w : List T} (h : G.Lang w) : G.toLambek.Lang w := by + obtain ⟨γ, hlex, hder⟩ := h + refine ⟨γ.map LType.ofCat, lexAssign_toLambek hlex, ?_⟩ + exact LDer_of_abDerives hder (LDer.ax _) + +end ABG + +/-! ### Every ε-free context-free language is a Lambek language -/ + +namespace GNFtoABG + +variable {N T : Type} + +/-- In the language model that interprets each nonterminal by its yield, every lexical type + of the Greibach-derived grammar contains its own letter. -/ +theorem lex_sem {G : GNF2 N T} {a : T} {C : Cat N} (h : (a, C) ∈ (toABG G).lexicon) : + (LType.ofCat C).sem (GNF2.Yield G) [a] := by + rcases lex_shapes h with ⟨U, rfl, hr⟩ | ⟨U, V, rfl, hr⟩ | ⟨U, V, W, rfl, hr⟩ + · simp only [LType.ofCat, LType.sem] + exact GNF2.Yield.r0 hr + · simp only [LType.ofCat, LType.sem] + intro y hy + exact GNF2.Yield.r1 hr hy + · simp only [LType.ofCat, LType.sem] + intro y hy z hz + simpa [List.append_assoc] using GNF2.Yield.r2 hr hy hz + +theorem lexAssign_sem {G : GNF2 N T} {w : List T} {Γ : List (LType N)} + (h : LambekGrammar.LexAssign (toABG G).toLambek w Γ) : SeqSem (GNF2.Yield G) Γ w := by + induction h with + | nil => exact SeqSem.nil + | cons ha _ ih => + obtain ⟨⟨a', C⟩, hmem, heq⟩ := List.mem_map.mp ha + simp only [Prod.mk.injEq] at heq + obtain ⟨rfl, rfl⟩ := heq + exact SeqSem.cons (lex_sem hmem) ih + +/-- The Lambek grammar with the Greibach-derived lexicon generates no more than the + 2-GNF grammar it comes from. -/ +theorem lambek_sub (G : GNF2 N T) {w : List T} (h : (toABG G).toLambek.Lang w) : G.Lang w := by + obtain ⟨Γ, hlex, hder⟩ := h + exact hder.sound w (lexAssign_sem hlex) + +theorem toLambek_lang (G : GNF2 N T) (w : List T) : + (toABG G).toLambek.Lang w ↔ G.Lang w := + ⟨lambek_sub G, fun h => ABG.lang_sub_lambek _ ((toABG_lang G w).mpr h)⟩ + +end GNFtoABG + +/-- Every context-free grammar has a Lambek grammar generating exactly its non-empty + strings. The lexicon uses only right division, with types of the forms `p`, `p / q` + and `(p / r) / q`. -/ +theorem cfg_to_lambek_equiv {N T : Type} [DecidableEq N] [DecidableEq T] (G : CFG N T) : + ∀ w, (cfgToABG G).toLambek.Lang w ↔ G.Lang w ∧ w ≠ [] := by + intro w + unfold cfgToABG + rw [GNFtoABG.toLambek_lang, CNFtoGNF.cnfToGNF_lang, cfgToCNF_lang] + + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/LambekCore.lean b/LeanPool/FormalLinguistics/LambekCore.lean new file mode 100644 index 0000000000..86407f29df --- /dev/null +++ b/LeanPool/FormalLinguistics/LambekCore.lean @@ -0,0 +1,122 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.Lambek + +/-! + Shared definitions for the proof that Lambek grammars generate only context-free + languages (Pentus 1993). + + • `LDer0`: the cut-free Lambek calculus with atomic axioms. + • `LType.size`, `LType.occ`, `LType.map`: size, occurrence counts and renaming of + primitive types. + • `FGWord`: words over signed letters, with a normaliser `reduce`, used for the + free-group interpretation of types. + + The statements proved about these definitions live in `LambekCut.lean`, + `LambekInterpolation.lean` and `LambekFreeGroup.lean`. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- The cut-free Lambek calculus `L` with atomic axioms `p → p`. The rules are those of + `LDer` without cut. -/ +inductive LDer0 {P : Type} : List (LType P) → LType P → Prop where + | ax (p : P) : LDer0 [LType.prim p] (LType.prim p) + | overR {Γ : List (LType P)} {A B : LType P} : + Γ ≠ [] → LDer0 (Γ ++ [B]) A → LDer0 Γ (LType.over A B) + | underR {Γ : List (LType P)} {A B : LType P} : + Γ ≠ [] → LDer0 (B :: Γ) A → LDer0 Γ (LType.under B A) + | overL {Γ Δ Θ : List (LType P)} {A B C : LType P} : + LDer0 Θ B → LDer0 (Γ ++ [A] ++ Δ) C → LDer0 (Γ ++ [LType.over A B] ++ Θ ++ Δ) C + | underL {Γ Δ Θ : List (LType P)} {A B C : LType P} : + LDer0 Θ B → LDer0 (Γ ++ [A] ++ Δ) C → LDer0 (Γ ++ Θ ++ [LType.under B A] ++ Δ) C + | mulR {Γ Δ : List (LType P)} {A B : LType P} : + LDer0 Γ A → LDer0 Δ B → LDer0 (Γ ++ Δ) (LType.mul A B) + | mulL {Γ Δ : List (LType P)} {A B C : LType P} : + LDer0 (Γ ++ [A, B] ++ Δ) C → LDer0 (Γ ++ [LType.mul A B] ++ Δ) C + +namespace LType + +variable {P Q : Type} + +/-- Number of occurrences of primitive types in a type. -/ +def size : LType P → Nat + | prim _ => 1 + | over A B => size A + size B + | under B A => size B + size A + | mul A B => size A + size B + +/-- Number of occurrences of the primitive type `p` in a type. -/ +def occ [DecidableEq P] (p : P) : LType P → Nat + | prim q => if q = p then 1 else 0 + | over A B => occ p A + occ p B + | under B A => occ p B + occ p A + | mul A B => occ p A + occ p B + +/-- Renaming of primitive types. -/ +def map (f : P → Q) : LType P → LType Q + | prim p => prim (f p) + | over A B => over (map f A) (map f B) + | under B A => under (map f B) (map f A) + | mul A B => mul (map f A) (map f B) + +end LType + +/-- Total size of a sequence of types. -/ +def sizeList {P : Type} (Γ : List (LType P)) : Nat := (Γ.map LType.size).sum + +/-- Number of occurrences of `p` in a sequence of types. -/ +def occList {P : Type} [DecidableEq P] (p : P) (Γ : List (LType P)) : Nat := + (Γ.map (LType.occ p)).sum + +/-- Words over signed letters: `(p, true)` stands for the generator `p` and `(p, false)` + for its inverse. -/ +abbrev FGWord (P : Type) := List (P × Bool) + +namespace FGWord + +variable {P : Type} + +/-- Formal inverse of a word. -/ +def inv (w : FGWord P) : FGWord P := (w.map fun x => (x.1, !x.2)).reverse + +/-- Push a letter on a stack (top at the head), cancelling it against the top if the top + is its inverse. -/ +def push [DecidableEq P] (s : FGWord P) (x : P × Bool) : FGWord P := + match s with + | y :: s' => if y.1 = x.1 ∧ y.2 = !x.2 then s' else x :: y :: s' + | [] => [x] + +/-- The freely reduced form of a word. -/ +def reduce [DecidableEq P] (w : FGWord P) : FGWord P := (w.foldl push []).reverse + +/-- Length of the freely reduced form. -/ +def norm [DecidableEq P] (w : FGWord P) : Nat := (reduce w).length + +end FGWord + +namespace LType + +variable {P : Type} + +/-- Free-group interpretation of a type, as an unreduced word. -/ +def interp : LType P → FGWord P + | prim p => [(p, true)] + | over A B => interp A ++ FGWord.inv (interp B) + | under B A => FGWord.inv (interp B) ++ interp A + | mul A B => interp A ++ interp B + +end LType + +/-- Free-group interpretation of a sequence of types. -/ +def interpList {P : Type} (Γ : List (LType P)) : FGWord P := (Γ.map LType.interp).flatten + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/LambekCut.lean b/LeanPool/FormalLinguistics/LambekCut.lean new file mode 100644 index 0000000000..9d6aa2d098 --- /dev/null +++ b/LeanPool/FormalLinguistics/LambekCut.lean @@ -0,0 +1,280 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.LambekCore + +/-! + Cut admissibility for the cut-free Lambek calculus `LDer0`, and its equivalence with + the calculus `LDer` of `Lambek.lean`. +-/ + +@[expose] public section + +namespace FormalLinguistics + +variable {P Q : Type} + +/-- No sequent with an empty antecedent is derivable. -/ +theorem LDer0.ne_nil {Γ : List (LType P)} {C : LType P} (h : LDer0 Γ C) : Γ ≠ [] := by + induction h with + | ax p => simp + | overR hne _ _ => exact hne + | underR hne _ _ => exact hne + | overL _ _ _ _ => simp + | underL _ _ _ _ => simp + | mulR _ _ ih1 _ => simp [ih1] + | mulL _ _ => simp + +/-- The identity sequent `A → A` is derivable for every type. -/ +theorem LDer0.identity (A : LType P) : LDer0 [A] A := by + induction A with + | prim p => exact LDer0.ax p + | over A B ihA ihB => + refine LDer0.overR (by simp) ?_ + have := LDer0.overL (A := A) (B := B) (Γ := []) (Δ := []) ihB (by simpa using ihA) + simpa using this + | under B A ihB ihA => + refine LDer0.underR (by simp) ?_ + have := LDer0.underL (A := A) (B := B) (Γ := []) (Δ := []) ihB (by simpa using ihA) + simpa using this + | mul A B ihA ihB => + have := LDer0.mulL (A := A) (B := B) (Γ := []) (Δ := []) (by simpa using LDer0.mulR ihA ihB) + simpa using this + +namespace LCut + +theorem cast {Γ Γ' : List (LType P)} {C : LType P} (h : LDer0 Γ C) (e : Γ = Γ') : + LDer0 Γ' C := e ▸ h + +theorem single_eq {α : Type} {Γ Δ : List α} {a b : α} (h : Γ ++ [a] ++ Δ = [b]) : + Γ = [] ∧ a = b ∧ Δ = [] := by + cases Γ with + | nil => simpa using h + | cons x Γ' => simp at h + +theorem split1 {α : Type} {Γ Δ X Y : List α} {a : α} (h : Γ ++ [a] ++ Δ = X ++ Y) : + (∃ M, X = Γ ++ [a] ++ M ∧ Δ = M ++ Y) ∨ (∃ M, Y = M ++ [a] ++ Δ ∧ Γ = X ++ M) := by + rw [List.append_assoc, List.append_eq_append_iff] at h + rcases h with ⟨a', hX, hY⟩ | ⟨c', hG, hY⟩ + · cases a' with + | nil => + simp at hX hY + subst hX hY + right; exact ⟨[], by simp, by simp⟩ + | cons m a'' => + simp at hY + obtain ⟨rfl, rfl⟩ := hY + subst hX + left; exact ⟨a'', by simp, rfl⟩ + · subst hG hY + right; exact ⟨c', by simp, rfl⟩ + +theorem split2 {α : Type} {Γ Δ X Y : List α} {a b : α} (h : Γ ++ [a] ++ Δ = X ++ [b] ++ Y) : + (Γ = X ∧ a = b ∧ Δ = Y) ∨ (∃ M, X = Γ ++ [a] ++ M ∧ Δ = M ++ [b] ++ Y) ∨ + (∃ M, Γ = X ++ [b] ++ M ∧ Y = M ++ [a] ++ Δ) := by + rw [List.append_assoc X] at h + rcases split1 h with ⟨M, hX, hD⟩ | ⟨M, hY, hG⟩ + · exact Or.inr (Or.inl ⟨M, hX, by simpa using hD⟩) + · cases M with + | nil => + simp at hY hG + obtain ⟨rfl, rfl⟩ := hY + exact Or.inl ⟨hG, rfl, rfl⟩ + | cons m M' => + simp at hY + obtain ⟨rfl, rfl⟩ := hY + exact Or.inr (Or.inr ⟨M', by simpa using hG, by simp⟩) + +/-- Cut on the cut formula `X` with left premise `Θ → X`, by induction on the right + premise, given the principal cases. -/ +theorem inner {Θ : List (LType P)} {X : LType P} (h1 : LDer0 Θ X) (hne : Θ ≠ []) + (hover : ∀ A B, X = LType.over A B → ∀ (Θ' Γ Δ : List (LType P)) (C : LType P), + LDer0 Θ' B → LDer0 (Γ ++ [A] ++ Δ) C → LDer0 (Γ ++ Θ ++ Θ' ++ Δ) C) + (hunder : ∀ A B, X = LType.under B A → ∀ (Θ' Γ Δ : List (LType P)) (C : LType P), + LDer0 Θ' B → LDer0 (Γ ++ [A] ++ Δ) C → LDer0 (Γ ++ Θ' ++ Θ ++ Δ) C) + (hmul : ∀ A B, X = LType.mul A B → ∀ (Γ Δ : List (LType P)) (C : LType P), + LDer0 (Γ ++ [A, B] ++ Δ) C → LDer0 (Γ ++ Θ ++ Δ) C) : + ∀ (Γ Δ : List (LType P)) (C : LType P), + LDer0 (Γ ++ [X] ++ Δ) C → LDer0 (Γ ++ Θ ++ Δ) C := by + intro Γ Δ C h2 + generalize hE : Γ ++ [X] ++ Δ = L at h2 + induction h2 generalizing Γ Δ with + | ax p => + obtain ⟨rfl, rfl, rfl⟩ := single_eq hE + simpa using h1 + | @overR G A B _ _ ih => + subst hE + exact LDer0.overR (by simp [hne]) (cast (ih Γ (Δ ++ [B]) (by simp)) (by simp)) + | @underR G A B _ _ ih => + subst hE + exact LDer0.underR (by simp [hne]) (cast (ih (B :: Γ) Δ (by simp)) (by simp)) + | @overL G D T A B C k1 k2 ih1 ih2 => + have hE' : Γ ++ [X] ++ Δ = G ++ [LType.over A B] ++ (T ++ D) := hE.trans (by simp) + rcases split2 hE' with ⟨rfl, rfl, rfl⟩ | ⟨M, rfl, rfl⟩ | ⟨M, rfl, hTD⟩ + · exact cast (hover A B rfl T Γ D C k1 k2) (by simp) + · have := ih2 Γ (M ++ [A] ++ D) (by simp) + exact cast (LDer0.overL (A := A) (B := B) (Γ := Γ ++ Θ ++ M) (Δ := D) k1 (cast this (by simp))) + (by simp) + · rcases split1 hTD.symm with ⟨N, rfl, rfl⟩ | ⟨N, rfl, rfl⟩ + · have := ih1 M N rfl + exact cast (LDer0.overL (A := A) (B := B) (Γ := G) (Δ := D) this k2) (by simp) + · have := ih2 (G ++ [A] ++ N) Δ (by simp) + exact cast (LDer0.overL (A := A) (B := B) (Γ := G) (Δ := N ++ Θ ++ Δ) k1 (cast this (by simp))) + (by simp) + | @underL G D T A B C k1 k2 ih1 ih2 => + rcases split2 hE with ⟨rfl, rfl, rfl⟩ | ⟨M, hGT, rfl⟩ | ⟨M, rfl, rfl⟩ + · exact cast (hunder A B rfl T G _ C k1 k2) (by simp) + · rcases split1 hGT.symm with ⟨N, rfl, rfl⟩ | ⟨N, rfl, rfl⟩ + · have := ih2 Γ (N ++ [A] ++ D) (by simp) + exact cast (LDer0.underL (A := A) (B := B) (Γ := Γ ++ Θ ++ N) (Δ := D) k1 (cast this (by simp))) + (by simp) + · have := ih1 N M rfl + exact cast (LDer0.underL (A := A) (B := B) (Γ := G) (Δ := D) this k2) (by simp) + · have := ih2 (G ++ [A] ++ M) Δ (by simp) + exact cast (LDer0.underL (A := A) (B := B) (Γ := G) (Δ := M ++ Θ ++ Δ) k1 (cast this (by simp))) + (by simp) + | @mulR G D A B k1 k2 ih1 ih2 => + rcases split1 hE with ⟨M, rfl, rfl⟩ | ⟨M, rfl, rfl⟩ + · exact cast (LDer0.mulR (ih1 Γ M rfl) k2) (by simp) + · exact cast (LDer0.mulR k1 (ih2 M Δ rfl)) (by simp) + | @mulL G D A B C k ih => + rcases split2 hE with ⟨rfl, rfl, rfl⟩ | ⟨M, rfl, rfl⟩ | ⟨M, rfl, rfl⟩ + · exact hmul A B rfl Γ Δ C k + · have := ih Γ (M ++ [A, B] ++ D) (by simp) + exact cast (LDer0.mulL (A := A) (B := B) (Γ := Γ ++ Θ ++ M) (Δ := D) (cast this (by simp))) (by simp) + · have := ih (G ++ [A, B] ++ M) Δ (by simp) + exact cast (LDer0.mulL (A := A) (B := B) (Γ := G) (Δ := M ++ Θ ++ Δ) (cast this (by simp))) (by simp) + +/-- Cut is admissible on the type `X`. -/ +def CutAdm (X : LType P) : Prop := + ∀ (Θ Γ Δ : List (LType P)) (C : LType P), + LDer0 Θ X → LDer0 (Γ ++ [X] ++ Δ) C → LDer0 (Γ ++ Θ ++ Δ) C + +/-- Cut is admissible on the immediate subtypes of a type. -/ +def SubAdm : LType P → Prop + | .prim _ => True + | .over A B => CutAdm A ∧ CutAdm B + | .under B A => CutAdm B ∧ CutAdm A + | .mul A B => CutAdm A ∧ CutAdm B + +/-- Cut on `X`, by induction on the left premise, given cut on the subtypes of `X`. -/ +theorem outer {Θ : List (LType P)} {X : LType P} (h1 : LDer0 Θ X) : + SubAdm X → ∀ (Γ Δ : List (LType P)) (C : LType P), + LDer0 (Γ ++ [X] ++ Δ) C → LDer0 (Γ ++ Θ ++ Δ) C := by + induction h1 with + | ax p => + intro _ Γ Δ C h2 + exact h2 + | @overR G A B hne k _ => + intro hs Γ Δ C h2 + simp only [SubAdm] at hs + refine inner (LDer0.overR hne k) hne ?_ (fun _ _ e => by cases e) + (fun _ _ e => by cases e) Γ Δ C h2 + intro A' B' e + cases e + intro Θ' Γ' Δ' C' hb hc + have k' := hs.2 Θ' G [] A hb (cast k (by simp)) + exact cast (hs.1 (G ++ Θ') Γ' Δ' C' (cast k' (by simp)) hc) (by simp) + | @underR G A B hne k _ => + intro hs Γ Δ C h2 + simp only [SubAdm] at hs + refine inner (LDer0.underR hne k) hne (fun _ _ e => by cases e) ?_ + (fun _ _ e => by cases e) Γ Δ C h2 + intro A' B' e + cases e + intro Θ' Γ' Δ' C' hb hc + have k' := hs.1 Θ' [] G A hb (cast k (by simp)) + exact cast (hs.2 (Θ' ++ G) Γ' Δ' C' (cast k' (by simp)) hc) (by simp) + | @overL G D T A B Y k1 _ _ ih2 => + intro hs Γ Δ C h2 + have := ih2 hs Γ Δ C h2 + exact cast (LDer0.overL (A := A) (B := B) (Γ := Γ ++ G) (Δ := D ++ Δ) k1 (cast this (by simp))) (by simp) + | @underL G D T A B Y k1 _ _ ih2 => + intro hs Γ Δ C h2 + have := ih2 hs Γ Δ C h2 + exact cast (LDer0.underL (A := A) (B := B) (Γ := Γ ++ G) (Δ := D ++ Δ) k1 (cast this (by simp))) (by simp) + | @mulR G D A B k1 k2 _ _ => + intro hs Γ Δ C h2 + simp only [SubAdm] at hs + have hne : G ++ D ≠ [] := by simp [LDer0.ne_nil k1] + refine inner (LDer0.mulR k1 k2) hne (fun _ _ e => by cases e) (fun _ _ e => by cases e) + ?_ Γ Δ C h2 + intro A' B' e + cases e + intro Γ' Δ' C' hc + have k' := hs.2 D (Γ' ++ [A]) Δ' C' k2 (cast hc (by simp)) + exact cast (hs.1 G Γ' (D ++ Δ') C' k1 (cast k' (by simp))) (by simp) + | @mulL G D A B Y _ ih => + intro hs Γ Δ C h2 + have := ih hs Γ Δ C h2 + exact cast (LDer0.mulL (A := A) (B := B) (Γ := Γ ++ G) (Δ := D ++ Δ) (cast this (by simp))) (by simp) + +theorem cutAdm (X : LType P) : CutAdm X := by + induction X with + | prim p => + intro Θ Γ Δ C h1 h2 + exact outer h1 (by simp only [SubAdm]) Γ Δ C h2 + | over A B ihA ihB => + intro Θ Γ Δ C h1 h2 + exact outer h1 (by simp only [SubAdm]; exact ⟨ihA, ihB⟩) Γ Δ C h2 + | under B A ihB ihA => + intro Θ Γ Δ C h1 h2 + exact outer h1 (by simp only [SubAdm]; exact ⟨ihB, ihA⟩) Γ Δ C h2 + | mul A B ihA ihB => + intro Θ Γ Δ C h1 h2 + exact outer h1 (by simp only [SubAdm]; exact ⟨ihA, ihB⟩) Γ Δ C h2 + +end LCut + +/-- Cut is admissible in the cut-free calculus. -/ +theorem LDer0.cut {Γ Δ Θ : List (LType P)} {A C : LType P} + (h1 : LDer0 Θ A) (h2 : LDer0 (Γ ++ [A] ++ Δ) C) : LDer0 (Γ ++ Θ ++ Δ) C := + LCut.cutAdm A Θ Γ Δ C h1 h2 + +/-- The cut-free calculus derives the same sequents as the calculus with cut. -/ +theorem LDer_iff_LDer0 {Γ : List (LType P)} {C : LType P} : LDer Γ C ↔ LDer0 Γ C := by + constructor + · intro h + induction h with + | ax A => exact LDer0.identity A + | overR hne _ ih => exact LDer0.overR hne ih + | underR hne _ ih => exact LDer0.underR hne ih + | overL _ _ ih1 ih2 => exact LDer0.overL ih1 ih2 + | underL _ _ ih1 ih2 => exact LDer0.underL ih1 ih2 + | mulR _ _ ih1 ih2 => exact LDer0.mulR ih1 ih2 + | mulL _ ih => exact LDer0.mulL ih + | cut _ _ ih1 ih2 => exact LDer0.cut ih1 ih2 + · intro h + induction h with + | ax p => exact LDer.ax _ + | overR hne _ ih => exact LDer.overR hne ih + | underR hne _ ih => exact LDer.underR hne ih + | overL _ _ ih1 ih2 => exact LDer.overL ih1 ih2 + | underL _ _ ih1 ih2 => exact LDer.underL ih1 ih2 + | mulR _ _ ih1 ih2 => exact LDer.mulR ih1 ih2 + | mulL _ ih => exact LDer.mulL ih + +/-- Derivability is preserved by renaming primitive types. -/ +theorem LDer0.map (f : P → Q) {Γ : List (LType P)} {C : LType P} (h : LDer0 Γ C) : + LDer0 (Γ.map (LType.map f)) (C.map f) := by + induction h with + | ax p => exact LDer0.ax (f p) + | overR hne _ ih => + exact LDer0.overR (by simpa using hne) (by simpa using ih) + | underR hne _ ih => + exact LDer0.underR (by simpa using hne) (by simpa using ih) + | overL _ _ ih1 ih2 => + simpa [LType.map] using LDer0.overL ih1 (by simpa using ih2) + | underL _ _ ih1 ih2 => + simpa [LType.map] using LDer0.underL ih1 (by simpa using ih2) + | mulR _ _ ih1 ih2 => + simpa [LType.map] using LDer0.mulR ih1 ih2 + | mulL _ ih => + simpa [LType.map] using LDer0.mulL (by simpa using ih) + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/LambekFreeGroup.lean b/LeanPool/FormalLinguistics/LambekFreeGroup.lean new file mode 100644 index 0000000000..3aa5700f62 --- /dev/null +++ b/LeanPool/FormalLinguistics/LambekFreeGroup.lean @@ -0,0 +1,652 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.LambekCore + +/-! + The free-group interpretation of the Lambek calculus and Pentus's lemma about free + groups. +-/ + +@[expose] public section + +namespace FormalLinguistics + +variable {P : Type} + +namespace FGWord + +/-! ### Basic theory of the normaliser -/ + +/-- `x` and `y` are mutually inverse letters. -/ +abbrev Canc (x y : P × Bool) : Prop := x.1 = y.1 ∧ x.2 = !y.2 + +theorem canc_symm {x y : P × Bool} (h : Canc x y) : Canc y x := by + obtain ⟨h1, h2⟩ := h + refine ⟨h1.symm, ?_⟩ + rw [h2]; simp + +/-- A word (or stack) without adjacent mutually inverse letters. -/ +def Red (s : FGWord P) : Prop := + ∀ (l₁ l₂ : FGWord P) (x y : P × Bool), s = l₁ ++ x :: y :: l₂ → ¬ Canc x y + +theorem red_nil : Red ([] : FGWord P) := by + intro l₁ l₂ x y h + have := congrArg List.length h + simp at this + +theorem red_single (x : P × Bool) : Red [x] := by + intro l₁ l₂ a b h + have := congrArg List.length h + simp at this + omega + +theorem red_cons_cons {x y : P × Bool} {s : FGWord P} : + Red (x :: y :: s) ↔ ¬ Canc x y ∧ Red (y :: s) := by + constructor + · intro H + refine ⟨H [] s x y rfl, ?_⟩ + intro l₁ l₂ a b h + exact H (x :: l₁) l₂ a b (by rw [h]; rfl) + · rintro ⟨h1, h2⟩ l₁ l₂ a b h + cases l₁ with + | nil => + simp only [List.nil_append, List.cons.injEq] at h + obtain ⟨rfl, rfl, rfl⟩ := h + exact h1 + | cons c l₁ => + simp only [List.cons_append, List.cons.injEq] at h + exact h2 l₁ l₂ a b h.2 + +theorem red_tail {x : P × Bool} {s : FGWord P} (h : Red (x :: s)) : Red s := by + intro l₁ l₂ a b e + exact h (x :: l₁) l₂ a b (by rw [e]; rfl) + +theorem red_reverse {s : FGWord P} (h : Red s) : Red s.reverse := by + intro l₁ l₂ a b e + have e' : s = l₂.reverse ++ b :: a :: l₁.reverse := by + have := congrArg List.reverse e + simp only [List.reverse_reverse] at this + rw [this] + simp + exact fun hc => h _ _ _ _ e' (canc_symm hc) + +/-- The letter-wise inversion used in `inv`. -/ +abbrev flip (x : P × Bool) : P × Bool := (x.1, !x.2) + +theorem red_map_flip {t : FGWord P} (h : Red t) : Red (t.map flip) := by + induction t with + | nil => exact red_nil + | cons x t ih => + cases t with + | nil => exact red_single _ + | cons y s => + rw [red_cons_cons] at h + have ih' := ih h.2 + simp only [List.map_cons] at ih' ⊢ + rw [red_cons_cons] + refine ⟨?_, ih'⟩ + intro hc + apply h.1 + obtain ⟨h1, h2⟩ := hc + refine ⟨h1, ?_⟩ + simpa using h2 + +theorem push_cons_of_canc [DecidableEq P] {y x : P × Bool} {s : FGWord P} (h : Canc y x) : + push (y :: s) x = s := by + simp only [push] + split + · rfl + · contradiction + +theorem push_cons_of_not [DecidableEq P] {y x : P × Bool} {s : FGWord P} (h : ¬ Canc y x) : + push (y :: s) x = x :: y :: s := by + simp only [push] + split + · contradiction + · rfl + +theorem red_push [DecidableEq P] {s : FGWord P} (h : Red s) (x : P × Bool) : + Red (push s x) := by + cases s with + | nil => exact red_single x + | cons y s' => + by_cases hc : Canc y x + · rw [push_cons_of_canc hc]; exact red_tail h + · rw [push_cons_of_not hc, red_cons_cons] + exact ⟨fun h' => hc (canc_symm h'), h⟩ + +theorem red_foldl [DecidableEq P] (w : FGWord P) : + ∀ (s : FGWord P), Red s → Red (w.foldl push s) := by + induction w with + | nil => intro s hs; exact hs + | cons x w ih => intro s hs; exact ih _ (red_push hs x) + +/-- Pushing a letter and then its inverse onto a reduced stack gives the stack back. -/ +theorem push_push [DecidableEq P] {s : FGWord P} (h : Red s) {x z : P × Bool} + (hc : Canc x z) : push (push s x) z = s := by + cases s with + | nil => + show push [x] z = [] + exact push_cons_of_canc hc + | cons y s' => + by_cases hy : Canc y x + · rw [push_cons_of_canc hy] + have hyz : y = z := by + obtain ⟨a1, a2⟩ := hy + obtain ⟨b1, b2⟩ := hc + apply Prod.ext + · exact a1.trans b1 + · rw [a2, b2]; simp + subst hyz + cases s' with + | nil => rfl + | cons w s'' => + rw [red_cons_cons] at h + exact push_cons_of_not (fun h' => h.1 (canc_symm h')) + · rw [push_cons_of_not hy] + exact push_cons_of_canc hc + +/-- The stack computed by the normaliser. -/ +def stk [DecidableEq P] (w : FGWord P) : FGWord P := w.foldl push [] + +theorem reduce_eq_stk [DecidableEq P] (w : FGWord P) : reduce w = (stk w).reverse := rfl + +theorem reduce_eq_iff [DecidableEq P] {u v : FGWord P} : reduce u = reduce v ↔ stk u = stk v := by + rw [reduce_eq_stk, reduce_eq_stk, List.reverse_inj] + +theorem norm_eq_len [DecidableEq P] (w : FGWord P) : norm w = (stk w).length := by + simp [norm, reduce_eq_stk] + +theorem red_stk [DecidableEq P] (w : FGWord P) : Red (stk w) := red_foldl w [] red_nil + +theorem stk_append [DecidableEq P] (u v : FGWord P) : stk (u ++ v) = v.foldl push (stk u) := + List.foldl_append + +theorem stk_nil [DecidableEq P] : stk ([] : FGWord P) = [] := rfl + +theorem stk_reverse_of_red [DecidableEq P] {s : FGWord P} (h : Red s) : stk s.reverse = s := by + induction s with + | nil => rfl + | cons y s' ih => + rw [List.reverse_cons, stk_append, ih (red_tail h)] + show push s' y = y :: s' + cases s' with + | nil => rfl + | cons w s'' => + rw [red_cons_cons] at h + exact push_cons_of_not (fun h' => h.1 (canc_symm h')) + +theorem foldl_push_reverse [DecidableEq P] {s : FGWord P} (hs : Red s) (t : FGWord P) + (x : P × Bool) : + (push t x).reverse.foldl push s = push (t.reverse.foldl push s) x := by + cases t with + | nil => rfl + | cons y t' => + by_cases hc : Canc y x + · rw [push_cons_of_canc hc, List.reverse_cons, List.foldl_append] + exact (push_push (red_foldl _ _ hs) hc).symm + · rw [push_cons_of_not hc, List.reverse_cons (a := x), List.foldl_append] + rfl + +theorem foldl_append_eq [DecidableEq P] {s : FGWord P} (hs : Red s) (v : FGWord P) : + ∀ (t : FGWord P), (t.reverse ++ v).foldl push s = (v.foldl push t).reverse.foldl push s := by + induction v with + | nil => intro t; simp + | cons x v ih => + intro t + rw [List.foldl_cons, ← ih (push t x), List.foldl_append, List.foldl_append, + List.foldl_cons, foldl_push_reverse hs] + +theorem foldl_stk_reverse [DecidableEq P] {s : FGWord P} (hs : Red s) (v : FGWord P) : + v.foldl push s = (stk v).reverse.foldl push s := by + have := foldl_append_eq hs v [] + simp only [List.reverse_nil, List.nil_append] at this + exact this + +theorem stk_append_right [DecidableEq P] (u v : FGWord P) : + stk (u ++ v) = stk (u ++ (stk v).reverse) := by + rw [stk_append, stk_append, ← foldl_stk_reverse (red_stk u)] + +theorem stk_append_left [DecidableEq P] (u v : FGWord P) : + stk (u ++ v) = stk ((stk u).reverse ++ v) := by + rw [stk_append, stk_append, stk_reverse_of_red (red_stk u)] + +theorem stk_congr [DecidableEq P] {u u' v v' : FGWord P} (hu : stk u = stk u') + (hv : stk v = stk v') : stk (u ++ v) = stk (u' ++ v') := by + rw [stk_append_left, hu, stk_append_right, hv, ← stk_append_right, ← stk_append_left] + +theorem stk_append_of_nil [DecidableEq P] (x : FGWord P) {y : FGWord P} (hy : stk y = []) : + stk (x ++ y) = stk x := by + rw [stk_append_right, hy]; simp + +theorem stk_mid_of_nil [DecidableEq P] (x : FGWord P) {y : FGWord P} (z : FGWord P) + (hy : stk y = []) : stk (x ++ (y ++ z)) = stk (x ++ z) := by + rw [← List.append_assoc, stk_append_left, stk_append_of_nil x hy, ← stk_append_left] + +theorem inv_nil : inv ([] : FGWord P) = [] := rfl + +theorem inv_cons (x : P × Bool) (w : FGWord P) : inv (x :: w) = inv w ++ [flip x] := by + simp [inv] + +theorem inv_append (u v : FGWord P) : inv (u ++ v) = inv v ++ inv u := by + simp [inv] + +theorem inv_inv (w : FGWord P) : inv (inv w) = w := by + simp [inv, List.map_reverse, Function.comp_def] + +theorem length_inv (w : FGWord P) : (inv w).length = w.length := by + simp [inv] + +theorem stk_append_inv [DecidableEq P] (w : FGWord P) : stk (w ++ inv w) = [] := by + induction w with + | nil => rfl + | cons x w ih => + rw [inv_cons] + have e : x :: w ++ (inv w ++ [flip x]) = [x] ++ (w ++ inv w) ++ [flip x] := by simp + rw [e, stk_append, List.foldl_cons, List.foldl_nil, stk_append_right, ih] + show push [x] (flip x) = [] + exact push_cons_of_canc ⟨rfl, by simp⟩ + +theorem stk_inv_append [DecidableEq P] (w : FGWord P) : stk (inv w ++ w) = [] := by + have := stk_append_inv (inv w) + rwa [inv_inv] at this + +theorem stk_cancel_inv_left [DecidableEq P] (x y z : FGWord P) : + stk (x ++ (inv y ++ (y ++ z))) = stk (x ++ z) := by + rw [← List.append_assoc (inv y)] + exact stk_mid_of_nil x z (stk_inv_append y) + +theorem stk_cancel_inv_right [DecidableEq P] (x y z : FGWord P) : + stk (x ++ (y ++ (inv y ++ z))) = stk (x ++ z) := by + rw [← List.append_assoc y] + exact stk_mid_of_nil x z (stk_append_inv y) + +theorem stk_inv_congr [DecidableEq P] {u v : FGWord P} (h : stk u = stk v) : + stk (inv u) = stk (inv v) := by + have h1 : stk (inv u ++ v) = [] := by + rw [stk_append_right, ← h, ← stk_append_right, stk_inv_append] + calc stk (inv u) = stk (inv u ++ (v ++ inv v)) := by + rw [stk_append_of_nil _ (stk_append_inv v)] + _ = stk (inv v) := by + rw [← List.append_assoc, stk_append_left, h1]; simp + +theorem stk_inv [DecidableEq P] (w : FGWord P) : stk (inv w) = inv (stk w) := by + have h1 : stk w = stk (stk w).reverse := (stk_reverse_of_red (red_stk w)).symm + rw [stk_inv_congr h1] + have e : inv (stk w).reverse = ((stk w).map flip).reverse.reverse := by simp [inv] + rw [e, stk_reverse_of_red (red_reverse (red_map_flip (red_stk w)))] + rfl + + +/-! ### Cancellation between a stack and a reduced word -/ + +private theorem ite_of_pos {α : Type} {c : Prop} [Decidable c] {a b : α} (h : c) : + (if c then a else b) = a := by simp [h] + +private theorem ite_of_neg {α : Type} {c : Prop} [Decidable c] {a b : α} (h : ¬ c) : + (if c then a else b) = b := by simp [h] + +/-- Number of letters cancelled when the word `w` is pushed onto the stack `s`. -/ +def cl [DecidableEq P] : FGWord P → FGWord P → Nat + | y :: s, x :: w => if y.1 = x.1 ∧ y.2 = !x.2 then cl s w + 1 else 0 + | _, _ => 0 + +theorem cl_cons_cons [DecidableEq P] (y x : P × Bool) (s w : FGWord P) : + cl (y :: s) (x :: w) = if y.1 = x.1 ∧ y.2 = !x.2 then cl s w + 1 else 0 := by + simp [cl] + +theorem cl_nil_left [DecidableEq P] (w : FGWord P) : cl [] w = 0 := by + cases w <;> simp [cl] + +theorem cl_nil_right [DecidableEq P] (s : FGWord P) : cl s [] = 0 := by + cases s <;> simp [cl] + +theorem cl_le [DecidableEq P] (s : FGWord P) : + ∀ (w : FGWord P), cl s w ≤ s.length ∧ cl s w ≤ w.length := by + induction s with + | nil => intro w; simp [cl_nil_left] + | cons y s ih => + intro w + cases w with + | nil => simp [cl_nil_right] + | cons x w => + rw [cl_cons_cons] + by_cases hc : y.1 = x.1 ∧ y.2 = !x.2 + · rw [ite_of_pos hc] + have := ih w + simp only [List.length_cons] + omega + · rw [ite_of_neg hc] + simp + +theorem cl_head_zero [DecidableEq P] {x : P × Bool} {w : FGWord P} (hw : Red (x :: w)) + (s : FGWord P) : cl (x :: s) w = 0 := by + cases w with + | nil => exact cl_nil_right _ + | cons z w => + rw [red_cons_cons] at hw + rw [cl_cons_cons, ite_of_neg (show ¬ (x.1 = z.1 ∧ x.2 = !z.2) from hw.1)] + +theorem foldl_cl [DecidableEq P] (w : FGWord P) (hw : Red w) : + ∀ (s : FGWord P), Red s → + w.foldl push s = (w.drop (cl s w)).reverse ++ s.drop (cl s w) := by + induction w with + | nil => intro s _; simp [cl_nil_right] + | cons x w ih => + intro s hs + have hw' := red_tail hw + cases s with + | nil => + rw [List.foldl_cons] + show w.foldl push [x] = _ + rw [ih hw' [x] (red_single x), cl_head_zero hw, cl_nil_left] + simp + | cons y s' => + by_cases hc : Canc y x + · rw [List.foldl_cons, push_cons_of_canc hc, ih hw' s' (red_tail hs), cl_cons_cons, + ite_of_pos (show y.1 = x.1 ∧ y.2 = !x.2 from hc)] + simp + · rw [List.foldl_cons, push_cons_of_not hc] + have hs2 : Red (x :: y :: s') := red_cons_cons.2 ⟨fun h => hc (canc_symm h), hs⟩ + rw [ih hw' _ hs2, cl_head_zero hw, cl_cons_cons, + ite_of_neg (show ¬ (y.1 = x.1 ∧ y.2 = !x.2) from hc)] + simp + +theorem cl_append_eq [DecidableEq P] (q m p : FGWord P) : + ∀ (w : FGWord P), cl (q ++ m) w < q.length → cl (q ++ p) w = cl (q ++ m) w := by + induction q with + | nil => intro w h; simp at h + | cons y q ih => + intro w h + cases w with + | nil => simp [cl_nil_right] + | cons x w => + simp only [List.cons_append, cl_cons_cons] at h ⊢ + by_cases hc : y.1 = x.1 ∧ y.2 = !x.2 + · rw [ite_of_pos hc] at h ⊢ + rw [ite_of_pos hc, ih w (by simp only [List.length_cons] at h; omega)] + · rw [ite_of_neg hc, ite_of_neg hc] + +/-! ### Pentus's lemma: the inductive invariant -/ + +private theorem pentus_aux [DecidableEq P] (rest : List (FGWord P)) : + ∀ (X u : FGWord P), + (∃ q p m : FGWord P, stk X = q ++ p ∧ stk u = q ++ m ∧ (stk u).length ≤ 2 * q.length) → + (∀ (l r : List (FGWord P)) (a b : FGWord P), u :: rest = l ++ a :: b :: r → + max (norm a) (norm b) < norm (a ++ b)) → + (rest = [] → 0 < (stk u).length) → + 0 < (stk (X ++ rest.flatten)).length := by + induction rest with + | nil => + intro X u ⟨q, p, m, hX, hu, hl⟩ _ hpos + have := hpos rfl + simp only [List.flatten_nil, List.append_nil, hX, List.length_append] + omega + | cons v rest ih => + intro X u ⟨q, p, m, hX, hu, hl⟩ hbad _ + have huv := hbad [] rest u v rfl + obtain ⟨b, hbdef⟩ : ∃ b, b = (stk v).reverse := ⟨_, rfl⟩ + have hb : Red b := hbdef ▸ red_reverse (red_stk v) + have hvb : stk v = b.reverse := by rw [hbdef, List.reverse_reverse] + have e1 : stk (u ++ v) = (b.drop (cl (stk u) b)).reverse ++ (stk u).drop (cl (stk u) b) := by + rw [stk_append, foldl_stk_reverse (red_stk u), ← hbdef, foldl_cl b hb _ (red_stk u)] + have e2 : stk (X ++ v) = (b.drop (cl (stk X) b)).reverse ++ (stk X).drop (cl (stk X) b) := by + rw [stk_append, foldl_stk_reverse (red_stk X), ← hbdef, foldl_cl b hb _ (red_stk X)] + rw [norm_eq_len, norm_eq_len, norm_eq_len, e1, hvb] at huv + have hk := cl_le (stk u) b + have hmax1 := Nat.le_max_left (stk u).length b.reverse.length + have hmax2 := Nat.le_max_right (stk u).length b.reverse.length + simp only [List.length_append, List.length_reverse, List.length_drop] at huv hmax1 hmax2 + have hk1 : 2 * cl (stk u) b < b.length := by omega + have hk2 : 2 * cl (stk u) b < (stk u).length := by omega + have hkq : cl (q ++ m) b < q.length := by + rw [hu] at hk2 hl; omega + have hk : cl (stk X) b = cl (stk u) b := by + rw [hX, hu]; exact cl_append_eq q m p b hkq + rw [hk] at e2 + have := ih (X ++ v) v + ⟨(b.drop (cl (stk u) b)).reverse, (stk X).drop (cl (stk u) b), + (b.take (cl (stk u) b)).reverse, e2, + by rw [hvb, ← List.reverse_append, List.take_append_drop], + by simp only [hvb, List.length_reverse, List.length_drop]; omega⟩ + (fun l r a b' e => hbad (u :: l) r a b' (by rw [e]; rfl)) + (fun _ => by rw [hvb, List.length_reverse]; omega) + simpa [List.append_assoc] using this + +/-! ### Lengths and generators -/ + +theorem length_push_le [DecidableEq P] (s : FGWord P) (x : P × Bool) : + (push s x).length ≤ s.length + 1 := by + cases s with + | nil => simp [push] + | cons y s => + by_cases hc : Canc y x + · rw [push_cons_of_canc hc]; simp only [List.length_cons]; omega + · rw [push_cons_of_not hc]; simp + +theorem length_foldl_push_le [DecidableEq P] (w : FGWord P) : + ∀ (s : FGWord P), (w.foldl push s).length ≤ s.length + w.length := by + induction w with + | nil => intro s; simp + | cons x w ih => + intro s + have h1 := ih (push s x) + have h2 := length_push_le s x + simp only [List.foldl_cons, List.length_cons] + omega + +theorem norm_le_length [DecidableEq P] (w : FGWord P) : norm w ≤ w.length := by + rw [norm_eq_len] + have := length_foldl_push_le w [] + simpa [stk] using this + +theorem count_fst_inv [DecidableEq P] (p : P) (w : FGWord P) : + ((inv w).map Prod.fst).count p = (w.map Prod.fst).count p := by + induction w with + | nil => rfl + | cons x w ih => + rw [inv_cons] + simp [List.count_append, List.count_cons, ih] + +theorem red_of_count [DecidableEq P] {w : FGWord P} + (h : ∀ p : P, (w.map Prod.fst).count p ≤ 1) : Red w := by + intro l₁ l₂ x y e hc + have := h x.1 + rw [e] at this + simp [List.count_append, hc.1] at this + omega + +theorem stk_of_red [DecidableEq P] {w : FGWord P} (h : Red w) : stk w = w.reverse := by + have := stk_reverse_of_red (red_reverse h) + rwa [List.reverse_reverse] at this + +/-- The norm of a word is the norm of its inverse. -/ +theorem norm_inv [DecidableEq P] (w : FGWord P) : norm (inv w) = norm w := by + rw [norm_eq_len, norm_eq_len, stk_inv, length_inv] + +/-- Words with the same reduced form have the same norm. -/ +theorem norm_eq_of_reduce_eq [DecidableEq P] {u v : FGWord P} (h : reduce u = reduce v) : + norm u = norm v := by + unfold norm; rw [h] + +/-- If `u` and `v` have the same reduced form, then `u · v⁻¹` reduces to the empty word. -/ +theorem reduce_append_inv_eq_nil [DecidableEq P] {u v : FGWord P} (h : reduce u = reduce v) : + reduce (u ++ inv v) = [] := by + have h' : stk u = stk v := reduce_eq_iff.1 h + rw [reduce_eq_stk, stk_append_left, h', ← stk_append_left, stk_append_inv] + rfl + +/-- If `a · b` reduces to the empty word, then `a` and `b` have the same norm. -/ +theorem norm_eq_of_reduce_append_eq_nil [DecidableEq P] {a b : FGWord P} + (h : reduce (a ++ b) = []) : norm a = norm b := by + have h0 : stk (a ++ b) = [] := by + rw [reduce_eq_stk, List.reverse_eq_nil_iff] at h; exact h + have hb : stk b = stk (inv a) := by + calc stk b = stk (inv a ++ a ++ b) := by + rw [stk_append_left (inv a ++ a), stk_inv_append]; rfl + _ = stk (inv a) := by + rw [List.append_assoc, stk_append_of_nil _ h0] + rw [norm_eq_len b, hb, ← norm_eq_len, norm_inv] + +/-- If `a · b · c` reduces to the empty word, then `b` has the same reduced form as + `a⁻¹ · c⁻¹`, hence the same norm as `c · a`. -/ +theorem norm_mid_eq_of_reduce_eq_nil [DecidableEq P] {a b c : FGWord P} + (h : reduce (a ++ b ++ c) = []) : norm b = norm (c ++ a) := by + have h0 : stk (a ++ (b ++ c)) = [] := by + rw [reduce_eq_stk, List.reverse_eq_nil_iff, List.append_assoc] at h; exact h + -- `b · c` has the reduced form of `a⁻¹`, so `b · c · a` reduces to the empty word. + have hbc : stk (b ++ c) = stk (inv a) := by + calc stk (b ++ c) = stk (inv a ++ a ++ (b ++ c)) := by + rw [stk_append_left (inv a ++ a), stk_inv_append]; rfl + _ = stk (inv a) := by + rw [List.append_assoc, stk_append_of_nil _ h0] + have h1 : stk (b ++ (c ++ a)) = [] := by + rw [← List.append_assoc, stk_append_left, hbc, ← stk_append_left, stk_inv_append] + apply norm_eq_of_reduce_append_eq_nil + rw [reduce_eq_stk, h1]; rfl + +/-- **Pentus's lemma.** If a product of at least two words reduces to the empty word, + then some two adjacent factors `u`, `v` satisfy `|u v| ≤ max(|u|, |v|)`. -/ +theorem pentus_lemma [DecidableEq P] (us : List (FGWord P)) (hlen : 2 ≤ us.length) + (h : reduce us.flatten = []) : + ∃ (l r : List (FGWord P)) (u v : FGWord P), + us = l ++ u :: v :: r ∧ norm (u ++ v) ≤ max (norm u) (norm v) := by + classical + obtain ⟨u, v, rest, rfl⟩ : ∃ u v rest, us = u :: v :: rest := by + match us, hlen with + | [], h => simp at h + | [_], h => simp at h + | u :: v :: rest, _ => exact ⟨u, v, rest, rfl⟩ + refine Classical.byContradiction fun hne => ?_ + have hbad : ∀ (l r : List (FGWord P)) (a b : FGWord P), u :: v :: rest = l ++ a :: b :: r → + max (norm a) (norm b) < norm (a ++ b) := by + intro l r a b e + exact Nat.lt_of_not_le (fun hle => hne ⟨l, r, a, b, e, hle⟩) + have hpos := pentus_aux (v :: rest) u u + ⟨stk u, [], [], by simp, by simp, by omega⟩ hbad (fun h => nomatch h) + have h0 : stk (u :: v :: rest).flatten = [] := by + rw [reduce_eq_stk, List.reverse_eq_nil_iff] at h; exact h + rw [List.flatten_cons] at h0 + rw [h0] at hpos + simp at hpos + +end FGWord + +private theorem interpList_nil : interpList ([] : List (LType P)) = [] := rfl + +private theorem interpList_cons (A : LType P) (Γ : List (LType P)) : + interpList (A :: Γ) = A.interp ++ interpList Γ := by + simp [interpList] + +private theorem interpList_append (Γ Δ : List (LType P)) : + interpList (Γ ++ Δ) = interpList Γ ++ interpList Δ := by + simp [interpList] + +private theorem interp_sound_stk [DecidableEq P] {Γ : List (LType P)} {C : LType P} + (h : LDer0 Γ C) : FGWord.stk (interpList Γ) = FGWord.stk C.interp := by + induction h with + | ax p => simp [interpList_cons, interpList_nil] + | @overR Γ A B _ _ ih => + rw [interpList_append, interpList_cons, interpList_nil, List.append_nil] at ih + simp only [LType.interp] + calc FGWord.stk (interpList Γ) + = FGWord.stk (interpList Γ ++ (B.interp ++ (FGWord.inv B.interp ++ []))) := by + rw [FGWord.stk_cancel_inv_right, List.append_nil] + _ = FGWord.stk (A.interp ++ FGWord.inv B.interp) := by + rw [List.append_nil, ← List.append_assoc] + exact FGWord.stk_congr ih rfl + | @underR Γ A B _ _ ih => + rw [interpList_cons] at ih + simp only [LType.interp] + calc FGWord.stk (interpList Γ) + = FGWord.stk ([] ++ (FGWord.inv B.interp ++ (B.interp ++ interpList Γ))) := by + rw [FGWord.stk_cancel_inv_left, List.nil_append] + _ = FGWord.stk (FGWord.inv B.interp ++ A.interp) := by + rw [List.nil_append] + exact FGWord.stk_congr rfl ih + | @overL Γ Δ Θ A B C _ _ ih1 ih2 => + simp only [interpList_append, interpList_cons, interpList_nil, List.append_nil, + LType.interp, List.append_assoc] at ih2 ⊢ + rw [← ih2] + calc FGWord.stk (interpList Γ ++ (A.interp ++ (FGWord.inv B.interp ++ + (interpList Θ ++ interpList Δ)))) + = FGWord.stk ((interpList Γ ++ (A.interp ++ FGWord.inv B.interp)) ++ + (interpList Θ ++ interpList Δ)) := by simp only [List.append_assoc] + _ = FGWord.stk ((interpList Γ ++ (A.interp ++ FGWord.inv B.interp)) ++ + (B.interp ++ interpList Δ)) := FGWord.stk_congr rfl (FGWord.stk_congr ih1 rfl) + _ = FGWord.stk ((interpList Γ ++ A.interp) ++ (FGWord.inv B.interp ++ + (B.interp ++ interpList Δ))) := by simp only [List.append_assoc] + _ = FGWord.stk (interpList Γ ++ (A.interp ++ interpList Δ)) := by + rw [FGWord.stk_cancel_inv_left, List.append_assoc] + | @underL Γ Δ Θ A B C _ _ ih1 ih2 => + simp only [interpList_append, interpList_cons, interpList_nil, List.append_nil, + LType.interp, List.append_assoc] at ih2 ⊢ + rw [← ih2] + calc FGWord.stk (interpList Γ ++ (interpList Θ ++ (FGWord.inv B.interp ++ + (A.interp ++ interpList Δ)))) + = FGWord.stk (interpList Γ ++ (B.interp ++ (FGWord.inv B.interp ++ + (A.interp ++ interpList Δ)))) := + FGWord.stk_congr rfl (FGWord.stk_congr ih1 rfl) + _ = FGWord.stk (interpList Γ ++ (A.interp ++ interpList Δ)) := + FGWord.stk_cancel_inv_right _ _ _ + | @mulR Γ Δ A B _ _ ih1 ih2 => + rw [interpList_append] + exact FGWord.stk_congr ih1 ih2 + | @mulL Γ Δ A B C _ ih => + simp only [interpList_append, interpList_cons, interpList_nil, List.append_nil, + LType.interp, List.append_assoc] at ih ⊢ + exact ih + +private theorem length_interp (A : LType P) : A.interp.length = A.size := by + induction A with + | prim p => rfl + | over A B ihA ihB => + simp only [LType.interp, LType.size, List.length_append, FGWord.length_inv, ihA, ihB] + | under B A ihB ihA => + simp only [LType.interp, LType.size, List.length_append, FGWord.length_inv, ihA, ihB] + | mul A B ihA ihB => + simp only [LType.interp, LType.size, List.length_append, ihA, ihB] + +private theorem count_interp [DecidableEq P] (p : P) (A : LType P) : + (A.interp.map Prod.fst).count p = A.occ p := by + induction A with + | prim q => + simp only [LType.interp, LType.occ, List.map_cons, List.map_nil, List.count_cons, + List.count_nil, beq_iff_eq] + split <;> simp + | over A B ihA ihB => + simp only [LType.interp, LType.occ, List.map_append, List.count_append, + FGWord.count_fst_inv, ihA, ihB] + | under B A ihB ihA => + simp only [LType.interp, LType.occ, List.map_append, List.count_append, + FGWord.count_fst_inv, ihA, ihB] + | mul A B ihA ihB => + simp only [LType.interp, LType.occ, List.map_append, List.count_append, ihA, ihB] + +/-- Soundness of the free-group interpretation: a derivable sequent has equal + interpretations on both sides. -/ +theorem LDer0.interp_sound [DecidableEq P] {Γ : List (LType P)} {C : LType P} + (h : LDer0 Γ C) : FGWord.reduce (interpList Γ) = FGWord.reduce C.interp := + FGWord.reduce_eq_iff.2 (interp_sound_stk h) + +/-- The norm of the interpretation of a type is at most its size. -/ +theorem LType.norm_interp_le [DecidableEq P] (A : LType P) : + FGWord.norm A.interp ≤ A.size := by + have := FGWord.norm_le_length A.interp + rwa [length_interp] at this + +/-- If every primitive type occurs at most once in `A`, the interpretation of `A` is + already reduced, so its norm equals the size of `A`. -/ +theorem LType.norm_interp_eq_size [DecidableEq P] (A : LType P) + (h : ∀ p : P, A.occ p ≤ 1) : FGWord.norm A.interp = A.size := by + have hr : FGWord.Red A.interp := + FGWord.red_of_count (fun p => by rw [count_interp]; exact h p) + rw [FGWord.norm_eq_len, FGWord.stk_of_red hr, List.length_reverse, length_interp] + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/LambekInterpolation.lean b/LeanPool/FormalLinguistics/LambekInterpolation.lean new file mode 100644 index 0000000000..0277eadd69 --- /dev/null +++ b/LeanPool/FormalLinguistics/LambekInterpolation.lean @@ -0,0 +1,291 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.LambekCore + +/-! + The interpolation theorem for the Lambek calculus (Roorda 1991), in the form used by + Pentus (1993). + + The proof follows Jäger's proof as presented by Kanazawa (2018, Theorem 3), restricted + to the connectives `/`, `\` and `•`: induction on the cut-free derivation, with a case + distinction on the position of the segment relative to the active formulas of the last + rule. +-/ + +@[expose] public section + +namespace FormalLinguistics + +variable {P : Type} + +namespace LInterp + +open LType + +theorem occList_nil [DecidableEq P] (p : P) : occList p ([] : List (LType P)) = 0 := rfl + +theorem occList_cons [DecidableEq P] (p : P) (A : LType P) (Γ : List (LType P)) : + occList p (A :: Γ) = A.occ p + occList p Γ := by + simp [occList] + +theorem occList_append [DecidableEq P] (p : P) (Γ Δ : List (LType P)) : + occList p (Γ ++ Δ) = occList p Γ + occList p Δ := by + simp [occList, List.sum_append] + +/-- The interpolation property for the sequent `L, S, R → C` relative to the segment `S`. -/ +def IP [DecidableEq P] (L S R : List (LType P)) (C : LType P) : Prop := + ∃ E : LType P, LDer0 S E ∧ LDer0 (L ++ [E] ++ R) C ∧ + ∀ p : P, E.occ p ≤ occList p S ∧ E.occ p ≤ occList p L + occList p R + C.occ p + +theorem castD {X Y : List (LType P)} {C : LType P} (h : LDer0 X C) (e : X = Y) : + LDer0 Y C := e ▸ h + +theorem overL' {Y : List (LType P)} (G D T : List (LType P)) {A B C : LType P} + (h1 : LDer0 T B) (h2 : LDer0 Y C) (eY : Y = G ++ [A] ++ D) : + LDer0 (G ++ [over A B] ++ T ++ D) C := by + subst eY; exact LDer0.overL h1 h2 + +theorem underL' {Y : List (LType P)} (G D T : List (LType P)) {A B C : LType P} + (h1 : LDer0 T B) (h2 : LDer0 Y C) (eY : Y = G ++ [A] ++ D) : + LDer0 (G ++ T ++ [under B A] ++ D) C := by + subst eY; exact LDer0.underL h1 h2 + +theorem mulL' {Y : List (LType P)} (G D : List (LType P)) {A B C : LType P} + (h : LDer0 Y C) (eY : Y = G ++ [A, B] ++ D) : + LDer0 (G ++ [mul A B] ++ D) C := by + subst eY; exact LDer0.mulL h + +theorem split3 {α : Type} {L S R A B : List α} (h : L ++ S ++ R = A ++ B) : + (∃ M, A = L ++ S ++ M ∧ R = M ++ B) ∨ (∃ M, B = M ++ S ++ R ∧ L = A ++ M) ∨ + (∃ S1 S2, S = S1 ++ S2 ∧ S1 ≠ [] ∧ S2 ≠ [] ∧ A = L ++ S1 ∧ B = S2 ++ R) := by + rw [List.append_assoc, List.append_eq_append_iff] at h + rcases h with ⟨a', rfl, h⟩ | ⟨c', rfl, rfl⟩ + · rw [List.append_eq_append_iff] at h + rcases h with ⟨b, rfl, rfl⟩ | ⟨c, rfl, rfl⟩ + · left; exact ⟨b, by simp, rfl⟩ + · by_cases ha : a' = [] + · subst ha; right; left; exact ⟨[], by simp, by simp⟩ + · by_cases hc : c = [] + · subst hc; left; exact ⟨[], by simp, by simp⟩ + · right; right; exact ⟨a', c, rfl, ha, hc, rfl, rfl⟩ + · right; left; exact ⟨c', by simp, rfl⟩ + +theorem split_mid {α : Type} {L S R P Q : List α} {X : α} (h : L ++ S ++ R = P ++ X :: Q) : + (∃ M, P = L ++ S ++ M ∧ R = M ++ X :: Q) ∨ + (∃ M, Q = M ++ S ++ R ∧ L = P ++ X :: M) ∨ + (∃ P2 Q1, S = P2 ++ X :: Q1 ∧ P = L ++ P2 ∧ Q = Q1 ++ R) := by + rcases split3 h with h | ⟨M, hM, rfl⟩ | ⟨S1, S2, rfl, _, hS2, rfl, hB⟩ + · exact Or.inl h + · rcases M with _ | ⟨m, M⟩ + · rcases S with _ | ⟨s, S⟩ + · left; exact ⟨[], by simp, by simpa using hM.symm⟩ + · simp only [List.nil_append, List.cons_append, List.cons.injEq] at hM + obtain ⟨rfl, rfl⟩ := hM + right; right; exact ⟨[], S, by simp, by simp, rfl⟩ + · simp only [List.cons_append, List.cons.injEq] at hM + obtain ⟨rfl, rfl⟩ := hM + right; left; exact ⟨M, by simp, rfl⟩ + · rcases S2 with _ | ⟨s, S2⟩ + · exact absurd rfl hS2 + · simp only [List.cons_append, List.cons.injEq] at hB + obtain ⟨rfl, rfl⟩ := hB + right; right; exact ⟨S1, S2, rfl, rfl, rfl⟩ + +/-- Normalize atom-occurrence counts for the arithmetic bounds in interpolation. -/ +macro "occBound" : tactic => + `(tactic| focus + simp only [occList_append, occList_cons, occList_nil, LType.occ, List.append_assoc, + List.cons_append, List.nil_append, List.singleton_append] at * + omega) + +theorem main [DecidableEq P] {Ξ : List (LType P)} {C : LType P} (h : LDer0 Ξ C) : + ∀ L S R : List (LType P), Ξ = L ++ S ++ R → S ≠ [] → IP L S R C := by + induction h with + | ax p => + intro L S R e hS + rcases L with _ | ⟨l, L⟩ + · rcases S with _ | ⟨s, S⟩ + · exact absurd rfl hS + · simp at e + obtain ⟨rfl, rfl, rfl⟩ := e + exact ⟨prim p, LDer0.ax p, LDer0.ax p, fun q => by simp [occList]⟩ + · simp at e + exact absurd e.2.2.1 hS + | @overR G A B _ _ ih => + intro L S R e hS + subst e + obtain ⟨E, h1, h2, hb⟩ := ih L S (R ++ [B]) (by simp) hS + refine ⟨E, h1, LDer0.overR (by simp) (castD h2 (by simp)), fun p => ?_⟩ + have := hb p + occBound + | @underR G A B _ _ ih => + intro L S R e hS + subst e + obtain ⟨E, h1, h2, hb⟩ := ih (B :: L) S R (by simp) hS + refine ⟨E, h1, LDer0.underR (by simp) (castD h2 (by simp)), fun p => ?_⟩ + have := hb p + occBound + | @overL G D T A B C hT hm ihT ihm => + intro L S R e hS + have e' : L ++ S ++ R = G ++ over A B :: (T ++ D) := by rw [← e]; simp + rcases split_mid e' with ⟨M, rfl, rfl⟩ | ⟨M, hM, rfl⟩ | ⟨P2, Q1, rfl, rfl, hQ⟩ + · obtain ⟨E, h1, h2, hb⟩ := ihm L S (M ++ [A] ++ D) (by simp) hS + refine ⟨E, h1, castD (overL' (A := A) (L ++ [E] ++ M) D T hT h2 (by simp)) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · rcases split3 hM.symm with ⟨N, rfl, rfl⟩ | ⟨N, rfl, rfl⟩ | + ⟨S1, S2, rfl, hS1, hS2, rfl, rfl⟩ + · obtain ⟨E, h1, h2, hb⟩ := ihT M S N rfl hS + refine ⟨E, h1, castD (overL' (A := A) G D (M ++ [E] ++ N) h2 hm rfl) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihm (G ++ [A] ++ N) S R (by simp) hS + refine ⟨E, h1, castD (overL' (A := A) G (N ++ [E] ++ R) T hT h2 (by simp)) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihT M S1 [] (by simp) hS1 + obtain ⟨F, h3, h4, hc⟩ := ihm (G ++ [A]) S2 R (by simp) hS2 + refine ⟨mul E F, LDer0.mulR h1 h3, + castD (mulL' (A := E) (B := F) (G ++ over A B :: M) R + (overL' (A := A) G (F :: R) (M ++ [E]) (castD h2 (by simp)) h4 (by simp)) (by simp)) + (by simp), fun p => ?_⟩ + have := hb p + have := hc p + occBound + · rw [List.append_eq_append_iff] at hQ + rcases hQ with ⟨a', rfl, rfl⟩ | ⟨c', rfl, rfl⟩ + · obtain ⟨E, h1, h2, hb⟩ := ihm L (P2 ++ [A] ++ a') R (by simp) (by simp) + refine ⟨E, castD (overL' (A := A) P2 a' T hT h1 rfl) (by simp), h2, fun p => ?_⟩ + have := hb p + occBound + · by_cases hc : c' = [] + · subst hc + obtain ⟨E, h1, h2, hb⟩ := ihm L (P2 ++ [A]) D (by simp) (by simp) + refine ⟨E, castD (overL' (A := A) P2 [] (Q1 ++ []) hT h1 (by simp)) (by simp), + castD h2 (by simp), fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihT Q1 c' [] (by simp) hc + obtain ⟨F, h3, h4, hd⟩ := ihm L (P2 ++ [A]) D (by simp) (by simp) + refine ⟨over F E, + LDer0.overR (by simp) + (castD (overL' (A := A) P2 [] (Q1 ++ [E]) (castD h2 (by simp)) h3 (by simp)) + (by simp)), + castD (overL' (A := F) L D c' h1 h4 (by simp)) (by simp), fun p => ?_⟩ + have := hb p + have := hd p + occBound + | @underL G D T A B C hT hm ihT ihm => + intro L S R e hS + have e' : L ++ S ++ R = (G ++ T) ++ under B A :: D := by rw [← e]; simp + rcases split_mid e' with ⟨M, hM, rfl⟩ | ⟨M, rfl, rfl⟩ | ⟨P2, Q1, rfl, hP, rfl⟩ + · rcases split3 hM.symm with ⟨N, rfl, rfl⟩ | ⟨N, rfl, rfl⟩ | + ⟨S1, S2, rfl, hS1, hS2, rfl, rfl⟩ + · obtain ⟨E, h1, h2, hb⟩ := ihm L S (N ++ [A] ++ D) (by simp) hS + refine ⟨E, h1, castD (underL' (A := A) (L ++ [E] ++ N) D T hT h2 (by simp)) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihT N S M rfl hS + refine ⟨E, h1, castD (underL' (A := A) G D (N ++ [E] ++ M) h2 hm rfl) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihm L S1 ([A] ++ D) (by simp) hS1 + obtain ⟨F, h3, h4, hc⟩ := ihT [] S2 M (by simp) hS2 + refine ⟨mul E F, LDer0.mulR h1 h3, + castD (mulL' (A := E) (B := F) L (M ++ under B A :: D) + (underL' (A := A) (L ++ [E]) D (F :: M) (castD h4 (by simp)) h2 (by simp)) (by simp)) + (by simp), fun p => ?_⟩ + have := hb p + have := hc p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihm (G ++ [A] ++ M) S R (by simp) hS + refine ⟨E, h1, castD (underL' (A := A) G (M ++ [E] ++ R) T hT h2 (by simp)) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · rw [List.append_eq_append_iff] at hP + rcases hP with ⟨a', rfl, rfl⟩ | ⟨c', rfl, rfl⟩ + · by_cases ha : a' = [] + · subst ha + obtain ⟨E, h1, h2, hb⟩ := ihm (G ++ []) ([A] ++ Q1) R (by simp) (by simp) + refine ⟨E, castD (underL' (A := A) [] Q1 ([] ++ P2) hT h1 (by simp)) (by simp), h2, + fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihT [] a' P2 (by simp) ha + obtain ⟨F, h3, h4, hd⟩ := ihm G ([A] ++ Q1) R (by simp) (by simp) + refine ⟨under E F, + LDer0.underR (by simp) + (castD (underL' (A := A) [] Q1 (E :: P2) (castD h2 (by simp)) h3 (by simp)) + (by simp)), + castD (underL' (A := F) G R a' h1 h4 (by simp)) (by simp), fun p => ?_⟩ + have := hb p + have := hd p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ihm L (c' ++ [A] ++ Q1) R (by simp) (by simp) + refine ⟨E, castD (underL' (A := A) c' Q1 T hT h1 rfl) (by simp), h2, fun p => ?_⟩ + have := hb p + occBound + | @mulR G D A B _ _ ih1 ih2 => + intro L S R e hS + rcases split3 e.symm with ⟨M, rfl, rfl⟩ | ⟨M, rfl, rfl⟩ | + ⟨S1, S2, rfl, hS1, hS2, rfl, rfl⟩ + · obtain ⟨E, h1, h2, hb⟩ := ih1 L S M rfl hS + refine ⟨E, h1, castD (LDer0.mulR h2 ‹LDer0 D B›) (by simp), fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ih2 M S R rfl hS + refine ⟨E, h1, castD (LDer0.mulR ‹LDer0 G A› h2) (by simp), fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ih1 L S1 [] (by simp) hS1 + obtain ⟨F, h3, h4, hc⟩ := ih2 [] S2 R (by simp) hS2 + refine ⟨mul E F, LDer0.mulR h1 h3, + castD (mulL' (A := E) (B := F) L R + (LDer0.mulR (castD h2 (by simp) : LDer0 (L ++ [E]) A) + (castD h4 (by simp) : LDer0 (F :: R) B)) (by simp)) (by simp), fun p => ?_⟩ + have := hb p + have := hc p + occBound + | @mulL G D A B C _ ih => + intro L S R e hS + have e' : L ++ S ++ R = G ++ mul A B :: D := by rw [← e]; simp + rcases split_mid e' with ⟨M, rfl, rfl⟩ | ⟨M, rfl, rfl⟩ | ⟨P2, Q1, rfl, rfl, rfl⟩ + · obtain ⟨E, h1, h2, hb⟩ := ih L S (M ++ [A, B] ++ D) (by simp) hS + refine ⟨E, h1, castD (mulL' (A := A) (B := B) (L ++ [E] ++ M) D h2 (by simp)) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ih (G ++ [A, B] ++ M) S R (by simp) hS + refine ⟨E, h1, castD (mulL' (A := A) (B := B) G (M ++ [E] ++ R) h2 (by simp)) (by simp), + fun p => ?_⟩ + have := hb p + occBound + · obtain ⟨E, h1, h2, hb⟩ := ih L (P2 ++ [A, B] ++ Q1) R (by simp) (by simp) + refine ⟨E, castD (mulL' (A := A) (B := B) P2 Q1 h1 rfl) (by simp), h2, fun p => ?_⟩ + have := hb p + occBound + +end LInterp + +/-- Interpolation. If `Γ, Δ, Θ → C` is derivable and `Δ` is non-empty, there is a type `E` + such that `Δ → E` and `Γ, E, Θ → C` are derivable, and every primitive type occurs in + `E` at most as often as in `Δ` and at most as often as in the rest of the sequent. -/ +theorem LDer0.interpolation [DecidableEq P] {Γ Δ Θ : List (LType P)} {C : LType P} + (h : LDer0 (Γ ++ Δ ++ Θ) C) (hΔ : Δ ≠ []) : + ∃ E : LType P, LDer0 Δ E ∧ LDer0 (Γ ++ [E] ++ Θ) C ∧ + ∀ p : P, E.occ p ≤ occList p Δ ∧ E.occ p ≤ occList p Γ + occList p Θ + C.occ p := + LInterp.main h Γ Δ Θ rfl hΔ + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/LambekPentus.lean b/LeanPool/FormalLinguistics/LambekPentus.lean new file mode 100644 index 0000000000..35e664cd3f --- /dev/null +++ b/LeanPool/FormalLinguistics/LambekPentus.lean @@ -0,0 +1,569 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.LambekCut +public import LeanPool.FormalLinguistics.LambekInterpolation +public import LeanPool.FormalLinguistics.LambekFreeGroup +public import LeanPool.FormalLinguistics.LambekThin + +/-! + Pentus's theorem (1993): every Lambek grammar generates a context-free language, and + the resulting characterisation of Lambek languages (Chomsky's conjecture). + + The proof follows Pentus's argument as presented by Kanazawa (2018, Section 4): + thin sequents, interpolation, the free-group interpretation and Pentus's lemma about + free groups give a "binary reduction" of every derivable sequent whose types have + bounded size; the context-free grammar has the types of bounded size as nonterminals + and the derivable sequents with at most two antecedent types as rules. +-/ + +@[expose] public section + +namespace FormalLinguistics + +namespace LPentus + +/-! ### Primitive types of a type -/ + +/-- The list of primitive types occurring in a type (with repetitions). -/ +def prims {P : Type} : LType P → List P + | LType.prim p => [p] + | LType.over A B => prims A ++ prims B + | LType.under B A => prims B ++ prims A + | LType.mul A B => prims A ++ prims B + +theorem size_map {P Q : Type} (f : P → Q) (A : LType P) : (A.map f).size = A.size := by + induction A with + | prim p => rfl + | over A B ihA ihB => simp [LType.map, LType.size, ihA, ihB] + | under B A ihB ihA => simp [LType.map, LType.size, ihA, ihB] + | mul A B ihA ihB => simp [LType.map, LType.size, ihA, ihB] + +theorem prims_map {P Q : Type} (f : P → Q) (A : LType P) : + prims (A.map f) = (prims A).map f := by + induction A with + | prim p => rfl + | over A B ihA ihB => simp [LType.map, prims, ihA, ihB] + | under B A ihB ihA => simp [LType.map, prims, ihA, ihB] + | mul A B ihA ihB => simp [LType.map, prims, ihA, ihB] + +theorem size_pos {P : Type} (A : LType P) : 1 ≤ A.size := by + induction A with + | prim p => simp [LType.size] + | over A B ihA ihB => simp only [LType.size]; omega + | under B A ihB ihA => simp only [LType.size]; omega + | mul A B ihA ihB => simp only [LType.size]; omega + +theorem mem_prims_of_occ {P : Type} [DecidableEq P] (p : P) (A : LType P) : + A.occ p ≠ 0 → p ∈ prims A := by + induction A with + | prim q => + intro h + simp only [LType.occ] at h + by_cases hq : q = p + · subst hq; simp [prims] + · simp [hq] at h + | over A B ihA ihB => + intro h; simp only [LType.occ] at h; simp only [prims, List.mem_append] + by_cases hA : A.occ p = 0 + · exact Or.inr (ihB (by omega)) + · exact Or.inl (ihA hA) + | under B A ihB ihA => + intro h; simp only [LType.occ] at h; simp only [prims, List.mem_append] + by_cases hB : B.occ p = 0 + · exact Or.inr (ihA (by omega)) + · exact Or.inl (ihB hB) + | mul A B ihA ihB => + intro h; simp only [LType.occ] at h; simp only [prims, List.mem_append] + by_cases hA : A.occ p = 0 + · exact Or.inr (ihB (by omega)) + · exact Or.inl (ihA hA) + +theorem exists_of_occList {P : Type} [DecidableEq P] (p : P) (Δ : List (LType P)) : + occList p Δ ≠ 0 → ∃ X ∈ Δ, p ∈ prims X := by + induction Δ with + | nil => intro h; exact absurd rfl h + | cons A Δ ih => + intro h + rw [LInterp.occList_cons] at h + by_cases hA : A.occ p = 0 + · obtain ⟨X, hX, hp⟩ := ih (by omega) + exact ⟨X, List.mem_cons_of_mem _ hX, hp⟩ + · exact ⟨A, List.mem_cons_self, mem_prims_of_occ p A hA⟩ + +theorem occ_of_mem_prims {P : Type} [DecidableEq P] (p : P) (A : LType P) : + p ∈ prims A → A.occ p ≠ 0 := by + induction A with + | prim q => + intro h + simp [prims] at h + subst h; simp [LType.occ] + | over A B ihA ihB => + intro h; simp only [LType.occ]; simp only [prims, List.mem_append] at h + rcases h with h | h + · have := ihA h; omega + · have := ihB h; omega + | under B A ihB ihA => + intro h; simp only [LType.occ]; simp only [prims, List.mem_append] at h + rcases h with h | h + · have := ihB h; omega + · have := ihA h; omega + | mul A B ihA ihB => + intro h; simp only [LType.occ]; simp only [prims, List.mem_append] at h + rcases h with h | h + · have := ihA h; omega + · have := ihB h; omega + +/-- Primitives of an interpolant, transported along a renaming. -/ +theorem transfer {P Q : Type} [DecidableEq Q] (f : Q → P) {E : LType Q} {Δ : List (LType Q)} + (h : ∀ q, E.occ q ≤ occList q Δ) : + ∀ p ∈ prims (E.map f), ∃ X ∈ Δ.map (LType.map f), p ∈ prims X := by + intro p hp + rw [prims_map, List.mem_map] at hp + obtain ⟨q, hq, rfl⟩ := hp + have h1 := occ_of_mem_prims q E hq + have h2 : occList q Δ ≠ 0 := by have := h q; omega + obtain ⟨X, hX, hqX⟩ := exists_of_occList q Δ h2 + refine ⟨X.map f, List.mem_map_of_mem hX, ?_⟩ + rw [prims_map] + exact List.mem_map_of_mem hqX + +theorem split_last {α β : Type} (f : α → β) (z : β) : + ∀ (xs : List α) (l r : List β) (u v : β), xs.map f ++ [z] = l ++ u :: v :: r → + (∃ xs1 a b xs2, xs = xs1 ++ [a, b] ++ xs2 ∧ u = f a ∧ v = f b) ∨ + (∃ xs1 a, xs = xs1 ++ [a] ∧ u = f a ∧ v = z) := by + intro xs + induction xs with + | nil => + intro l r u v h + cases l with + | nil => simp at h + | cons x l => simp at h + | cons x xs ih => + intro l r u v h + cases l with + | nil => + simp at h + obtain ⟨rfl, h⟩ := h + cases xs with + | nil => + simp at h + right; exact ⟨[], x, by simp, rfl, h.1.symm⟩ + | cons y ys => + simp at h + left; exact ⟨[], x, y, ys, by simp, rfl, h.1.symm⟩ + | cons l0 l' => + simp at h + obtain ⟨_, h⟩ := h + rcases ih l' r u v h with ⟨xs1, a, b, xs2, rfl, hu, hv⟩ | ⟨xs1, a, rfl, hu, hv⟩ + · left; exact ⟨x :: xs1, a, b, xs2, by simp, hu, hv⟩ + · right; exact ⟨x :: xs1, a, by simp, hu, hv⟩ + +/-- **Binary reduction step** (Kanazawa 2018, Lemma 5). -/ +theorem step {P : Type} [DecidableEq P] (m : Nat) {Γ : List (LType P)} {C : LType P} + (h : LDer0 Γ C) (hlen : 3 ≤ Γ.length) (hΓ : ∀ X ∈ Γ, X.size ≤ m) (hC : C.size ≤ m) : + (∃ Γ₁ Γ₂ A B E, Γ = Γ₁ ++ [A, B] ++ Γ₂ ∧ E.size ≤ m ∧ LDer0 [A, B] E ∧ + LDer0 (Γ₁ ++ [E] ++ Γ₂) C ∧ ∀ p ∈ prims E, ∃ X ∈ [A, B], p ∈ prims X) ∨ + (∃ Γ₁ A E, Γ = Γ₁ ++ [A] ∧ Γ₁ ≠ [] ∧ E.size ≤ m ∧ LDer0 Γ₁ E ∧ LDer0 [E, A] C ∧ + ∀ p ∈ prims E, ∃ X ∈ Γ₁, p ∈ prims X) := by + obtain ⟨Γ', C', h', hΓ', hC', hthin⟩ := h.exists_thin + subst hΓ' hC' + have hred0 : FGWord.reduce (interpList Γ' ++ FGWord.inv C'.interp) = [] := + FGWord.reduce_append_inv_eq_nil h'.interp_sound + have hflat : (Γ'.map LType.interp ++ [FGWord.inv C'.interp]).flatten + = interpList Γ' ++ FGWord.inv C'.interp := by simp [interpList] + have hlen' : 2 ≤ (Γ'.map LType.interp ++ [FGWord.inv C'.interp]).length := by + simp at hlen ⊢; omega + obtain ⟨l, r, u, v, hus, hnorm⟩ := + FGWord.pentus_lemma _ hlen' (by rw [hflat]; exact hred0) + have hfac : ∀ x ∈ Γ'.map LType.interp ++ [FGWord.inv C'.interp], FGWord.norm x ≤ m := by + intro x hx + rw [List.mem_append, List.mem_map, List.mem_singleton] at hx + rcases hx with ⟨A', hA', rfl⟩ | rfl + · have h1 := LType.norm_interp_le A' + have h2 := hΓ (A'.map Prod.fst) (List.mem_map_of_mem hA') + rw [size_map] at h2 + omega + · rw [FGWord.norm_inv] + have h1 := LType.norm_interp_le C' + rw [size_map] at hC + omega + have hu := hfac u (by rw [hus]; simp) + have hv := hfac v (by rw [hus]; simp) + have huv : FGWord.norm (u ++ v) ≤ m := by + have := Nat.max_le.2 ⟨hu, hv⟩ + omega + rcases split_last LType.interp _ Γ' l r u v hus with + ⟨Γ₁', A', B', Γ₂', rfl, rfl, rfl⟩ | ⟨Γ₁', A', rfl, rfl, rfl⟩ + · obtain ⟨E', hE1, hE2, hocc⟩ := + LDer0.interpolation (Γ := Γ₁') (Δ := [A', B']) (Θ := Γ₂') h' (by simp) + have hocc1 : ∀ q, E'.occ q ≤ 1 := by + intro q + have h1 := hthin q + have h2 := hocc q + rw [LInterp.occList_append, LInterp.occList_append] at h1 + omega + have hsz : E'.size ≤ m := by + rw [← LType.norm_interp_eq_size E' hocc1, ← FGWord.norm_eq_of_reduce_eq hE1.interp_sound] + have e : interpList [A', B'] = A'.interp ++ B'.interp := by simp [interpList] + rw [e]; exact huv + left + refine ⟨Γ₁'.map (LType.map Prod.fst), Γ₂'.map (LType.map Prod.fst), A'.map Prod.fst, + B'.map Prod.fst, E'.map Prod.fst, by simp, by rw [size_map]; exact hsz, + by simpa using hE1.map Prod.fst, by simpa using hE2.map Prod.fst, ?_⟩ + have := transfer Prod.fst (fun q => (hocc q).1) + simpa using this + · have hne : Γ₁' ≠ [] := by + intro h0; subst h0; simp at hlen + obtain ⟨E', hE1, hE2, hocc⟩ := + LDer0.interpolation (Γ := []) (Δ := Γ₁') (Θ := [A']) (by simpa using h') hne + have hocc1 : ∀ q, E'.occ q ≤ 1 := by + intro q + have h1 := hthin q + have h2 := hocc q + rw [LInterp.occList_append] at h1 + rw [LInterp.occList_nil] at h2 + omega + have hsz : E'.size ≤ m := by + rw [← LType.norm_interp_eq_size E' hocc1, ← FGWord.norm_eq_of_reduce_eq hE1.interp_sound] + have e : interpList (Γ₁' ++ [A']) = interpList Γ₁' ++ A'.interp := by simp [interpList] + rw [e, List.append_assoc] at hred0 + rw [FGWord.norm_eq_of_reduce_append_eq_nil hred0] + exact huv + right + refine ⟨Γ₁'.map (LType.map Prod.fst), A'.map Prod.fst, E'.map Prod.fst, by simp, + by simpa using hne, by rw [size_map]; exact hsz, + by simpa using hE1.map Prod.fst, by simpa using hE2.map Prod.fst, ?_⟩ + exact transfer Prod.fst (fun q => (hocc q).1) + +/-! ### Finitely many candidate types -/ + +/-- All types built from the primitives `ps` with at most `n` nested connectives. -/ +def allTypes {P : Type} (ps : List P) : Nat → List (LType P) + | 0 => ps.map LType.prim + | n + 1 => allTypes ps n ++ (allTypes ps n).flatMap (fun X => (allTypes ps n).flatMap + (fun Y => [LType.over X Y, LType.under X Y, LType.mul X Y])) + +theorem allTypes_succ {P : Type} {ps : List P} {n : Nat} {A : LType P} + (h : A ∈ allTypes ps n) : A ∈ allTypes ps (n + 1) := by + simp only [allTypes, List.mem_append]; exact Or.inl h + +theorem allTypes_prim {P : Type} {ps : List P} {p : P} (hp : p ∈ ps) : + ∀ n, LType.prim p ∈ allTypes ps n := by + intro n + induction n with + | zero => simp only [allTypes]; exact List.mem_map_of_mem hp + | succ n ih => exact allTypes_succ ih + +theorem allTypes_bin {P : Type} {ps : List P} {n : Nat} {X Y : LType P} + (hX : X ∈ allTypes ps n) (hY : Y ∈ allTypes ps n) : + LType.over X Y ∈ allTypes ps (n + 1) ∧ LType.under X Y ∈ allTypes ps (n + 1) ∧ + LType.mul X Y ∈ allTypes ps (n + 1) := by + refine ⟨?_, ?_, ?_⟩ <;> + · simp only [allTypes, List.mem_append, List.mem_flatMap] + exact Or.inr ⟨X, hX, Y, hY, by simp⟩ + +theorem mem_allTypes {P : Type} (ps : List P) (A : LType P) : + (∀ p ∈ prims A, p ∈ ps) → ∀ n, A.size ≤ n + 1 → A ∈ allTypes ps n := by + induction A with + | prim p => + intro h n _ + exact allTypes_prim (h p (by simp [prims])) n + | over A B ihA ihB => + intro h n hn + have h1 := size_pos A; have h2 := size_pos B + simp only [LType.size] at hn + obtain ⟨k, rfl⟩ : ∃ k, n = k + 1 := ⟨n - 1, by omega⟩ + refine (allTypes_bin (ihA (fun p hp => h p (by simp [prims, hp])) k (by omega)) + (ihB (fun p hp => h p (by simp [prims, hp])) k (by omega))).1 + | under B A ihB ihA => + intro h n hn + have h1 := size_pos A; have h2 := size_pos B + simp only [LType.size] at hn + obtain ⟨k, rfl⟩ : ∃ k, n = k + 1 := ⟨n - 1, by omega⟩ + refine (allTypes_bin (ihB (fun p hp => h p (by simp [prims, hp])) k (by omega)) + (ihA (fun p hp => h p (by simp [prims, hp])) k (by omega))).2.1 + | mul A B ihA ihB => + intro h n hn + have h1 := size_pos A; have h2 := size_pos B + simp only [LType.size] at hn + obtain ⟨k, rfl⟩ : ∃ k, n = k + 1 := ⟨n - 1, by omega⟩ + refine (allTypes_bin (ihA (fun p hp => h p (by simp [prims, hp])) k (by omega)) + (ihB (fun p hp => h p (by simp [prims, hp])) k (by omega))).2.2 + +/-- The "good" types: bounded size, primitives among `ps`. -/ +def Good {P : Type} (ps : List P) (m : Nat) (A : LType P) : Prop := + A.size ≤ m ∧ ∀ p ∈ prims A, p ∈ ps + +theorem Good.mem {P : Type} {ps : List P} {m : Nat} {A : LType P} (h : Good ps m A) : + A ∈ allTypes ps m := + mem_allTypes ps A h.2 m (by have := h.1; omega) + +/-! ### The context-free grammar -/ + +/-- Admissible rules of the context-free grammar. -/ +def RuleOK {P T : Type} (G : LambekGrammar P T) (r : LType P × List (Symbol (LType P) T)) : + Prop := + (∃ a, r.2 = [Symbol.tm a] ∧ (a, r.1) ∈ G.lexicon) ∨ + (∃ A, r.2 = [Symbol.nt A] ∧ LDer0 [A] r.1) ∨ + (∃ A B, r.2 = [Symbol.nt A, Symbol.nt B] ∧ LDer0 [A, B] r.1) + +open Classical in +/-- The context-free grammar whose nonterminals are types: lexical rules, and the derivable + sequents with one or two antecedent types among the candidate types. -/ +noncomputable def pentusCFG {P T : Type} (G : LambekGrammar P T) (ps : List P) (m : Nat) : + CFG (LType P) T where + start := LType.prim G.distinguished + rules := (G.lexicon.map (fun (x : T × LType P) => (x.2, [Symbol.tm x.1])) ++ + (allTypes ps m).flatMap (fun A => (allTypes ps m).map (fun D => (D, [Symbol.nt A]))) ++ + (allTypes ps m).flatMap (fun A => (allTypes ps m).flatMap (fun B => + (allTypes ps m).map (fun D => (D, [Symbol.nt A, Symbol.nt B]))))).filter + (fun r => decide (RuleOK G r)) + +theorem rule_ok {P T : Type} {G : LambekGrammar P T} {ps : List P} {m : Nat} + {r : LType P × List (Symbol (LType P) T)} (h : r ∈ (pentusCFG G ps m).rules) : + RuleOK G r := by + simp only [pentusCFG, List.mem_filter, decide_eq_true_iff] at h + exact h.2 + +theorem lex_rule {P T : Type} {G : LambekGrammar P T} {ps : List P} {m : Nat} {a : T} + {A : LType P} (h : (a, A) ∈ G.lexicon) : (A, [Symbol.tm a]) ∈ (pentusCFG G ps m).rules := by + simp only [pentusCFG, List.mem_filter, decide_eq_true_iff] + refine ⟨?_, Or.inl ⟨a, rfl, h⟩⟩ + simp only [List.mem_append] + exact Or.inl (Or.inl (List.mem_map.2 ⟨(a, A), h, rfl⟩)) + +theorem un_rule {P T : Type} {G : LambekGrammar P T} {ps : List P} {m : Nat} + {A D : LType P} (hA : A ∈ allTypes ps m) (hD : D ∈ allTypes ps m) (h : LDer0 [A] D) : + (D, [Symbol.nt A]) ∈ (pentusCFG G ps m).rules := by + simp only [pentusCFG, List.mem_filter, decide_eq_true_iff] + refine ⟨?_, Or.inr (Or.inl ⟨A, rfl, h⟩)⟩ + simp only [List.mem_append, List.mem_flatMap, List.mem_map] + exact Or.inl (Or.inr ⟨A, hA, D, hD, rfl⟩) + +theorem bin_rule {P T : Type} {G : LambekGrammar P T} {ps : List P} {m : Nat} + {A B D : LType P} (hA : A ∈ allTypes ps m) (hB : B ∈ allTypes ps m) + (hD : D ∈ allTypes ps m) (h : LDer0 [A, B] D) : + (D, [Symbol.nt A, Symbol.nt B]) ∈ (pentusCFG G ps m).rules := by + simp only [pentusCFG, List.mem_filter, decide_eq_true_iff] + refine ⟨?_, Or.inr (Or.inr ⟨A, B, rfl, h⟩)⟩ + simp only [List.mem_append, List.mem_flatMap, List.mem_map] + exact Or.inr ⟨A, hA, B, hB, D, hD, rfl⟩ + +/-! ### Soundness of the grammar -/ + +theorem lexAssign_append {P T : Type} {G : LambekGrammar P T} {w1 w2 : List T} + {Γ1 Γ2 : List (LType P)} (h1 : G.LexAssign w1 Γ1) (h2 : G.LexAssign w2 Γ2) : + G.LexAssign (w1 ++ w2) (Γ1 ++ Γ2) := by + induction h1 with + | nil => simpa using h2 + | cons ha _ ih => exact LambekGrammar.LexAssign.cons ha ih + +/-- List-level companion of `CFG.YieldList` for the soundness proof. -/ +inductive SY {P T : Type} (G : LambekGrammar P T) : List (Symbol (LType P) T) → List T → Prop + | nil : SY G [] [] + | cons_tm {a : T} {rhs : List (Symbol (LType P) T)} {w : List T} : + SY G rhs w → SY G (Symbol.tm a :: rhs) (a :: w) + | cons_nt {D : LType P} {rhs : List (Symbol (LType P) T)} {w1 w2 : List T} : + (∃ Γ, G.LexAssign w1 Γ ∧ LDer0 Γ D) → SY G rhs w2 → SY G (Symbol.nt D :: rhs) (w1 ++ w2) + +mutual + theorem sound {P T : Type} {G : LambekGrammar P T} {ps : List P} {m : Nat} + {D : LType P} {w : List T} : + CFG.Yield (pentusCFG G ps m) D w → ∃ Γ, G.LexAssign w Γ ∧ LDer0 Γ D + | CFG.Yield.rule hr hyl_raw => by + have hyl := sound_list hyl_raw + rcases rule_ok hr with ⟨a, he, hlex⟩ | ⟨A, he, hd⟩ | ⟨A, B, he, hd⟩ + · simp only at he hlex + subst he + cases hyl with + | cons_tm hnil => + cases hnil + exact ⟨[D], LambekGrammar.LexAssign.cons hlex LambekGrammar.LexAssign.nil, + LDer0.identity D⟩ + · simp only at he hd + subst he + cases hyl with + | cons_nt h1 hnil => + cases hnil + obtain ⟨Γ, hl, hg⟩ := h1 + refine ⟨Γ, by simpa using hl, ?_⟩ + have := LDer0.cut (Γ := []) (Δ := []) hg (by simpa using hd) + simpa using this + · simp only at he hd + subst he + cases hyl with + | cons_nt h1 hrest => + cases hrest with + | cons_nt h2 hnil => + cases hnil + obtain ⟨Γ1, hl1, hg1⟩ := h1 + obtain ⟨Γ2, hl2, hg2⟩ := h2 + refine ⟨Γ1 ++ Γ2, by simpa using lexAssign_append hl1 hl2, ?_⟩ + have k1 := LDer0.cut (Γ := []) (Δ := [B]) hg1 (by simpa using hd) + have k2 := LDer0.cut (Γ := Γ1) (Δ := []) hg2 (by simpa using k1) + simpa using k2 + + theorem sound_list {P T : Type} {G : LambekGrammar P T} {ps : List P} {m : Nat} + {rhs : List (Symbol (LType P) T)} {w : List T} : + CFG.YieldList (pentusCFG G ps m) rhs w → SY G rhs w + | CFG.YieldList.nil => SY.nil + | CFG.YieldList.cons_tm h => SY.cons_tm (sound_list h) + | CFG.YieldList.cons_nt hy h => SY.cons_nt (sound hy) (sound_list h) +end + +/-! ### Completeness of the grammar -/ + +theorem complete {P T : Type} [DecidableEq P] (G : LambekGrammar P T) (ps : List P) (m : Nat) : + ∀ n (Γ : List (LType P)) (D : LType P), Γ.length ≤ n → (∀ X ∈ Γ, Good ps m X) → + Good ps m D → LDer0 Γ D → + CFG.Derives (pentusCFG G ps m) [Symbol.nt D] (Γ.map Symbol.nt) := by + intro n + induction n with + | zero => + intro Γ D hlen _ _ hder + have : Γ = [] := List.eq_nil_of_length_eq_zero (by omega) + exact absurd this hder.ne_nil + | succ n ih => + intro Γ D hlen hg hD hder + by_cases h3 : 3 ≤ Γ.length + · rcases step m hder h3 (fun X hX => (hg X hX).1) hD.1 with + ⟨Γ₁, Γ₂, A, B, E, rfl, hE, hAB, hrest, hpr⟩ | ⟨Γ₁, A, E, rfl, hne, hE, hΓ₁, hEA, hpr⟩ + · have hgA := hg A (by simp) + have hgB := hg B (by simp) + have hgE : Good ps m E := ⟨hE, fun p hp => by + obtain ⟨X, hX, hpX⟩ := hpr p hp + simp at hX + rcases hX with rfl | rfl + · exact hgA.2 p hpX + · exact hgB.2 p hpX⟩ + have h1 := ih (Γ₁ ++ [E] ++ Γ₂) D (by simp at hlen ⊢; omega) + (fun X hX => by + simp only [List.mem_append, List.mem_singleton] at hX + rcases hX with (hX | rfl) | hX + · exact hg X (by simp [hX]) + · exact hgE + · exact hg X (by simp [hX])) hD hrest + have h2 : CFG.Step (pentusCFG G ps m) + (Γ₁.map Symbol.nt ++ [Symbol.nt E] ++ Γ₂.map Symbol.nt) + (Γ₁.map Symbol.nt ++ [Symbol.nt A, Symbol.nt B] ++ Γ₂.map Symbol.nt) := + CFG.Step.mk _ _ _ _ (bin_rule hgA.mem hgB.mem hgE.mem hAB) + have h3 := CFG.Derives.tail (by simpa using h1) h2 + simpa using h3 + · have hgA := hg A (by simp) + have hgE : Good ps m E := ⟨hE, fun p hp => by + obtain ⟨X, hX, hpX⟩ := hpr p hp + exact (hg X (by simp [hX])).2 p hpX⟩ + have h1 := ih Γ₁ E (by simp at hlen ⊢; omega) + (fun X hX => hg X (by simp [hX])) hgE hΓ₁ + have h2 : CFG.Step (pentusCFG G ps m) [Symbol.nt D] [Symbol.nt E, Symbol.nt A] := by + simpa using CFG.Step.mk [] [] _ _ (bin_rule hgE.mem hgA.mem hD.mem hEA) + have h3 := CFG.Derives.append_right [Symbol.nt A] h1 + have h4 := CFG.Derives.trans (CFG.Derives.single h2) (by simpa using h3) + simpa using h4 + · rcases Γ with _ | ⟨A, _ | ⟨B, _ | ⟨X, rest⟩⟩⟩ + · exact absurd rfl hder.ne_nil + · have hgA := hg A (by simp) + have h2 : CFG.Step (pentusCFG G ps m) [Symbol.nt D] [Symbol.nt A] := by + simpa using CFG.Step.mk [] [] _ _ (un_rule hgA.mem hD.mem hder) + simpa using CFG.Derives.single h2 + · have hgA := hg A (by simp) + have hgB := hg B (by simp) + have h2 : CFG.Step (pentusCFG G ps m) [Symbol.nt D] [Symbol.nt A, Symbol.nt B] := by + simpa using CFG.Step.mk [] [] _ _ (bin_rule hgA.mem hgB.mem hD.mem hder) + simpa using CFG.Derives.single h2 + · simp at h3 + +theorem lex_derives {P T : Type} {G : LambekGrammar P T} {ps : List P} {m : Nat} + {w : List T} {Γ : List (LType P)} (h : G.LexAssign w Γ) : + CFG.Derives (pentusCFG G ps m) (Γ.map Symbol.nt) (w.map Symbol.tm) := by + induction h with + | nil => exact CFG.Derives.refl _ + | @cons a A w Γ ha _ ih => + have h1 : CFG.Step (pentusCFG G ps m) [Symbol.nt A] [Symbol.tm a] := by + simpa using CFG.Step.mk [] [] _ _ (lex_rule (ps := ps) (m := m) ha) + have := CFG.Derives.append (CFG.Derives.single h1) ih + simpa using this + +theorem lexAssign_mem {P T : Type} {G : LambekGrammar P T} {w : List T} + {Γ : List (LType P)} (h : G.LexAssign w Γ) : ∀ X ∈ Γ, ∃ a, (a, X) ∈ G.lexicon := by + induction h with + | nil => intro X hX; simp at hX + | @cons a A w Γ ha _ ih => + intro X hX + rcases List.mem_cons.1 hX with rfl | hX + · exact ⟨a, ha⟩ + · exact ih X hX + +theorem le_sum_of_mem {α : Type} (f : α → Nat) {l : List α} {x : α} (h : x ∈ l) : + f x ≤ (l.map f).sum := by + induction l with + | nil => simp at h + | cons y l ih => + rcases List.mem_cons.1 h with rfl | h + · simp + · have := ih h; simp; omega + +end LPentus + +/-- **Pentus's theorem.** Every Lambek grammar has a context-free grammar generating the + same language. -/ +theorem lambek_to_cfg {P T : Type} (G : LambekGrammar P T) : + ∃ G' : CFG (LType P) T, ∀ w, G'.Lang w ↔ G.Lang w := by + classical + let ps : List P := G.distinguished :: G.lexicon.flatMap (fun x => LPentus.prims x.2) + let m : Nat := (G.lexicon.map (fun x => x.2.size)).sum + 1 + have hlexgood : ∀ a A, (a, A) ∈ G.lexicon → LPentus.Good ps m A := by + intro a A h + refine ⟨?_, fun p hp => ?_⟩ + · have := LPentus.le_sum_of_mem (fun x : T × LType P => x.2.size) h + simp only at this + omega + · exact List.mem_cons_of_mem _ (List.mem_flatMap.2 ⟨(a, A), h, hp⟩) + have hsgood : LPentus.Good ps m (LType.prim G.distinguished) := + ⟨by simp [LType.size, m], fun p hp => by simp [LPentus.prims] at hp; simp [ps, hp]⟩ + refine ⟨LPentus.pentusCFG G ps m, fun w => ⟨fun h => ?_, fun h => ?_⟩⟩ + · obtain ⟨Γ, hl, hd⟩ := LPentus.sound (CFG.lang_iff_yield.1 h) + exact ⟨Γ, hl, LDer_iff_LDer0.2 hd⟩ + · obtain ⟨Γ, hl, hd⟩ := h + have hd0 := LDer_iff_LDer0.1 hd + have hg : ∀ X ∈ Γ, LPentus.Good ps m X := by + intro X hX + obtain ⟨a, ha⟩ := LPentus.lexAssign_mem hl X hX + exact hlexgood a X ha + have h1 := LPentus.complete G ps m Γ.length Γ _ (Nat.le_refl _) hg hsgood hd0 + exact CFG.Derives.trans h1 (LPentus.lex_derives hl) + +/-- A language is a Lambek language if it is generated by some finite Lambek grammar. -/ +def IsLambekLang {T : Type} (L : List T → Prop) : Prop := + ∃ (P : Type) (G : LambekGrammar P T), ∀ w, G.Lang w ↔ L w + +/-- **Chomsky–Pentus theorem.** A language is generated by a Lambek grammar if and only if + it is an ε-free context-free language. -/ +theorem chomsky_pentus {T : Type} [DecidableEq T] (L : List T → Prop) : + IsLambekLang L ↔ + ((∃ (N : Type) (_ : DecidableEq N) (G : CFG N T), ∀ w, G.Lang w ↔ L w) ∧ ¬ L []) := by + constructor + · rintro ⟨P, G, hG⟩ + obtain ⟨G', hG'⟩ := lambek_to_cfg G + refine ⟨⟨LType P, fun a b => Classical.propDecidable (a = b), G', fun w => (hG' w).trans (hG w)⟩, ?_⟩ + intro h0 + obtain ⟨Γ, hl, hd⟩ := (hG []).2 h0 + cases hl + exact (LDer_iff_LDer0.1 hd).ne_nil rfl + · rintro ⟨⟨N, inst, G, hG⟩, hne⟩ + refine ⟨_, (cfgToABG G).toLambek, fun w => ?_⟩ + rw [cfg_to_lambek_equiv, hG] + constructor + · exact fun h => h.1 + · intro h + refine ⟨h, ?_⟩ + rintro rfl + exact hne h + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/LambekThin.lean b/LeanPool/FormalLinguistics/LambekThin.lean new file mode 100644 index 0000000000..5fe26e1e74 --- /dev/null +++ b/LeanPool/FormalLinguistics/LambekThin.lean @@ -0,0 +1,190 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.LambekCore + +/-! + Thin sequents (Pentus 1993): every derivable sequent is the image, under a renaming of + primitive types, of a derivable sequent in which each primitive type occurs at most twice. +-/ + +@[expose] public section + +namespace FormalLinguistics + +variable {P : Type} + +namespace LThin + + +theorem occList_nil [DecidableEq P] (q : P) : occList q ([] : List (LType P)) = 0 := rfl + +theorem occList_cons [DecidableEq P] (q : P) (x : LType P) (a : List (LType P)) : + occList q (x :: a) = x.occ q + occList q a := by + simp [occList] + +theorem occList_append [DecidableEq P] (q : P) (a b : List (LType P)) : + occList q (a ++ b) = occList q a + occList q b := by + simp [occList, List.sum_append] + +theorem map_eq_over {Q : Type} {f : P → Q} {X : LType P} {A B : LType Q} + (h : X.map f = LType.over A B) : + ∃ A' B', X = LType.over A' B' ∧ A'.map f = A ∧ B'.map f = B := by + cases X with + | over a b => simp only [LType.map, LType.over.injEq] at h; exact ⟨a, b, rfl, h.1, h.2⟩ + | _ => simp [LType.map] at h + +theorem map_eq_under {Q : Type} {f : P → Q} {X : LType P} {A B : LType Q} + (h : X.map f = LType.under B A) : + ∃ B' A', X = LType.under B' A' ∧ B'.map f = B ∧ A'.map f = A := by + cases X with + | under b a => simp only [LType.map, LType.under.injEq] at h; exact ⟨b, a, rfl, h.1, h.2⟩ + | _ => simp [LType.map] at h + +theorem map_eq_mul {Q : Type} {f : P → Q} {X : LType P} {A B : LType Q} + (h : X.map f = LType.mul A B) : + ∃ A' B', X = LType.mul A' B' ∧ A'.map f = A ∧ B'.map f = B := by + cases X with + | mul a b => simp only [LType.map, LType.mul.injEq] at h; exact ⟨a, b, rfl, h.1, h.2⟩ + | _ => simp [LType.map] at h + +/-- Split a renamed antecedent `Ξ'` with `Ξ'.map f = Γ ++ [A] ++ Δ`. -/ +theorem split3 {Q : Type} {f : LType Q → LType P} {Ξ : List (LType Q)} + {Γ Δ : List (LType P)} {A : LType P} (h : Ξ.map f = Γ ++ [A] ++ Δ) : + ∃ Γ' A' Δ', Ξ = Γ' ++ [A'] ++ Δ' ∧ Γ'.map f = Γ ∧ f A' = A ∧ Δ'.map f = Δ := by + obtain ⟨L, Δ', rfl, hL, hΔ⟩ := List.map_eq_append_iff.mp h + obtain ⟨Γ', L2, rfl, hΓ, hL2⟩ := List.map_eq_append_iff.mp hL + obtain ⟨A', rfl, hA⟩ := List.map_eq_singleton_iff.mp hL2 + exact ⟨Γ', A', Δ', rfl, hΓ, hA, hΔ⟩ + +theorem split4 {Q : Type} {f : LType Q → LType P} {Ξ : List (LType Q)} + {Γ Δ : List (LType P)} {A B : LType P} (h : Ξ.map f = Γ ++ [A, B] ++ Δ) : + ∃ Γ' A' B' Δ', Ξ = Γ' ++ [A', B'] ++ Δ' ∧ Γ'.map f = Γ ∧ f A' = A ∧ f B' = B ∧ + Δ'.map f = Δ := by + obtain ⟨L, Δ', rfl, hL, hΔ⟩ := List.map_eq_append_iff.mp h + obtain ⟨Γ', L2, rfl, hΓ, hL2⟩ := List.map_eq_append_iff.mp hL + obtain ⟨A', L3, rfl, hA, hL3⟩ := List.map_eq_cons_iff.mp hL2 + obtain ⟨B', rfl, hB⟩ := List.map_eq_singleton_iff.mp hL3 + exact ⟨Γ', A', B', Δ', rfl, hΓ, hA, hB, hΔ⟩ + +/-- The strengthened statement with index ranges. -/ +theorem main [DecidableEq P] {Γ : List (LType P)} {C : LType P} (h : LDer0 Γ C) : + ∀ n : Nat, ∃ (m : Nat) (Γ' : List (LType (P × Nat))) (C' : LType (P × Nat)), + n ≤ m ∧ LDer0 Γ' C' ∧ + Γ'.map (LType.map Prod.fst) = Γ ∧ C'.map Prod.fst = C ∧ + (∀ q : P × Nat, occList q Γ' + C'.occ q ≤ 2) ∧ + (∀ q : P × Nat, (q.2 < n ∨ m ≤ q.2) → occList q Γ' + C'.occ q = 0) := by + induction h with + | ax p => + intro n + refine ⟨n + 1, [LType.prim (p, n)], LType.prim (p, n), by omega, LDer0.ax _, rfl, rfl, + ?_, ?_⟩ + · intro q + by_cases hq : (p, n) = q <;> simp [occList, LType.occ, hq] + · intro q hq + have hne : (p, n) ≠ q := by + rintro rfl; simp at hq; omega + simp [occList, LType.occ, hne] + | @overR Γ A B hne _ ih => + intro n + obtain ⟨m, Ξ', A', hnm, d', hΞ, hA, hb, hz⟩ := ih n + obtain ⟨Γ', L, rfl, hΓ, hL⟩ := List.map_eq_append_iff.mp hΞ + obtain ⟨B', rfl, hB⟩ := List.map_eq_singleton_iff.mp hL + refine ⟨m, Γ', LType.over A' B', hnm, LDer0.overR ?_ d', hΓ, + by simp [LType.map, hA, hB], ?_, ?_⟩ + · rintro rfl; exact hne (by simpa using hΓ.symm) + · intro q; have := hb q + simp only [occList_append, occList_cons, occList_nil, LType.occ] at this ⊢; omega + · intro q hq; have := hz q hq + simp only [occList_append, occList_cons, occList_nil, LType.occ] at this ⊢; omega + | @underR Γ A B hne _ ih => + intro n + obtain ⟨m, Ξ', A', hnm, d', hΞ, hA, hb, hz⟩ := ih n + obtain ⟨B', Γ', rfl, hB, hΓ⟩ := List.map_eq_cons_iff.mp hΞ + refine ⟨m, Γ', LType.under B' A', hnm, LDer0.underR ?_ d', hΓ, + by simp [LType.map, hA, hB], ?_, ?_⟩ + · rintro rfl; exact hne (by simpa using hΓ.symm) + · intro q; have := hb q + simp only [occList_cons, LType.occ] at this ⊢; omega + · intro q hq; have := hz q hq + simp only [occList_cons, LType.occ] at this ⊢; omega + | @overL Γ Δ Θ A B C _ _ ih1 ih2 => + intro n + obtain ⟨m1, Θ', B', hnm1, d1, hΘ, hB, hb1, hz1⟩ := ih1 n + obtain ⟨m2, Ξ', C', hm12, d2, hΞ, hC, hb2, hz2⟩ := ih2 m1 + obtain ⟨Γ', A', Δ', rfl, hΓ, hA, hΔ⟩ := split3 hΞ + refine ⟨m2, Γ' ++ [LType.over A' B'] ++ Θ' ++ Δ', C', by omega, LDer0.overL d1 d2, + by simp [hΓ, hΔ, hΘ, LType.map, hA, hB], hC, ?_, ?_⟩ + · intro q + have e1 := hb1 q; have e2 := hb2 q + by_cases hq : q.2 < m1 + · have e3 := hz2 q (Or.inl hq) + simp only [occList_append, occList_cons, occList_nil, LType.occ] at e1 e2 e3 ⊢; omega + · have e3 := hz1 q (Or.inr (by omega)) + simp only [occList_append, occList_cons, occList_nil, LType.occ] at e1 e2 e3 ⊢; omega + · intro q hq + have e1 := hz1 q (by omega); have e2 := hz2 q (by omega) + simp only [occList_append, occList_cons, occList_nil, LType.occ] at e1 e2 ⊢; omega + | @underL Γ Δ Θ A B C _ _ ih1 ih2 => + intro n + obtain ⟨m1, Θ', B', hnm1, d1, hΘ, hB, hb1, hz1⟩ := ih1 n + obtain ⟨m2, Ξ', C', hm12, d2, hΞ, hC, hb2, hz2⟩ := ih2 m1 + obtain ⟨Γ', A', Δ', rfl, hΓ, hA, hΔ⟩ := split3 hΞ + refine ⟨m2, Γ' ++ Θ' ++ [LType.under B' A'] ++ Δ', C', by omega, LDer0.underL d1 d2, + by simp [hΓ, hΔ, hΘ, LType.map, hA, hB], hC, ?_, ?_⟩ + · intro q + have e1 := hb1 q; have e2 := hb2 q + by_cases hq : q.2 < m1 + · have e3 := hz2 q (Or.inl hq) + simp only [occList_append, occList_cons, occList_nil, LType.occ] at e1 e2 e3 ⊢; omega + · have e3 := hz1 q (Or.inr (by omega)) + simp only [occList_append, occList_cons, occList_nil, LType.occ] at e1 e2 e3 ⊢; omega + · intro q hq + have e1 := hz1 q (by omega); have e2 := hz2 q (by omega) + simp only [occList_append, occList_cons, occList_nil, LType.occ] at e1 e2 ⊢; omega + | @mulR Γ Δ A B _ _ ih1 ih2 => + intro n + obtain ⟨m1, Γ', A', hnm1, d1, hΓ, hA, hb1, hz1⟩ := ih1 n + obtain ⟨m2, Δ', B', hm12, d2, hΔ, hB, hb2, hz2⟩ := ih2 m1 + refine ⟨m2, Γ' ++ Δ', LType.mul A' B', by omega, LDer0.mulR d1 d2, + by simp [hΓ, hΔ], by simp [LType.map, hA, hB], ?_, ?_⟩ + · intro q + have e1 := hb1 q; have e2 := hb2 q + by_cases hq : q.2 < m1 + · have e3 := hz2 q (Or.inl hq) + simp only [occList_append, LType.occ] at e1 e2 e3 ⊢; omega + · have e3 := hz1 q (Or.inr (by omega)) + simp only [occList_append, LType.occ] at e1 e2 e3 ⊢; omega + · intro q hq + have e1 := hz1 q (by omega); have e2 := hz2 q (by omega) + simp only [occList_append, LType.occ] at e1 e2 ⊢; omega + | @mulL Γ Δ A B C _ ih => + intro n + obtain ⟨m, Ξ', C', hnm, d', hΞ, hC, hb, hz⟩ := ih n + obtain ⟨Γ', A', B', Δ', rfl, hΓ, hA, hB, hΔ⟩ := split4 hΞ + refine ⟨m, Γ' ++ [LType.mul A' B'] ++ Δ', C', hnm, LDer0.mulL d', + by simp [hΓ, hΔ, LType.map, hA, hB], hC, ?_, ?_⟩ + · intro q; have := hb q + simp only [occList_append, occList_cons, occList_nil, LType.occ] at this ⊢; omega + · intro q hq; have := hz q hq + simp only [occList_append, occList_cons, occList_nil, LType.occ] at this ⊢; omega + +end LThin + +/-- Every derivable sequent `Γ → C` over primitive types `P` is obtained, by forgetting the + numerical index of each primitive type, from a derivable sequent over `P × Nat` in which + every primitive type occurs at most twice in total. -/ +theorem LDer0.exists_thin [DecidableEq P] {Γ : List (LType P)} {C : LType P} (h : LDer0 Γ C) : + ∃ (Γ' : List (LType (P × Nat))) (C' : LType (P × Nat)), + LDer0 Γ' C' ∧ + Γ'.map (LType.map Prod.fst) = Γ ∧ C'.map Prod.fst = C ∧ + ∀ q : P × Nat, occList q Γ' + C'.occ q ≤ 2 := by + obtain ⟨_, Γ', C', _, d, hΓ, hC, hb, _⟩ := LThin.main h 0 + exact ⟨Γ', C', d, hΓ, hC, hb⟩ + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/MCFG.lean b/LeanPool/FormalLinguistics/MCFG.lean new file mode 100644 index 0000000000..ab4b0a2d26 --- /dev/null +++ b/LeanPool/FormalLinguistics/MCFG.lean @@ -0,0 +1,178 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import Init + +/-! + Multiple Context-Free Grammars / Linear Context-Free Rewriting Systems + (Seki, Matsumura, Fujii & Kasami 1991; Vijay-Shanker, Weir & Joshi 1987) + + A linear, non-erasing MCFG (LCFRS) over nonterminals `N` and terminals `T` + assigns each nonterminal `A : N` a positive dimension `dim A ≥ 1` (with `dim start = 1`), + and each rule builds a `dim A`-tuple of strings linearly and non-erasingly from + the string tuples of its RHS nonterminals plus literal terminals. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- An atom inside an MCFG yield component: either a literal terminal or + a variable `(argIdx, compIdx)` referencing component `compIdx` of RHS nonterminal `argIdx`. -/ +inductive MCFGAtom (T : Type) where + | tm : T → MCFGAtom T + | var : Nat → Nat → MCFGAtom T + deriving DecidableEq, Repr + +/-- An MCFG production rule: + `lhs` derives `rhs` via the tuple of component templates `yield`. -/ +structure MCFGRule (N T : Type) where + /-- Nonterminal produced by the rule. -/ + lhs : N + /-- Ordered argument nonterminals whose yields feed the rule. -/ + rhs : List N + /-- Output component templates, referring to argument components by position. -/ + yield : List (List (MCFGAtom T)) + deriving DecidableEq, Repr + +namespace MCFGRule + +variable {N T : Type} + +/-- All variable occurrences `(argIdx, compIdx)` appearing across all components of `r.yield`. -/ +def varOccurrences (r : MCFGRule N T) : List (Nat × Nat) := + r.yield.flatMap fun comp => + comp.filterMap fun + | MCFGAtom.tm _ => none + | MCFGAtom.var i j => some (i, j) + +/-- Expected list of all input variable coordinates `(i, j)` for `r.rhs` under `dim`. -/ +def expectedVars (dim : N → Nat) (rhs : List N) : List (Nat × Nat) := + (List.range rhs.length).flatMap fun i => + match rhs[i]? with + | none => [] + | some B => (List.range (dim B)).map fun j => (i, j) + +/-- A rule is **linear** if no variable coordinate `(i, j)` appears more than once. -/ +def isLinear (r : MCFGRule N T) : Prop := + r.varOccurrences.Nodup + +/-- A rule is **non-erasing** (and well-scoped) if every input coordinate `(i, j)` + with `i < r.rhs.length` and `j < dim (r.rhs[i])` appears in `r.yield`, and vice versa. -/ +def isNonErasing (dim : N → Nat) (r : MCFGRule N T) : Prop := + ∀ i j, (i, j) ∈ r.varOccurrences ↔ + ∃ B, r.rhs[i]? = some B ∧ j < dim B + +/-- Full well-formedness of an LCFRS / linear non-erasing MCFG rule: + correct output arity, linearity, and non-erasing variable bijection. -/ +def WellFormed (dim : N → Nat) (r : MCFGRule N T) : Prop := + r.yield.length = dim r.lhs ∧ r.isLinear ∧ r.isNonErasing dim + +end MCFGRule + +/-- A finite Linear Non-Erasing Multiple Context-Free Grammar (LCFRS / MCFG). -/ +structure MCFG (N T : Type) where + /-- Arity-one start nonterminal. -/ + start : N + /-- Number of string components yielded by each nonterminal. -/ + dim : N → Nat + dim_pos : ∀ A, 1 ≤ dim A + dim_start : dim start = 1 + /-- List of linear, non-erasing productions. -/ + rules : List (MCFGRule N T) + rules_wf : ∀ r, r ∈ rules → r.WellFormed dim + +namespace MCFG + +variable {N T : Type} + +/-- Evaluate a single component template `comp` given the list of RHS string tuples `args`. -/ +def evalComp (args : List (List (List T))) : List (MCFGAtom T) → List T + | [] => [] + | MCFGAtom.tm a :: rest => a :: evalComp args rest + | MCFGAtom.var i j :: rest => + let piece := + match args[i]? with + | some tup => + match tup[j]? with + | some s => s + | none => [] + | none => [] + piece ++ evalComp args rest + +/-- Evaluate all output components of an MCFG rule on `args`. -/ +def evalYield (args : List (List (List T))) (yield : List (List (MCFGAtom T))) : List (List T) := + yield.map (evalComp args) + +theorem evalComp_append (args : List (List (List T))) (c1 c2 : List (MCFGAtom T)) : + evalComp args (c1 ++ c2) = evalComp args c1 ++ evalComp args c2 := by + induction c1 with + | nil => simp [evalComp] + | cons a t ih => + cases a with + | tm x => simp [evalComp, ih] + | var i j => simp [evalComp, ih, List.append_assoc] + +theorem evalYield_length (args : List (List (List T))) (yield : List (List (MCFGAtom T))) : + (evalYield args yield).length = yield.length := by + simp [evalYield] + +/- Structural tuple derivations for an MCFG (mutually inductive for single nonterminals and RHS lists). -/ +mutual + /-- A derivation of a tuple of words from one nonterminal. -/ + inductive Yield (G : MCFG N T) : N → List (List T) → Prop where + | rule {r : MCFGRule N T} {args : List (List (List T))} : + r ∈ G.rules → + YieldList G r.rhs args → + Yield G r.lhs (evalYield args r.yield) + + /-- Simultaneous derivations of the tuples for a rule’s argument nonterminals. -/ + inductive YieldList (G : MCFG N T) : List N → List (List (List T)) → Prop where + | nil : YieldList G [] [] + | cons {B : N} {Bs : List N} {tup : List (List T)} {tups : List (List (List T))} : + Yield G B tup → + YieldList G Bs tups → + YieldList G (B :: Bs) (tup :: tups) +end + +/-- Every tuple yielded by nonterminal `A` has length `G.dim A`. -/ +theorem Yield.length_eq {G : MCFG N T} {A : N} {tup : List (List T)} + (h : Yield G A tup) : tup.length = G.dim A := by + cases h with + | rule hr _ => + rw [evalYield_length] + exact (G.rules_wf _ hr).1 + +/-- The string language generated by an MCFG (`start` has dimension 1). -/ +def Lang (G : MCFG N T) (w : List T) : Prop := + Yield G G.start [w] + +theorem YieldList.length_eq {G : MCFG N T} {Bs : List N} {args : List (List (List T))} : + YieldList G Bs args → args.length = Bs.length + | YieldList.nil => rfl + | YieldList.cons _ rest => by simp [YieldList.length_eq rest] + +theorem YieldList.getElem?_some {G : MCFG N T} {Bs : List N} {args : List (List (List T))} : + YieldList G Bs args → + ∀ (i : Nat) (B : N), Bs[i]? = some B → ∃ tup, args[i]? = some tup ∧ Yield G B tup + | YieldList.nil, _, _, h => by simp at h + | YieldList.cons hy hrest, 0, B, h => by + simp at h; subst h + exact ⟨_, rfl, hy⟩ + | YieldList.cons _ hrest, i + 1, B, h => + YieldList.getElem?_some hrest i B (by simpa using h) + +theorem YieldList.append {G : MCFG N T} {Bs1 Bs2 : List N} + {args1 args2 : List (List (List T))} : + YieldList G Bs1 args1 → YieldList G Bs2 args2 → + YieldList G (Bs1 ++ Bs2) (args1 ++ args2) + | YieldList.nil, h2 => by simpa using h2 + | YieldList.cons hy h1, h2 => YieldList.cons hy (YieldList.append h1 h2) + +end MCFG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/MCFGtoMG.lean b/LeanPool/FormalLinguistics/MCFGtoMG.lean new file mode 100644 index 0000000000..cf3b5b6295 --- /dev/null +++ b/LeanPool/FormalLinguistics/MCFGtoMG.lean @@ -0,0 +1,1682 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.MG +public import LeanPool.FormalLinguistics.BinMCFG + +/-! + Harkema (2001) / Michaelis (2001) — Direction 2: `MCFG → MG` + + Every finite Linear Non-Erasing Multiple Context-Free Grammar (LCFRS / MCFG) + has a weakly equivalent chain-based Minimalist Grammar (Stabler & Keenan 2003). + + The architecture follows Michaelis (2001), Sect. 4: three families of licensees + (one for the components being assembled, one for each of the two arguments), with + every mover carrying a single licensee so that it moves exactly once. The details + are adapted to the chain-based setting. + + Architecture: + 1. First binarize any arbitrary-rank LCFRS `G` into a rank-≤-2 LCFRS `G' = BinMCFG.binarizeMCFG G`. + 2. Compile any rank-≤-2 LCFRS `G` into a Minimalist Grammar `binMCFGToMG G` using a + 3-bank mover architecture (`Bank.L`, `Bank.R`, `Bank.O`) where every mover carries + a single licensee feature `[licensee (bank, idx)]` (so `Move2` never fires): + • Each MCFG nonterminal `A` of dimension `d` is realized on two target banks + `Side.L` and `Side.R`: + `⟨false, ⟨ε, [cat (nt A side)]⟩, {(side, j) ↦ tup[j] | 0 ≤ j < d}⟩`. + • Each rule `(r, rid)` loads its 0, 1, or 2 RHS tuples into disjoint banks `L` and `R`, + builds output components `k = 0 .. dim(lhs)-1` by scanning `r.yield[k]` in reverse + (left-prepending via `Move1` for variables and `Merge2` for terminal literals) and + parking each finished component into bank `O` via `Merge3`, then copies bank `O` + to target bank `side ∈ {L, R}` (`Move1` + `Merge3`). + • A top-level start head selects `(nt G.start L)` and lands `(L, 0)` via `Move1`. + 3. Prove Completeness (`MCFG.Yield → MG.Derives`) and Soundness (`MG.Derives → MGInv`) + via an exact finite-map mover invariant `ExactMap`, then compose with `BinMCFG`. +-/ + +@[expose] public section + +namespace FormalLinguistics +namespace MCFGtoMG + +variable {N T : Type} + +/-! ### Part 1: Types, Indexing, and 3-Bank Lexicon Construction -/ + +/-- Three disjoint mover banks: left RHS input (`L`), right RHS input (`R`), + and output accumulator (`O`). -/ +inductive Bank where + | L + | R + | O + deriving DecidableEq, Repr + +/-- Target input bank for a derived nonterminal tuple. -/ +inductive Side where + | L + | R + deriving DecidableEq, Repr + +/-- Assign a child in a binary production to the corresponding storage bank. -/ +def Side.toBank : Side → Bank + | Side.L => Bank.L + | Side.R => Bank.R + +theorem Side.toBank_ne_O (s : Side) : s.toBank ≠ Bank.O := by + cases s <;> decide + +/-- Movement feature keys: `(bank, componentIndex)`. -/ +abbrev MGLic := Bank × Nat + +/-- Disjoint base syntactic categories for the compiled Minimalist Grammar. -/ +inductive MGBase (N T : Type) where + | start : MGBase N T + | nt (A : N) (s : Side) : MGBase N T + | lit (a : T) : MGBase N T + | stage (rid : Nat) (k : Nat) : MGBase N T + | built (rid : Nat) (k : Nat) : MGBase N T + | copyStage (rid : Nat) (s : Side) (k : Nat) : MGBase N T + | copied (rid : Nat) (s : Side) (k : Nat) : MGBase N T + deriving DecidableEq, Repr + +/-- Index list elements starting at `k`, yielding `(idx, elem)` pairs. -/ +def indexFrom {α : Type} (k : Nat) : List α → List (Nat × α) + | [] => [] + | a :: t => (k, a) :: indexFrom (k + 1) t + +theorem mem_indexFrom_iff {α : Type} (L : List α) (k idx : Nat) (x : α) : + (idx, x) ∈ indexFrom k L ↔ k ≤ idx ∧ L[idx - k]? = some x := by + induction L generalizing k with + | nil => simp [indexFrom] + | cons a t ih => + simp only [indexFrom, List.mem_cons, Prod.mk.injEq, ih (k + 1)] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨hle, hget⟩) + · exact ⟨Nat.le_refl _, by simp⟩ + · refine ⟨by omega, ?_⟩ + have hpos : idx - k = (idx - (k + 1)) + 1 := by omega + rw [hpos] + simpa using hget + · rintro ⟨hle, hget⟩ + by_cases heq : idx = k + · subst heq + simp at hget + left; exact ⟨rfl, hget.symm⟩ + · right + have hpos : idx - k = (idx - (k + 1)) + 1 := by omega + rw [hpos] at hget + exact ⟨by omega, by simpa using hget⟩ + +theorem mem_indexFrom_zero_iff {α : Type} (L : List α) (idx : Nat) (x : α) : + (idx, x) ∈ indexFrom 0 L ↔ L[idx]? = some x := by + rw [mem_indexFrom_iff] + simp + +/-- Translate an MCFG yield atom into an MG feature that prepends its contribution on the left: + • `tm a` ↦ `=lit(a)` (left-prepends `[a]` via `Merge2`) + • `var 0 j` ↦ `+(L, j)` (left-prepends `x_j` via `Move1`) + • `var 1 j` ↦ `+(R, j)` (left-prepends `y_j` via `Move1`). -/ +def atomToFeat : MCFGAtom T → MGFeature (MGBase N T) MGLic + | MCFGAtom.tm a => MGFeature.sel (MGBase.lit a) + | MCFGAtom.var 0 j => MGFeature.licensor (Bank.L, j) + | MCFGAtom.var _ j => MGFeature.licensor (Bank.R, j) + +/-- Collect all terminals occurring in the yield templates of `G`. -/ +def allTerminals (G : MCFG N T) : List T := + G.rules.flatMap fun r => + r.yield.flatMap fun comp => + comp.filterMap fun + | MCFGAtom.tm a => some a + | MCFGAtom.var _ _ => none + +/-- Emit all lexical entries for a single rank-≤-2 rule `(rid, r)`. -/ +def ruleLexicon (G : MCFG N T) (rid : Nat) (r : MCFGRule N T) : + List (List T × List (MGFeature (MGBase N T) MGLic)) := + let initLex : List (List T × List (MGFeature (MGBase N T) MGLic)) := + match r.rhs with + | [] => [([], [MGFeature.cat (MGBase.stage rid 0)])] + | [B] => [([], [MGFeature.sel (MGBase.nt B Side.L), MGFeature.cat (MGBase.stage rid 0)])] + | [B, C] => [([], [MGFeature.sel (MGBase.nt B Side.L), MGFeature.sel (MGBase.nt C Side.R), + MGFeature.cat (MGBase.stage rid 0)])] + | _ => [] + let buildLex : List (List T × List (MGFeature (MGBase N T) MGLic)) := + (indexFrom 0 r.yield).flatMap fun (k, comp) => + [ ([], MGFeature.sel (MGBase.stage rid k) :: + comp.reverse.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]), + ([], [MGFeature.sel (MGBase.built rid k), MGFeature.cat (MGBase.stage rid (k + 1))]) ] + let copyLex : List (List T × List (MGFeature (MGBase N T) MGLic)) := + [Side.L, Side.R].flatMap fun side => + ([], [MGFeature.sel (MGBase.stage rid r.yield.length), + MGFeature.cat (MGBase.copyStage rid side 0)]) :: + (List.range (G.dim r.lhs)).flatMap fun k => + let nextCat := + if k + 1 < G.dim r.lhs then MGBase.copyStage rid side (k + 1) + else MGBase.nt r.lhs side + [ ([], [MGFeature.sel (MGBase.copyStage rid side k), + MGFeature.licensor (Bank.O, k), + MGFeature.cat (MGBase.copied rid side k), + MGFeature.licensee (side.toBank, k)]), + ([], [MGFeature.sel (MGBase.copied rid side k), MGFeature.cat nextCat]) ] + initLex ++ buildLex ++ copyLex + +/-- Full lexicon of the compiled Minimalist Grammar for a rank-≤-2 MCFG `G`. -/ +def buildLexicon (G : MCFG N T) : List (List T × List (MGFeature (MGBase N T) MGLic)) := + let startLex : List T × List (MGFeature (MGBase N T) MGLic) := + ([], [MGFeature.sel (MGBase.nt G.start Side.L), + MGFeature.licensor (Bank.L, 0), + MGFeature.cat MGBase.start]) + let litLex : List (List T × List (MGFeature (MGBase N T) MGLic)) := + (allTerminals G).map fun a => ([a], [MGFeature.cat (MGBase.lit a)]) + let rulesLex : List (List T × List (MGFeature (MGBase N T) MGLic)) := + (indexFrom 0 G.rules).flatMap fun (rid, r) => ruleLexicon G rid r + startLex :: (litLex ++ rulesLex) + +theorem buildLexicon_nonempty (G : MCFG N T) : + ∀ entry, entry ∈ buildLexicon G → entry.2 ≠ [] := by + intro entry hentry + unfold buildLexicon at hentry + simp only [List.mem_cons, List.mem_append, List.mem_map, List.mem_flatMap] at hentry + rcases hentry with rfl | ⟨a, _, rfl⟩ | ⟨⟨rid, r⟩, _, hrl⟩ + · simp + · simp + · unfold ruleLexicon at hrl + simp only [List.mem_append] at hrl + rcases hrl with (hinit | hbuild) | hcopy + · cases hrhs : r.rhs with + | nil => simp [hrhs] at hinit; subst hinit; simp + | cons B rest => + cases rest with + | nil => simp [hrhs] at hinit; subst hinit; simp + | cons C rest' => + cases rest' with + | nil => simp [hrhs] at hinit; subst hinit; simp + | cons _ _ => simp [hrhs] at hinit + · simp only [List.mem_flatMap, List.mem_cons, List.not_mem_nil, or_false] at hbuild + obtain ⟨⟨k, comp⟩, _, h1 | h2⟩ := hbuild <;> (subst entry; simp) + · simp only [List.mem_flatMap, List.mem_cons] at hcopy + obtain ⟨side, _, hbr | hcp⟩ := hcopy + · subst hbr; simp + · simp only [List.not_mem_nil, or_false] at hcp + obtain ⟨k, _, h1 | h2⟩ := hcp <;> (subst entry; simp) + +/-- The Minimalist Grammar compiled from a rank-≤-2 MCFG `G`. -/ +def binMCFGToMG (G : MCFG N T) : MG (MGBase N T) MGLic T where + start := MGBase.start + lexicon := buildLexicon G + lex_nonempty := buildLexicon_nonempty G + +/-! ### Part 2: ExactMap Mover Invariant & Algebra -/ + +/-- Exact finite-map invariant for single-feature movers: + `ms` satisfies SMC, every chain in `ms` is `⟨val k, [licensee k]⟩` for some `k` in `dom`, + and every `k` in `dom` is present in `ms` with value `val k`. -/ +def ExactMap (ms : List (MGChain (MGBase N T) MGLic T)) + (dom : MGLic → Prop) (val : MGLic → List T) : Prop := + SMC ms ∧ + (∀ c, c ∈ ms → ∃ k, dom k ∧ c = ⟨val k, [MGFeature.licensee k]⟩) ∧ + (∀ k, dom k → ⟨val k, [MGFeature.licensee k]⟩ ∈ ms) + +theorem exactMap_nil (val : MGLic → List T) : + ExactMap (N := N) [] (fun _ => False) val := by + refine ⟨⟨by intro c hc; simp at hc, List.nodup_nil⟩, ?_, ?_⟩ + · intro c hc; simp at hc + · intro k hk; exact False.elim hk + +theorem exactMap_ext {ms : List (MGChain (MGBase N T) MGLic T)} + {dom1 dom2 : MGLic → Prop} {val1 val2 : MGLic → List T} + (h : ExactMap ms dom1 val1) + (hdom : ∀ k, dom1 k ↔ dom2 k) + (hval : ∀ k, dom1 k → val1 k = val2 k) : + ExactMap ms dom2 val2 := by + obtain ⟨hsmc, hf, hb⟩ := h + refine ⟨hsmc, ?_, ?_⟩ + · intro c hc + obtain ⟨k, hk, rfl⟩ := hf c hc + exact ⟨k, (hdom k).mp hk, by rw [hval k hk]⟩ + · intro k hk2 + have hk1 := (hdom k).mpr hk2 + rw [← hval k hk1] + exact hb k hk1 + +theorem exactMap_empty_eq_nil {ms : List (MGChain (MGBase N T) MGLic T)} + {dom : MGLic → Prop} {val : MGLic → List T} + (h : ExactMap ms dom val) (hempty : ∀ k, ¬dom k) : ms = [] := by + cases ms with + | nil => rfl + | cons c t => + obtain ⟨k, hk, _⟩ := h.2.1 c (List.mem_cons_self ..) + exact False.elim (hempty k hk) + +theorem exactMap_disjoint_append {ms1 ms2 : List (MGChain (MGBase N T) MGLic T)} + {dom1 dom2 : MGLic → Prop} {val : MGLic → List T} + (h1 : ExactMap ms1 dom1 val) (h2 : ExactMap ms2 dom2 val) + (hdisj : ∀ k, dom1 k → ¬dom2 k) : + ExactMap (ms1 ++ ms2) (fun k => dom1 k ∨ dom2 k) val := by + obtain ⟨hsmc1, hf1, hb1⟩ := h1 + obtain ⟨hsmc2, hf2, hb2⟩ := h2 + have hsmc : SMC (ms1 ++ ms2) := by + refine ⟨?_, ?_⟩ + · intro c hc + rcases List.mem_append.mp hc with hm1 | hm2 + · exact hsmc1.1 c hm1 + · exact hsmc2.1 c hm2 + · rw [List.filterMap_append, List.nodup_append] + refine ⟨hsmc1.2, hsmc2.2, ?_⟩ + intro k1 hk1 k2 hk2 heq + subst heq + obtain ⟨c1, hc1, hl1⟩ := List.mem_filterMap.mp hk1 + obtain ⟨c2, hc2, hl2⟩ := List.mem_filterMap.mp hk2 + obtain ⟨j1, hj1, rfl⟩ := hf1 c1 hc1 + obtain ⟨j2, hj2, rfl⟩ := hf2 c2 hc2 + simp [MGChain.headLic] at hl1 hl2 + rw [← hl1] at hl2 + exact hdisj j1 hj1 (hl2 ▸ hj2) + refine ⟨hsmc, ?_, ?_⟩ + · intro c hc + rcases List.mem_append.mp hc with hm1 | hm2 + · obtain ⟨k, hk, rfl⟩ := hf1 c hm1; exact ⟨k, Or.inl hk, rfl⟩ + · obtain ⟨k, hk, rfl⟩ := hf2 c hm2; exact ⟨k, Or.inr hk, rfl⟩ + · intro k hk + rcases hk with hk1 | hk2 + · exact List.mem_append_left _ (hb1 k hk1) + · exact List.mem_append_right _ (hb2 k hk2) + +theorem exactMap_cons_fresh {ms : List (MGChain (MGBase N T) MGLic T)} + {dom : MGLic → Prop} {val : MGLic → List T} + {k0 : MGLic} {u : List T} + (h : ExactMap ms dom val) (hfresh : ¬dom k0) (hval0 : val k0 = u) : + ExactMap (⟨u, [MGFeature.licensee k0]⟩ :: ms) (fun k => k = k0 ∨ dom k) val := by + obtain ⟨hsmc, hf, hb⟩ := h + have hsmc' : SMC (⟨u, [MGFeature.licensee k0]⟩ :: ms) := by + refine ⟨?_, ?_⟩ + · intro c hc + rcases List.mem_cons.mp hc with rfl | hm + · exact ⟨k0, [], rfl⟩ + · exact hsmc.1 c hm + · simp only [List.filterMap_cons, MGChain.headLic, List.nodup_cons] + refine ⟨?_, hsmc.2⟩ + intro hmem + obtain ⟨c, hc, hl⟩ := List.mem_filterMap.mp hmem + obtain ⟨k, hk, rfl⟩ := hf c hc + simp [MGChain.headLic] at hl + subst hl + exact hfresh hk + refine ⟨hsmc', ?_, ?_⟩ + · intro c hc + rcases List.mem_cons.mp hc with rfl | hm + · exact ⟨k0, Or.inl rfl, by rw [hval0]⟩ + · obtain ⟨k, hk, rfl⟩ := hf c hm + exact ⟨k, Or.inr hk, rfl⟩ + · intro k hk + rcases hk with rfl | hk' + · rw [hval0]; exact List.mem_cons_self .. + · exact List.mem_cons_of_mem _ (hb k hk') + +theorem exactMap_remove {ms1 ms2 : List (MGChain (MGBase N T) MGLic T)} + {dom : MGLic → Prop} {val : MGLic → List T} + {k0 : MGLic} {t : List T} + (h : ExactMap (ms1 ++ ⟨t, [MGFeature.licensee k0]⟩ :: ms2) dom val) : + dom k0 ∧ t = val k0 ∧ + ExactMap (ms1 ++ ms2) (fun k => dom k ∧ k ≠ k0) val := by + obtain ⟨hsmc, hf, hb⟩ := h + have hmem0 : ⟨t, [MGFeature.licensee k0]⟩ ∈ ms1 ++ ⟨t, [MGFeature.licensee k0]⟩ :: ms2 := + List.mem_append_right _ (List.mem_cons_self ..) + obtain ⟨k', hk', heq⟩ := hf _ hmem0 + have ht_eq : t = val k' := by injection heq + have hk_eq : k0 = k' := by + have hfeats := congrArg MGChain.feats heq + simp at hfeats + exact hfeats + subst hk_eq + refine ⟨hk', ht_eq, MG.smc_remove hsmc, ?_, ?_⟩ + · intro c hc + have hc_in : c ∈ ms1 ++ ⟨t, [MGFeature.licensee k0]⟩ :: ms2 := by + rcases List.mem_append.mp hc with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2) + obtain ⟨k, hk, rfl⟩ := hf c hc_in + have hne : k ≠ k0 := by + intro heqk; subst heqk + have hnd := hsmc.2 + simp only [List.filterMap_append, List.filterMap_cons, MGChain.headLic, + List.nodup_append, List.nodup_cons] at hnd + rcases List.mem_append.mp hc with h1 | h2 + · exact hnd.2.2 k (List.mem_filterMap.mpr ⟨_, h1, rfl⟩) k (List.mem_cons_self ..) rfl + · exact hnd.2.1.1 (List.mem_filterMap.mpr ⟨_, h2, rfl⟩) + exact ⟨k, ⟨hk, hne⟩, rfl⟩ + · intro k ⟨hk, hne⟩ + have hm := hb k hk + rcases List.mem_append.mp hm with h1 | h2 + · exact List.mem_append_left _ h1 + · rcases List.mem_cons.mp h2 with heq' | h2' + · have hfe := congrArg MGChain.feats heq' + simp at hfe + exact absurd hfe hne + · exact List.mem_append_right _ h2' + +/-- Predicate expressing that every mover in `ms` has a single licensee feature. -/ +def SingleMover (ms : List (MGChain (MGBase N T) MGLic T)) : Prop := + ∀ c, c ∈ ms → ∃ k, c.feats = [MGFeature.licensee k] + +theorem exactMap_singleMover {ms : List (MGChain (MGBase N T) MGLic T)} + {dom : MGLic → Prop} {val : MGLic → List T} (h : ExactMap ms dom val) : + SingleMover ms := by + intro c hc + obtain ⟨k, _, rfl⟩ := h.2.1 c hc + exact ⟨k, rfl⟩ + +theorem singleMover_nil : SingleMover (N := N) (T := T) [] := by + intro c hc; simp at hc + +theorem singleMover_no_move2 {ms1 ms2 : List (MGChain (MGBase N T) MGLic T)} + {t : List T} {f f' : MGLic} {δ' : List (MGFeature (MGBase N T) MGLic)} + (hs : SingleMover (ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2)) : + False := by + obtain ⟨k, hk⟩ := hs _ (List.mem_append_right _ (List.mem_cons_self ..)) + simp at hk + +/-! ### Part 3: Variable Domains, Rule Values, and Linearity Lemmas -/ + +/-- Variable pairs occurring in a single component template. -/ +def compVars (comp : List (MCFGAtom T)) : List (Nat × Nat) := + comp.filterMap fun + | MCFGAtom.tm _ => none + | MCFGAtom.var i j => some (i, j) + +/-- Variable pairs occurring across a list of component templates. -/ +def compsVars (cs : List (List (MCFGAtom T))) : List (Nat × Nat) := + cs.flatMap compVars + +theorem compVars_append (c1 c2 : List (MCFGAtom T)) : + compVars (c1 ++ c2) = compVars c1 ++ compVars c2 := + List.filterMap_append + +theorem compVars_reverse (c : List (MCFGAtom T)) : + compVars c.reverse = (compVars c).reverse := by + induction c with + | nil => rfl + | cons a t ih => + cases a with + | tm x => simp [compVars] + | var i j => simp [compVars] + +theorem mem_compVars_reverse {c : List (MCFGAtom T)} {p : Nat × Nat} : + p ∈ compVars c.reverse ↔ p ∈ compVars c := by + rw [compVars_reverse, List.mem_reverse] + +theorem compsVars_append (cs1 cs2 : List (List (MCFGAtom T))) : + compsVars (cs1 ++ cs2) = compsVars cs1 ++ compsVars cs2 := + List.flatMap_append + +theorem compsVars_cons (c : List (MCFGAtom T)) (cs : List (List (MCFGAtom T))) : + compsVars (c :: cs) = compVars c ++ compsVars cs := rfl + +theorem varOccurrences_eq_compsVars (r : MCFGRule N T) : + r.varOccurrences = compsVars r.yield := rfl + +theorem drop_eq_cons_drop_succ {α : Type} {L : List α} {k : Nat} {x : α} + (h : L[k]? = some x) : L.drop k = x :: L.drop (k + 1) := by + induction L generalizing k with + | nil => simp at h + | cons a t ih => + cases k with + | zero => + simp at h; subst h; rfl + | succ k' => + simp only [List.getElem?_cons_succ] at h + simpa [List.drop_succ_cons] using ih h + +/-- Extract the `(i, j)`-th argument string from `args` (matching `MCFG.evalComp`). -/ +def argPiece (args : List (List (List T))) (i j : Nat) : List T := + match args[i]? with + | some tup => + match tup[j]? with + | some s => s + | none => [] + | none => [] + +theorem argPiece_eq_getD {args : List (List (List T))} {i j : Nat} {tup : List (List T)} + (h : args[i]? = some tup) : argPiece args i j = (tup[j]?).getD [] := by + simp only [argPiece, h] + cases tup[j]? <;> rfl + +/-- Canonical value map for a rule `r` evaluated on RHS argument tuples `args`. -/ +def ruleVal (r : MCFGRule N T) (args : List (List (List T))) : MGLic → List T + | (Bank.L, j) => argPiece args 0 j + | (Bank.R, j) => argPiece args 1 j + | (Bank.O, k) => + match r.yield[k]? with + | some comp => MCFG.evalComp args comp + | none => [] + +theorem ruleVal_O_eq_evalYield {r : MCFGRule N T} {args : List (List (List T))} {m : Nat} : + ruleVal r args (Bank.O, m) = ((MCFG.evalYield args r.yield)[m]?).getD [] := by + simp only [ruleVal, MCFG.evalYield, List.getElem?_map] + cases r.yield[m]? <;> rfl + +/-- Mover domain at `stage rid k` (`0 ≤ k ≤ r.yield.length`): + output components `0 .. k-1` in bank `O`, plus all variables occurring in `r.yield.drop k` + in banks `L` (`i = 0`) and `R` (`i = 1`). -/ +def stageDom (r : MCFGRule N T) (k : Nat) : MGLic → Prop + | (Bank.O, m) => m < k + | (Bank.L, j) => (0, j) ∈ compsVars (r.yield.drop k) + | (Bank.R, j) => (1, j) ∈ compsVars (r.yield.drop k) + +/-- Mover domain while building component `k` with remaining reverse prefix `revPref`: + output components `0 .. k-1` in bank `O`, plus variables in `revPref` or `r.yield.drop (k+1)`. -/ +def buildDom (r : MCFGRule N T) (k : Nat) (revPref : List (MCFGAtom T)) : MGLic → Prop + | (Bank.O, m) => m < k + | (Bank.L, j) => (0, j) ∈ compVars revPref ∨ (0, j) ∈ compsVars (r.yield.drop (k + 1)) + | (Bank.R, j) => (1, j) ∈ compVars revPref ∨ (1, j) ∈ compsVars (r.yield.drop (k + 1)) + +/-- Mover domain during the copy phase (`0 ≤ k ≤ d`): + `side` holds `0 .. k-1`, `O` holds `k .. d-1`. -/ +def copyDom (d : Nat) (side : Side) (k : Nat) : MGLic → Prop := + fun m => + (∃ j, j < k ∧ m = (side.toBank, j)) ∨ + (∃ j, k ≤ j ∧ j < d ∧ m = (Bank.O, j)) + +/-- Every variable in `r.yield` of a well-formed rank-≤-2 rule has argument index `0` or `1`. -/ +theorem var_index_lt_two {G : MCFG N T} {r : MCFGRule N T} + (hwf : r.WellFormed G.dim) (hrank : r.rhs.length ≤ 2) + {i j : Nat} (hv : (i, j) ∈ r.varOccurrences) : i = 0 ∨ i = 1 := by + obtain ⟨B, hB, _⟩ := (hwf.2.2 i j).mp hv + have hi : i < r.rhs.length := by + by_cases hlt : i < r.rhs.length + · exact hlt + · rw [List.getElem?_eq_none (Nat.le_of_not_lt hlt)] at hB + simp at hB + omega + +theorem nodup_of_reverse {α : Type} {L : List α} (h : L.reverse.Nodup) : L.Nodup := by + induction L with + | nil => exact List.nodup_nil + | cons a t ih => + simp only [List.reverse_cons, List.nodup_append, List.nodup_cons, List.mem_singleton] at h + rw [List.nodup_cons] + refine ⟨?_, ih h.1⟩ + intro ha + exact h.2.2 a (List.mem_reverse.mpr ha) a rfl rfl + +/-- If `comp = r.yield[k]` and `comp = revPref.reverse ++ suf`, then + `compVars revPref ++ compsVars (r.yield.drop (k + 1))` is `Nodup` by linearity of `r`. -/ +theorem nodup_buildVars {r : MCFGRule N T} (hlin : r.isLinear) + {k : Nat} {comp revPref suf : List (MCFGAtom T)} + (hget : r.yield[k]? = some comp) (hsplit : comp = revPref.reverse ++ suf) : + (compVars revPref ++ compsVars (r.yield.drop (k + 1))).Nodup := by + have hfull : r.yield = r.yield.take k ++ comp :: r.yield.drop (k + 1) := by + have h1 := (List.take_append_drop k r.yield).symm + rw [drop_eq_cons_drop_succ hget] at h1 + exact h1 + have hnd : r.varOccurrences.Nodup := hlin + rw [varOccurrences_eq_compsVars, hfull, compsVars_append, compsVars_cons, hsplit, + compVars_append] at hnd + have hnd1 := (List.nodup_append.mp hnd).2.1 + have hnd2 := List.nodup_append.mp hnd1 + have hnd_rev : (compVars revPref.reverse).Nodup := (List.nodup_append.mp hnd2.1).1 + have hnd_p : (compVars revPref).Nodup := by + rw [compVars_reverse] at hnd_rev + exact nodup_of_reverse hnd_rev + rw [List.nodup_append] + refine ⟨hnd_p, hnd2.2.1, ?_⟩ + intro x hx y hy + exact hnd2.2.2 x (List.mem_append_left _ (mem_compVars_reverse.mpr hx)) y hy + +theorem stageDom_zero_iff {G : MCFG N T} {r : MCFGRule N T} (hwf : r.WellFormed G.dim) : + ∀ m, stageDom r 0 m ↔ + (∃ B j, r.rhs[0]? = some B ∧ j < G.dim B ∧ m = (Bank.L, j)) ∨ + (∃ C j, r.rhs[1]? = some C ∧ j < G.dim C ∧ m = (Bank.R, j)) := by + intro ⟨bank, j⟩ + cases bank with + | O => simp [stageDom] + | L => + change (0, j) ∈ r.varOccurrences ↔ _ + rw [hwf.2.2 0 j] + constructor + · rintro ⟨B, hB, hj⟩; left; exact ⟨B, j, hB, hj, rfl⟩ + · rintro (⟨B, j', hB, hj, heq⟩ | ⟨C, j', _, _, heq⟩) + · have : j = j' := by injection heq + subst this; exact ⟨B, hB, hj⟩ + · simp at heq + | R => + change (1, j) ∈ r.varOccurrences ↔ _ + rw [hwf.2.2 1 j] + constructor + · rintro ⟨C, hC, hj⟩; right; exact ⟨C, j, hC, hj, rfl⟩ + · rintro (⟨B, j', _, _, heq⟩ | ⟨C, j', hC, hj, heq⟩) + · simp at heq + · have : j = j' := by injection heq + subst this; exact ⟨C, hC, hj⟩ + +theorem stageDom_eq_buildDom_start {r : MCFGRule N T} {k : Nat} {comp : List (MCFGAtom T)} + (hget : r.yield[k]? = some comp) : + ∀ m, stageDom r k m ↔ buildDom r k comp.reverse m := by + intro ⟨bank, j⟩ + cases bank with + | O => rfl + | L => + simp only [stageDom, buildDom, drop_eq_cons_drop_succ hget, compsVars_cons, + List.mem_append, mem_compVars_reverse] + | R => + simp only [stageDom, buildDom, drop_eq_cons_drop_succ hget, compsVars_cons, + List.mem_append, mem_compVars_reverse] + +theorem buildDom_step_tm {r : MCFGRule N T} {k : Nat} (a : T) (rest : List (MCFGAtom T)) : + ∀ m, buildDom r k (MCFGAtom.tm a :: rest) m ↔ buildDom r k rest m := by + intro ⟨bank, j⟩ + cases bank <;> simp [buildDom, compVars] + +theorem buildDom_step_var0 {r : MCFGRule N T} (hlin : r.isLinear) + {k j0 : Nat} {comp rest suf : List (MCFGAtom T)} + (hget : r.yield[k]? = some comp) + (hsplit : comp = (MCFGAtom.var 0 j0 :: rest).reverse ++ suf) : + ∀ m, (buildDom r k (MCFGAtom.var 0 j0 :: rest) m ∧ m ≠ (Bank.L, j0)) ↔ + buildDom r k rest m := by + have hnd := nodup_buildVars hlin hget hsplit + simp only [compVars, List.filterMap_cons, List.cons_append, List.nodup_cons, + List.mem_append] at hnd + obtain ⟨hnot_in, _⟩ := hnd + intro ⟨bank, j⟩ + cases bank with + | O => simp [buildDom] + | R => + simp only [buildDom, compVars, List.filterMap_cons, List.mem_cons, Prod.mk.injEq, + Nat.one_ne_zero, false_and, false_or, ne_eq, reduceCtorEq, not_false_eq_true, and_true] + | L => + simp only [buildDom, compVars, List.filterMap_cons, List.mem_cons, Prod.mk.injEq, + true_and, ne_eq] + constructor + · rintro ⟨(rfl | hrest) | hdrop, hne⟩ + · exact absurd rfl hne + · exact Or.inl hrest + · exact Or.inr hdrop + · rintro (hrest | hdrop) + · refine ⟨Or.inl (Or.inr hrest), ?_⟩ + rintro rfl; exact hnot_in (Or.inl hrest) + · refine ⟨Or.inr hdrop, ?_⟩ + rintro rfl; exact hnot_in (Or.inr hdrop) + +theorem buildDom_step_var1 {r : MCFGRule N T} (hlin : r.isLinear) + {k j0 : Nat} {comp rest suf : List (MCFGAtom T)} + (hget : r.yield[k]? = some comp) + (hsplit : comp = (MCFGAtom.var 1 j0 :: rest).reverse ++ suf) : + ∀ m, (buildDom r k (MCFGAtom.var 1 j0 :: rest) m ∧ m ≠ (Bank.R, j0)) ↔ + buildDom r k rest m := by + have hnd := nodup_buildVars hlin hget hsplit + simp only [compVars, List.filterMap_cons, List.cons_append, List.nodup_cons, + List.mem_append] at hnd + obtain ⟨hnot_in, _⟩ := hnd + intro ⟨bank, j⟩ + cases bank with + | O => simp [buildDom] + | L => + simp only [buildDom, compVars, List.filterMap_cons, List.mem_cons, Prod.mk.injEq, + Nat.zero_ne_one, false_and, false_or, ne_eq, reduceCtorEq, not_false_eq_true, and_true] + | R => + simp only [buildDom, compVars, List.filterMap_cons, List.mem_cons, Prod.mk.injEq, + true_and, ne_eq] + constructor + · rintro ⟨(rfl | hrest) | hdrop, hne⟩ + · exact absurd rfl hne + · exact Or.inl hrest + · exact Or.inr hdrop + · rintro (hrest | hdrop) + · refine ⟨Or.inl (Or.inr hrest), ?_⟩ + rintro rfl; exact hnot_in (Or.inl hrest) + · refine ⟨Or.inr hdrop, ?_⟩ + rintro rfl; exact hnot_in (Or.inr hdrop) + +theorem buildDom_end_insert {r : MCFGRule N T} {k : Nat} : + ∀ m, (m = (Bank.O, k) ∨ buildDom r k [] m) ↔ stageDom r (k + 1) m := by + intro ⟨bank, j⟩ + cases bank with + | O => + simp only [buildDom, stageDom, Prod.mk.injEq, true_and] + omega + | L => simp [buildDom, stageDom, compVars] + | R => simp [buildDom, stageDom, compVars] + +theorem stageDom_end_eq_copyDom_zero {r : MCFGRule N T} (d : Nat) (hd : r.yield.length = d) + (side : Side) : + ∀ m, stageDom r r.yield.length m ↔ copyDom d side 0 m := by + intro ⟨bank, j⟩ + cases bank with + | O => + simp only [stageDom, copyDom, hd] + constructor + · intro hj; right; exact ⟨j, Nat.zero_le j, hj, rfl⟩ + · rintro (⟨j', hj', _⟩ | ⟨j', _, hj', heq⟩) + · omega + · have : j = j' := by injection heq + subst this; exact hj' + | L => + simp only [stageDom, List.drop_length, compsVars, List.flatMap_nil, List.not_mem_nil, + copyDom, Prod.mk.injEq, false_iff] + rintro (⟨j', hj', _, _⟩ | ⟨j', _, _, hbk, _⟩) + · omega + · simp at hbk + | R => + simp only [stageDom, List.drop_length, compsVars, List.flatMap_nil, List.not_mem_nil, + copyDom, Prod.mk.injEq, false_iff] + rintro (⟨j', hj', _, _⟩ | ⟨j', _, _, hbk, _⟩) + · omega + · simp at hbk + +theorem copyDom_step {d : Nat} {side : Side} {k : Nat} (hk : k < d) : + ∀ m, (m = (side.toBank, k) ∨ (copyDom d side k m ∧ m ≠ (Bank.O, k))) ↔ + copyDom d side (k + 1) m := by + intro m + constructor + · rintro (rfl | ⟨(⟨j, hj, rfl⟩ | ⟨j, hlo, hhi, rfl⟩), hne⟩) + · left; exact ⟨k, by omega, rfl⟩ + · left; exact ⟨j, by omega, rfl⟩ + · right + have hjk : j ≠ k := fun heq => hne (by rw [heq]) + exact ⟨j, by omega, hhi, rfl⟩ + · rintro (⟨j, hj, rfl⟩ | ⟨j, hlo, hhi, rfl⟩) + · by_cases hjk : j = k + · subst hjk; left; rfl + · right + refine ⟨Or.inl ⟨j, by omega, rfl⟩, ?_⟩ + intro heq + have hbk : side.toBank = Bank.O := by injection heq + exact Side.toBank_ne_O side hbk + · right + refine ⟨Or.inr ⟨j, by omega, hhi, rfl⟩, ?_⟩ + intro heq + have hjk : j = k := by injection heq + omega + +theorem copyDom_end {d : Nat} {side : Side} : + ∀ m, copyDom d side d m ↔ ∃ j, j < d ∧ m = (side.toBank, j) := by + intro m + simp only [copyDom] + constructor + · rintro (h | ⟨j, hlo, hhi, _⟩) + · exact h + · omega + · exact Or.inl + +/-! ### Part 4: Completeness (`MCFG.Yield G → MG.Derives (binMCFGToMG G)`) -/ + +/-- Helper: membership of a literal terminal in `buildLexicon G`. -/ +theorem mem_lit_buildLexicon {G : MCFG N T} {r : MCFGRule N T} + (hr : r ∈ G.rules) {comp : List (MCFGAtom T)} (hcomp : comp ∈ r.yield) + {a : T} (ha : MCFGAtom.tm a ∈ comp) : + ([a], [MGFeature.cat (MGBase.lit a)]) ∈ (binMCFGToMG G).lexicon := by + change _ ∈ buildLexicon G + unfold buildLexicon + apply List.mem_cons_of_mem + apply List.mem_append_left + apply List.mem_map.mpr + refine ⟨a, ?_, rfl⟩ + unfold allTerminals + simp only [List.mem_flatMap, List.mem_filterMap] + exact ⟨r, hr, comp, hcomp, MCFGAtom.tm a, ha, rfl⟩ + +/-- Helper: membership of a rule lexicon entry in `buildLexicon G`. -/ +theorem mem_ruleLexicon_buildLexicon {G : MCFG N T} {rid : Nat} {r : MCFGRule N T} + (hr : G.rules[rid]? = some r) + {entry : List T × List (MGFeature (MGBase N T) MGLic)} + (he : entry ∈ ruleLexicon G rid r) : + entry ∈ (binMCFGToMG G).lexicon := by + change entry ∈ buildLexicon G + unfold buildLexicon + apply List.mem_cons_of_mem + apply List.mem_append_right + apply List.mem_flatMap.mpr + exact ⟨(rid, r), (mem_indexFrom_zero_iff G.rules rid r).mpr hr, he⟩ + +/-- Completing component `k` by scanning `revPref` down to `[]`. -/ +theorem buildComp_derives {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) + {rid k : Nat} {r : MCFGRule N T} {comp : List (MCFGAtom T)} + (hr : G.rules[rid]? = some r) (hcomp : r.yield[k]? = some comp) + {args : List (List (List T))} : + ∀ (revPref suf : List (MCFGAtom T)) (ms : List (MGChain (MGBase N T) MGLic T)), + comp = revPref.reverse ++ suf → + ExactMap ms (buildDom r k revPref) (ruleVal r args) → + MG.Derives (binMCFGToMG G) + ⟨false, + ⟨MCFG.evalComp args suf, + revPref.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]⟩, + ms⟩ → + ∃ ms', + ExactMap ms' (buildDom r k []) (ruleVal r args) ∧ + MG.Derives (binMCFGToMG G) + ⟨false, + ⟨MCFG.evalComp args comp, + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]⟩, + ms'⟩ := by + have hr_mem : r ∈ G.rules := List.mem_of_getElem? hr + have hwf : r.WellFormed G.dim := G.rules_wf r hr_mem + have hcomp_mem : comp ∈ r.yield := List.mem_of_getElem? hcomp + intro revPref + induction revPref with + | nil => + intro suf ms hsplit hex hder + simp only [List.reverse_nil, List.nil_append] at hsplit + subst hsplit + exact ⟨ms, hex, hder⟩ + | cons atom rest ih => + intro suf ms hsplit hex hder + have hsplit' : comp = rest.reverse ++ (atom :: suf) := by + simpa [List.reverse_cons, List.append_assoc] using hsplit + cases atom with + | tm a => + have ha_in : MCFGAtom.tm a ∈ comp := by + rw [hsplit']; exact List.mem_append_right _ (List.mem_cons_self ..) + have hlit : MG.Derives (binMCFGToMG G) ⟨true, ⟨[a], [MGFeature.cat (MGBase.lit a)]⟩, []⟩ := + MG.Derives.lex (mem_lit_buildLexicon hr_mem hcomp_mem ha_in) + have hsmc' : SMC (ms ++ []) := by simpa using hex.1 + have hstep : MG.Derives (binMCFGToMG G) + ⟨false, + ⟨MCFG.evalComp args (MCFGAtom.tm a :: suf), + rest.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]⟩, + ms⟩ := by + have hm := MG.Derives.merge2 hder hlit hsmc' + simpa [MCFG.evalComp] using hm + have hex' : ExactMap ms (buildDom r k rest) (ruleVal r args) := + exactMap_ext hex (buildDom_step_tm a rest) (fun _ _ => rfl) + exact ih (MCFGAtom.tm a :: suf) ms hsplit' hex' hstep + | var i j => + have hv_in : (i, j) ∈ r.varOccurrences := by + simp only [MCFGRule.varOccurrences, List.mem_flatMap, List.mem_filterMap] + refine ⟨comp, hcomp_mem, MCFGAtom.var i j, ?_, rfl⟩ + rw [hsplit']; exact List.mem_append_right _ (List.mem_cons_self ..) + rcases var_index_lt_two hwf (hrank r hr_mem) hv_in with rfl | rfl + · -- i = 0 (Bank.L) + have hdom0 : buildDom r k (MCFGAtom.var 0 j :: rest) (Bank.L, j) := by + simp [buildDom, compVars] + have hmem_ch : ⟨ruleVal r args (Bank.L, j), [MGFeature.licensee (Bank.L, j)]⟩ ∈ ms := + hex.2.2 (Bank.L, j) hdom0 + obtain ⟨ms1, ms2, hms_eq⟩ := List.append_of_mem hmem_ch + subst hms_eq + have hstep : MG.Derives (binMCFGToMG G) + ⟨false, + ⟨MCFG.evalComp args (MCFGAtom.var 0 j :: suf), + rest.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]⟩, + ms1 ++ ms2⟩ := by + exact MG.Derives.move1 hder + have ⟨_, _, hrem⟩ := exactMap_remove hex + have hex' : ExactMap (ms1 ++ ms2) (buildDom r k rest) (ruleVal r args) := + exactMap_ext hrem (buildDom_step_var0 hwf.2.1 hcomp hsplit) (fun _ _ => rfl) + exact ih (MCFGAtom.var 0 j :: suf) (ms1 ++ ms2) hsplit' hex' hstep + · -- i = 1 (Bank.R) + have hdom1 : buildDom r k (MCFGAtom.var 1 j :: rest) (Bank.R, j) := by + simp [buildDom, compVars] + have hmem_ch : ⟨ruleVal r args (Bank.R, j), [MGFeature.licensee (Bank.R, j)]⟩ ∈ ms := + hex.2.2 (Bank.R, j) hdom1 + obtain ⟨ms1, ms2, hms_eq⟩ := List.append_of_mem hmem_ch + subst hms_eq + have hstep : MG.Derives (binMCFGToMG G) + ⟨false, + ⟨MCFG.evalComp args (MCFGAtom.var 1 j :: suf), + rest.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]⟩, + ms1 ++ ms2⟩ := by + exact MG.Derives.move1 hder + have ⟨_, _, hrem⟩ := exactMap_remove hex + have hex' : ExactMap (ms1 ++ ms2) (buildDom r k rest) (ruleVal r args) := + exactMap_ext hrem (buildDom_step_var1 hwf.2.1 hcomp hsplit) (fun _ _ => rfl) + exact ih (MCFGAtom.var 1 j :: suf) (ms1 ++ ms2) hsplit' hex' hstep + +/-- Advance from `stage rid 0` to `stage rid k` for all `k ≤ r.yield.length`. -/ +theorem buildAllComps_derives {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) + {rid : Nat} {r : MCFGRule N T} (hr : G.rules[rid]? = some r) + {args : List (List (List T))} {b0 : Bool} {ms0 : List (MGChain (MGBase N T) MGLic T)} + (hex0 : ExactMap ms0 (stageDom r 0) (ruleVal r args)) + (hder0 : MG.Derives (binMCFGToMG G) ⟨b0, ⟨[], [MGFeature.cat (MGBase.stage rid 0)]⟩, ms0⟩) : + ∀ k, k ≤ r.yield.length → + ∃ b ms, + ExactMap ms (stageDom r k) (ruleVal r args) ∧ + MG.Derives (binMCFGToMG G) ⟨b, ⟨[], [MGFeature.cat (MGBase.stage rid k)]⟩, ms⟩ := by + intro k + induction k with + | zero => intro _; exact ⟨b0, ms0, hex0, hder0⟩ + | succ k ih => + intro hkle + obtain ⟨bk, msk, hexk, hderk⟩ := ih (by omega) + have hlt : k < r.yield.length := by omega + cases hcomp : r.yield[k]? with + | none => + rw [List.getElem?_eq_none_iff] at hcomp; omega + | some comp => + -- 1. Merge1 builder lexical item with `stage rid k` + have hbuild_lex : + ([], MGFeature.sel (MGBase.stage rid k) :: + comp.reverse.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]) ∈ + (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hr + unfold ruleLexicon + simp only [List.mem_append, List.mem_flatMap, List.mem_cons] + left; right + exact ⟨(k, comp), (mem_indexFrom_zero_iff r.yield k comp).mpr hcomp, Or.inl rfl⟩ + have hstart_build : MG.Derives (binMCFGToMG G) + ⟨false, + ⟨MCFG.evalComp args [], + comp.reverse.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]⟩, + msk⟩ := by + simpa [MCFG.evalComp] using MG.Derives.merge1 (MG.Derives.lex hbuild_lex) hderk + have hex_start : ExactMap msk (buildDom r k comp.reverse) (ruleVal r args) := + exactMap_ext hexk (stageDom_eq_buildDom_start hcomp) (fun _ _ => rfl) + -- 2. Run `buildComp_derives` down to `built rid k` + have hsplit0 : comp = comp.reverse.reverse ++ [] := by simp + obtain ⟨ms_built, hex_built, hder_built⟩ := + buildComp_derives hrank hr hcomp comp.reverse [] msk hsplit0 hex_start hstart_build + -- 3. Park finished component into `(Bank.O, k)` via Merge3 + have hpark_lex : + ([], [MGFeature.sel (MGBase.built rid k), MGFeature.cat (MGBase.stage rid (k + 1))]) ∈ + (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hr + unfold ruleLexicon + simp only [List.mem_append, List.mem_flatMap, List.mem_cons] + left; right + exact ⟨(k, comp), (mem_indexFrom_zero_iff r.yield k comp).mpr hcomp, Or.inr (Or.inl rfl)⟩ + have hfresh : ¬buildDom r k [] (Bank.O, k) := by simp [buildDom] + have hvalk : ruleVal r args (Bank.O, k) = MCFG.evalComp args comp := by + simp [ruleVal, hcomp] + have hex_parked : + ExactMap (⟨MCFG.evalComp args comp, [MGFeature.licensee (Bank.O, k)]⟩ :: ms_built) + (stageDom r (k + 1)) (ruleVal r args) := + exactMap_ext (exactMap_cons_fresh hex_built hfresh hvalk) + buildDom_end_insert (fun _ _ => rfl) + have hder_next : MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.cat (MGBase.stage rid (k + 1))]⟩, + ⟨MCFG.evalComp args comp, [MGFeature.licensee (Bank.O, k)]⟩ :: ms_built⟩ := by + exact MG.Derives.merge3 (MG.Derives.lex hpark_lex) hder_built hex_parked.1 + exact ⟨false, _, hex_parked, hder_next⟩ + +/-- Copy all `d = G.dim r.lhs` components from bank `O` to target bank `side`, + ending in `nt r.lhs side`. -/ +theorem copyAll_derives {G : MCFG N T} + {rid : Nat} {r : MCFGRule N T} (hr : G.rules[rid]? = some r) + (side : Side) (tup : List (List T)) : + ∀ rem k, k + rem = G.dim r.lhs → + k < G.dim r.lhs → + ∀ ms, + ExactMap ms (copyDom (G.dim r.lhs) side k) (fun m => (tup[m.2]?).getD []) → + MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.cat (MGBase.copyStage rid side k)]⟩, ms⟩ → + ∃ ms', + ExactMap ms' (fun m => ∃ j, j < G.dim r.lhs ∧ m = (side.toBank, j)) + (fun m => (tup[m.2]?).getD []) ∧ + MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.cat (MGBase.nt r.lhs side)]⟩, ms'⟩ := by + intro rem + induction rem with + | zero => intro k hsum hk; omega + | succ rem' ih => + intro k hsum hk ms hex hder + -- 1. Merge1 lift lexical item with `copyStage rid side k` + have hlift_lex : + ([], [MGFeature.sel (MGBase.copyStage rid side k), + MGFeature.licensor (Bank.O, k), + MGFeature.cat (MGBase.copied rid side k), + MGFeature.licensee (side.toBank, k)]) ∈ (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hr + unfold ruleLexicon + simp only [List.mem_append, List.mem_flatMap, List.mem_cons] + right + refine ⟨side, by cases side <;> simp, Or.inr ?_⟩ + exact ⟨k, List.mem_range.mpr hk, Or.inl rfl⟩ + have hstep1 : MG.Derives (binMCFGToMG G) + ⟨false, + ⟨[], [MGFeature.licensor (Bank.O, k), + MGFeature.cat (MGBase.copied rid side k), + MGFeature.licensee (side.toBank, k)]⟩, + ms⟩ := by + simpa using MG.Derives.merge1 (MG.Derives.lex hlift_lex) hder + -- 2. Move1 on `(Bank.O, k)` + have hdomO : copyDom (G.dim r.lhs) side k (Bank.O, k) := + Or.inr ⟨k, Nat.le_refl _, hk, rfl⟩ + have hmemO : ⟨(tup[k]?).getD [], [MGFeature.licensee (Bank.O, k)]⟩ ∈ ms := + hex.2.2 (Bank.O, k) hdomO + obtain ⟨ms1, ms2, hms_eq⟩ := List.append_of_mem hmemO + subst hms_eq + have hstep2 : MG.Derives (binMCFGToMG G) + ⟨false, + ⟨(tup[k]?).getD [], + [MGFeature.cat (MGBase.copied rid side k), MGFeature.licensee (side.toBank, k)]⟩, + ms1 ++ ms2⟩ := by + simpa using MG.Derives.move1 hstep1 + have ⟨_, _, hrem⟩ := exactMap_remove hex + -- 3. Merge3 park lexical item + let nextCat : MGBase N T := + if k + 1 < G.dim r.lhs then MGBase.copyStage rid side (k + 1) + else MGBase.nt r.lhs side + have hpark_lex : + ([], [MGFeature.sel (MGBase.copied rid side k), MGFeature.cat nextCat]) ∈ + (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hr + unfold ruleLexicon + simp only [List.mem_append, List.mem_flatMap, List.mem_cons] + right + refine ⟨side, by cases side <;> simp, Or.inr ?_⟩ + exact ⟨k, List.mem_range.mpr hk, Or.inr (Or.inl rfl)⟩ + have hfresh : ¬(copyDom (G.dim r.lhs) side k (side.toBank, k) ∧ (side.toBank, k) ≠ (Bank.O, k)) := by + rintro ⟨(⟨j, hj, heq⟩ | ⟨j, _, _, heq⟩), _⟩ + · have : k = j := by injection heq + omega + · have : side.toBank = Bank.O := by injection heq + exact Side.toBank_ne_O side this + have hex_next : + ExactMap (⟨(tup[k]?).getD [], [MGFeature.licensee (side.toBank, k)]⟩ :: (ms1 ++ ms2)) + (copyDom (G.dim r.lhs) side (k + 1)) (fun m => (tup[m.2]?).getD []) := + exactMap_ext (exactMap_cons_fresh hrem hfresh rfl) (copyDom_step hk) (fun _ _ => rfl) + have hstep3 : MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.cat nextCat]⟩, + ⟨(tup[k]?).getD [], [MGFeature.licensee (side.toBank, k)]⟩ :: (ms1 ++ ms2)⟩ := + MG.Derives.merge3 (MG.Derives.lex hpark_lex) hstep2 hex_next.1 + by_cases hlt' : k + 1 < G.dim r.lhs + · have hnext_eq : nextCat = MGBase.copyStage rid side (k + 1) := by simp [nextCat, hlt'] + rw [hnext_eq] at hstep3 + exact ih (k + 1) (by omega) hlt' _ hex_next hstep3 + · have hnext_eq : nextCat = MGBase.nt r.lhs side := by simp [nextCat, hlt'] + have heq_d : k + 1 = G.dim r.lhs := by omega + rw [hnext_eq] at hstep3 + rw [heq_d] at hex_next + exact ⟨_, exactMap_ext hex_next copyDom_end (fun _ _ => rfl), hstep3⟩ + +/-- Inductive list helper for mutual structural recursion on `MCFG.Yield` / `MCFG.YieldList`. -/ +inductive CompleteList (G : MCFG N T) : List N → List (List (List T)) → Prop where + | nil : CompleteList G [] [] + | cons {A : N} {As : List N} {tup : List (List T)} {tups : List (List (List T))} : + (∀ side : Side, ∃ ms, + ExactMap ms (fun m => ∃ j, j < G.dim A ∧ m = (side.toBank, j)) + (fun m => (tup[m.2]?).getD []) ∧ + MG.Derives (binMCFGToMG G) ⟨false, ⟨[], [MGFeature.cat (MGBase.nt A side)]⟩, ms⟩) → + CompleteList G As tups → + CompleteList G (A :: As) (tup :: tups) + +theorem getElem?_of_mem {α : Type} {x : α} {L : List α} (h : x ∈ L) : + ∃ idx : Nat, L[idx]? = some x := by + induction L with + | nil => simp at h + | cons a t ih => + rcases List.mem_cons.mp h with rfl | ht + · exact ⟨0, rfl⟩ + · obtain ⟨idx, hidx⟩ := ih ht + exact ⟨idx + 1, by simpa using hidx⟩ + +mutual + theorem binMCFGToMG_complete {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) + {A : N} {tup : List (List T)} : + MCFG.Yield G A tup → + ∀ side : Side, ∃ ms, + ExactMap ms (fun m => ∃ j, j < G.dim A ∧ m = (side.toBank, j)) + (fun m => (tup[m.2]?).getD []) ∧ + MG.Derives (binMCFGToMG G) ⟨false, ⟨[], [MGFeature.cat (MGBase.nt A side)]⟩, ms⟩ + | @MCFG.Yield.rule _ _ _ r args hr hargs_raw => by + have hargs := binMCFGToMG_complete_list hrank hargs_raw + obtain ⟨rid, hrid⟩ := getElem?_of_mem hr + have hwf := G.rules_wf r hr + have hlen_le := hrank r hr + -- Step 1: Reach `stage rid 0` + have hstage0 : ∃ b0 ms0, + ExactMap ms0 (stageDom r 0) (ruleVal r args) ∧ + MG.Derives (binMCFGToMG G) ⟨b0, ⟨[], [MGFeature.cat (MGBase.stage rid 0)]⟩, ms0⟩ := by + cases hrhs : r.rhs with + | nil => + rw [hrhs] at hargs + cases hargs + have hinit_lex : ([], [MGFeature.cat (MGBase.stage rid 0)]) ∈ (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hrid + unfold ruleLexicon + simp [hrhs] + have hdom0 : ∀ m, False ↔ stageDom r 0 m := by + intro m; rw [stageDom_zero_iff hwf m, hrhs]; simp + exact ⟨true, [], exactMap_ext (exactMap_nil (ruleVal r [])) hdom0 (fun _ h => False.elim h), + MG.Derives.lex hinit_lex⟩ + | cons B rest => + cases rest with + | nil => + rw [hrhs] at hargs + cases hargs with + | @cons _ _ tupB _ hB hnil => + cases hnil + obtain ⟨msB, hexB, hderB⟩ := hB Side.L + have hinit_lex : + ([], [MGFeature.sel (MGBase.nt B Side.L), MGFeature.cat (MGBase.stage rid 0)]) ∈ + (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hrid + unfold ruleLexicon + simp [hrhs] + have hder0 : MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.cat (MGBase.stage rid 0)]⟩, msB⟩ := by + simpa using MG.Derives.merge1 (MG.Derives.lex hinit_lex) hderB + have hex0 : ExactMap msB (stageDom r 0) (ruleVal r [tupB]) := by + refine exactMap_ext hexB ?_ ?_ + · intro m + rw [stageDom_zero_iff hwf m, hrhs] + simp [Side.toBank] + · intro m hm + obtain ⟨j, _, hm'⟩ := hm; subst hm' + simp only [Side.toBank, ruleVal] + exact (argPiece_eq_getD rfl).symm + exact ⟨false, msB, hex0, hder0⟩ + | cons C rest' => + cases rest' with + | nil => + rw [hrhs] at hargs + cases hargs with + | @cons _ _ tupB _ hB hrest => + cases hrest with + | @cons _ _ tupC _ hC hnil => + cases hnil + obtain ⟨msB, hexB, hderB⟩ := hB Side.L + obtain ⟨msC, hexC, hderC⟩ := hC Side.R + have hinit_lex : + ([], [MGFeature.sel (MGBase.nt B Side.L), + MGFeature.sel (MGBase.nt C Side.R), + MGFeature.cat (MGBase.stage rid 0)]) ∈ (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hrid + unfold ruleLexicon + simp [hrhs] + have hmid : MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.sel (MGBase.nt C Side.R), + MGFeature.cat (MGBase.stage rid 0)]⟩, msB⟩ := by + simpa using MG.Derives.merge1 (MG.Derives.lex hinit_lex) hderB + have hexB' : ExactMap msB (fun m => ∃ j, j < G.dim B ∧ m = (Bank.L, j)) + (ruleVal r [tupB, tupC]) := by + refine exactMap_ext hexB (fun _ => Iff.rfl) ?_ + intro m ⟨j, _, hm'⟩; subst hm' + simp only [Side.toBank, ruleVal] + exact (argPiece_eq_getD rfl).symm + have hexC' : ExactMap msC (fun m => ∃ j, j < G.dim C ∧ m = (Bank.R, j)) + (ruleVal r [tupB, tupC]) := by + refine exactMap_ext hexC (fun _ => Iff.rfl) ?_ + intro m ⟨j, _, hm'⟩; subst hm' + simp only [Side.toBank, ruleVal] + exact (argPiece_eq_getD rfl).symm + have hdisj : ∀ m, (∃ j, j < G.dim B ∧ m = (Bank.L, j)) → + ¬(∃ j, j < G.dim C ∧ m = (Bank.R, j)) := by + rintro m ⟨j1, _, rfl⟩ ⟨j2, _, heq⟩; simp at heq + have hexBC := exactMap_disjoint_append hexB' hexC' hdisj + have hder0 : MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.cat (MGBase.stage rid 0)]⟩, msB ++ msC⟩ := by + simpa using MG.Derives.merge2 hmid hderC hexBC.1 + have hex0 : ExactMap (msB ++ msC) (stageDom r 0) (ruleVal r [tupB, tupC]) := by + refine exactMap_ext hexBC ?_ (fun _ _ => rfl) + intro m + rw [stageDom_zero_iff hwf m, hrhs] + simp + exact ⟨false, msB ++ msC, hex0, hder0⟩ + | cons _ _ => + rw [hrhs] at hlen_le; simp at hlen_le + -- Step 2: Build all `r.yield.length` components into bank `O` + obtain ⟨b0, ms0, hex0, hder0⟩ := hstage0 + obtain ⟨bEnd, msEnd, hexEnd, hderEnd⟩ := + buildAllComps_derives hrank hrid hex0 hder0 r.yield.length (Nat.le_refl _) + -- Step 3: Bridge to `copyStage rid side 0` and copy `O → side` + intro side + have hbridge_lex : + ([], [MGFeature.sel (MGBase.stage rid r.yield.length), + MGFeature.cat (MGBase.copyStage rid side 0)]) ∈ (binMCFGToMG G).lexicon := by + apply mem_ruleLexicon_buildLexicon hrid + unfold ruleLexicon + simp only [List.mem_append, List.mem_flatMap, List.mem_cons] + right + exact ⟨side, by cases side <;> simp, Or.inl rfl⟩ + have hder_c0 : MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.cat (MGBase.copyStage rid side 0)]⟩, msEnd⟩ := by + simpa using MG.Derives.merge1 (MG.Derives.lex hbridge_lex) hderEnd + have hex_c0 : ExactMap msEnd (copyDom (G.dim r.lhs) side 0) + (fun m => ((MCFG.evalYield args r.yield)[m.2]?).getD []) := by + refine exactMap_ext hexEnd (stageDom_end_eq_copyDom_zero (G.dim r.lhs) hwf.1 side) ?_ + intro ⟨bank, m⟩ hm + cases bank with + | O => exact ruleVal_O_eq_evalYield + | L => simp [stageDom, compsVars] at hm + | R => simp [stageDom, compsVars] at hm + exact copyAll_derives hrid side (MCFG.evalYield args r.yield) + (G.dim r.lhs) 0 (by omega) (G.dim_pos r.lhs) msEnd hex_c0 hder_c0 + + theorem binMCFGToMG_complete_list {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) + {As : List N} {args : List (List (List T))} : + MCFG.YieldList G As args → CompleteList G As args + | MCFG.YieldList.nil => CompleteList.nil + | MCFG.YieldList.cons hy hrest => + CompleteList.cons (binMCFGToMG_complete hrank hy) + (binMCFGToMG_complete_list hrank hrest) +end + +theorem binMCFGToMG_lang_of_mcfg {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) {w : List T} + (h : G.Lang w) : (binMCFGToMG G).Lang w := by + obtain ⟨ms, hex, hder_start⟩ := binMCFGToMG_complete hrank h Side.L + have hstart_lex : + ([], [MGFeature.sel (MGBase.nt G.start Side.L), + MGFeature.licensor (Bank.L, 0), + MGFeature.cat MGBase.start]) ∈ (binMCFGToMG G).lexicon := by + change _ ∈ buildLexicon G + unfold buildLexicon + exact List.mem_cons_self .. + have hmid : MG.Derives (binMCFGToMG G) + ⟨false, ⟨[], [MGFeature.licensor (Bank.L, 0), MGFeature.cat MGBase.start]⟩, ms⟩ := by + simpa using MG.Derives.merge1 (MG.Derives.lex hstart_lex) hder_start + have hdom0 : ∃ j, j < G.dim G.start ∧ (Bank.L, 0) = (Side.L.toBank, j) := + ⟨0, by rw [G.dim_start]; omega, rfl⟩ + have hmem0 : ⟨w, [MGFeature.licensee (Bank.L, 0)]⟩ ∈ ms := by + simpa using hex.2.2 (Bank.L, 0) hdom0 + obtain ⟨ms1, ms2, hms_eq⟩ := List.append_of_mem hmem0 + subst hms_eq + have hfin : MG.Derives (binMCFGToMG G) + ⟨false, ⟨w, [MGFeature.cat MGBase.start]⟩, ms1 ++ ms2⟩ := by + simpa using MG.Derives.move1 hmid + have ⟨_, _, hrem⟩ := exactMap_remove hex + have hnil : ms1 ++ ms2 = [] := by + apply exactMap_empty_eq_nil hrem + rintro m ⟨⟨j, hj, rfl⟩, hne⟩ + rw [G.dim_start] at hj + have hj0 : j = 0 := by omega + subst hj0 + exact hne rfl + rw [hnil] at hfin + exact ⟨false, hfin⟩ + +/-! ### Part 5: Soundness (`MG.Derives (binMCFGToMG G) → MGInv G`) -/ + +/-- Exact inductive invariant characterizing all 18 expression shapes + of `binMCFGToMG G`. Every constructor has a disjoint syntactic signature. -/ +inductive MGInv (G : MCFG N T) : MGExpr (MGBase N T) MGLic T → Prop where + | startLex : + MGInv G ⟨true, ⟨[], [MGFeature.sel (MGBase.nt G.start Side.L), + MGFeature.licensor (Bank.L, 0), + MGFeature.cat MGBase.start]⟩, []⟩ + | startMid {w : List T} {ms : List (MGChain (MGBase N T) MGLic T)} : + G.Lang w → + ExactMap ms (fun m => m = (Bank.L, 0)) (fun _ => w) → + MGInv G ⟨false, ⟨[], [MGFeature.licensor (Bank.L, 0), MGFeature.cat MGBase.start]⟩, ms⟩ + | startDone {w : List T} : + G.Lang w → + MGInv G ⟨false, ⟨w, [MGFeature.cat MGBase.start]⟩, []⟩ + | litLex (a : T) : + MGInv G ⟨true, ⟨[a], [MGFeature.cat (MGBase.lit a)]⟩, []⟩ + | ntReady {A : N} {side : Side} {tup : List (List T)} + {ms : List (MGChain (MGBase N T) MGLic T)} : + MCFG.Yield G A tup → + ExactMap ms (fun m => ∃ j, j < G.dim A ∧ m = (side.toBank, j)) + (fun m => (tup[m.2]?).getD []) → + MGInv G ⟨false, ⟨[], [MGFeature.cat (MGBase.nt A side)]⟩, ms⟩ + | initUnaryLex {rid : Nat} {r : MCFGRule N T} {B : N} : + G.rules[rid]? = some r → + r.rhs = [B] → + MGInv G ⟨true, ⟨[], [MGFeature.sel (MGBase.nt B Side.L), + MGFeature.cat (MGBase.stage rid 0)]⟩, []⟩ + | initBinLex {rid : Nat} {r : MCFGRule N T} {B C : N} : + G.rules[rid]? = some r → + r.rhs = [B, C] → + MGInv G ⟨true, ⟨[], [MGFeature.sel (MGBase.nt B Side.L), + MGFeature.sel (MGBase.nt C Side.R), + MGFeature.cat (MGBase.stage rid 0)]⟩, []⟩ + | initBinMid {rid : Nat} {r : MCFGRule N T} {B C : N} {tup0 : List (List T)} + {ms : List (MGChain (MGBase N T) MGLic T)} : + G.rules[rid]? = some r → + r.rhs = [B, C] → + MCFG.Yield G B tup0 → + ExactMap ms (fun m => ∃ j, j < G.dim B ∧ m = (Bank.L, j)) + (fun m => (tup0[m.2]?).getD []) → + MGInv G ⟨false, ⟨[], [MGFeature.sel (MGBase.nt C Side.R), + MGFeature.cat (MGBase.stage rid 0)]⟩, ms⟩ + | stageReady {b : Bool} {rid k : Nat} {r : MCFGRule N T} + {args : List (List (List T))} {ms : List (MGChain (MGBase N T) MGLic T)} : + G.rules[rid]? = some r → + k ≤ r.yield.length → + MCFG.YieldList G r.rhs args → + ExactMap ms (stageDom r k) (ruleVal r args) → + MGInv G ⟨b, ⟨[], [MGFeature.cat (MGBase.stage rid k)]⟩, ms⟩ + | buildLex {rid k : Nat} {r : MCFGRule N T} {comp : List (MCFGAtom T)} : + G.rules[rid]? = some r → + r.yield[k]? = some comp → + MGInv G ⟨true, ⟨[], MGFeature.sel (MGBase.stage rid k) :: + comp.reverse.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)]⟩, []⟩ + | buildActive {rid k : Nat} {r : MCFGRule N T} {comp revPref suf : List (MCFGAtom T)} + {args : List (List (List T))} {ms : List (MGChain (MGBase N T) MGLic T)} + {α : List (MGFeature (MGBase N T) MGLic)} : + G.rules[rid]? = some r → + r.yield[k]? = some comp → + comp = revPref.reverse ++ suf → + α = revPref.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)] → + MCFG.YieldList G r.rhs args → + ExactMap ms (buildDom r k revPref) (ruleVal r args) → + MGInv G ⟨false, ⟨MCFG.evalComp args suf, α⟩, ms⟩ + | parkBuiltLex {rid k : Nat} {r : MCFGRule N T} {comp : List (MCFGAtom T)} : + G.rules[rid]? = some r → + r.yield[k]? = some comp → + MGInv G ⟨true, ⟨[], [MGFeature.sel (MGBase.built rid k), + MGFeature.cat (MGBase.stage rid (k + 1))]⟩, []⟩ + | bridgeLex {rid : Nat} {r : MCFGRule N T} {side : Side} : + G.rules[rid]? = some r → + MGInv G ⟨true, ⟨[], [MGFeature.sel (MGBase.stage rid r.yield.length), + MGFeature.cat (MGBase.copyStage rid side 0)]⟩, []⟩ + | copyStageReady {rid k : Nat} {r : MCFGRule N T} {side : Side} {tup : List (List T)} + {ms : List (MGChain (MGBase N T) MGLic T)} : + G.rules[rid]? = some r → + k < G.dim r.lhs → + MCFG.Yield G r.lhs tup → + ExactMap ms (copyDom (G.dim r.lhs) side k) (fun m => (tup[m.2]?).getD []) → + MGInv G ⟨false, ⟨[], [MGFeature.cat (MGBase.copyStage rid side k)]⟩, ms⟩ + | copyLiftLex {rid k : Nat} {r : MCFGRule N T} {side : Side} : + G.rules[rid]? = some r → + k < G.dim r.lhs → + MGInv G ⟨true, ⟨[], [MGFeature.sel (MGBase.copyStage rid side k), + MGFeature.licensor (Bank.O, k), + MGFeature.cat (MGBase.copied rid side k), + MGFeature.licensee (side.toBank, k)]⟩, []⟩ + | copyLiftMid {rid k : Nat} {r : MCFGRule N T} {side : Side} {tup : List (List T)} + {ms : List (MGChain (MGBase N T) MGLic T)} : + G.rules[rid]? = some r → + k < G.dim r.lhs → + MCFG.Yield G r.lhs tup → + ExactMap ms (copyDom (G.dim r.lhs) side k) (fun m => (tup[m.2]?).getD []) → + MGInv G ⟨false, ⟨[], [MGFeature.licensor (Bank.O, k), + MGFeature.cat (MGBase.copied rid side k), + MGFeature.licensee (side.toBank, k)]⟩, ms⟩ + | copiedReady {rid k : Nat} {r : MCFGRule N T} {side : Side} {tup : List (List T)} + {ms : List (MGChain (MGBase N T) MGLic T)} : + G.rules[rid]? = some r → + k < G.dim r.lhs → + MCFG.Yield G r.lhs tup → + ExactMap ms (fun m => copyDom (G.dim r.lhs) side k m ∧ m ≠ (Bank.O, k)) + (fun m => (tup[m.2]?).getD []) → + MGInv G ⟨false, ⟨(tup[k]?).getD [], + [MGFeature.cat (MGBase.copied rid side k), + MGFeature.licensee (side.toBank, k)]⟩, ms⟩ + | parkCopiedLex {rid k : Nat} {r : MCFGRule N T} {side : Side} : + G.rules[rid]? = some r → + k < G.dim r.lhs → + MGInv G ⟨true, ⟨[], [MGFeature.sel (MGBase.copied rid side k), + MGFeature.cat (if k + 1 < G.dim r.lhs + then MGBase.copyStage rid side (k + 1) + else MGBase.nt r.lhs side)]⟩, []⟩ + +theorem MGInv.singleMover {G : MCFG N T} {e : MGExpr (MGBase N T) MGLic T} + (h : MGInv G e) : SingleMover e.movers := by + cases h with + | startLex | startDone | litLex | initUnaryLex | initBinLex | buildLex + | parkBuiltLex | bridgeLex | copyLiftLex | parkCopiedLex => + exact singleMover_nil + | startMid _ hex | ntReady _ hex | initBinMid _ _ _ hex | stageReady _ _ _ hex + | buildActive _ _ _ _ _ hex | copyStageReady _ _ _ hex | copyLiftMid _ _ _ hex + | copiedReady _ _ _ hex => + exact exactMap_singleMover hex + +/-- Helper: a `buildActive` feature list never has length 1 (`[cat x]`). -/ +theorem buildActive_feats_ne_singleton {revPref : List (MCFGAtom T)} {rid k : Nat} + {x : MGBase N T} : + revPref.map (atomToFeat (N := N)) ++ + [MGFeature.cat (MGBase.built rid k), MGFeature.licensee (Bank.O, k)] ≠ + [MGFeature.cat x] := by + intro heq + have hlen := congrArg List.length heq + simp at hlen + +private theorem binMCFGToMG_merge1 {N T : Type} {G : MCFG N T} + {s t : List T} {x : MGBase N T} {γ : List (MGFeature (MGBase N T) MGLic)} {b : Bool} + {ms : List (MGChain (MGBase N T) MGLic T)} + (ih1 : MGInv G { isLex := true, head := { str := s, feats := MGFeature.sel x :: γ }, movers := [] }) + (ih2 : MGInv G { isLex := b, head := { str := t, feats := [MGFeature.cat x] }, movers := ms }) : + MGInv G { isLex := false, head := { str := s ++ t, feats := γ }, movers := ms } := by + cases ih1 with + | startLex => + cases ih2 with + | @ntReady _ _ tup _ hy hex => + have hlen : tup.length = 1 := by rw [hy.length_eq, G.dim_start] + cases tup with + | nil => simp at hlen + | cons w rest => + cases rest with + | cons _ _ => simp at hlen + | nil => + have hex' : ExactMap ms (fun m => m = (Bank.L, 0)) (fun _ => w) := by + refine exactMap_ext hex ?_ ?_ + · intro m + rw [G.dim_start] + constructor + · rintro ⟨j, hj, rfl⟩ + have : j = 0 := by omega + subst this; rfl + · rintro rfl; exact ⟨0, by omega, rfl⟩ + · rintro m ⟨j, hj, rfl⟩ + rw [G.dim_start] at hj + have : j = 0 := by omega + subst this; rfl + simpa using MGInv.startMid hy hex' + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | @initUnaryLex rid r B hrid hrhs => + cases ih2 with + | @ntReady _ _ tup _ hy hex => + have hwf := G.rules_wf r (List.mem_of_getElem? hrid) + have hyl : MCFG.YieldList G r.rhs [tup] := by + rw [hrhs]; exact MCFG.YieldList.cons hy MCFG.YieldList.nil + have hex0 : ExactMap ms (stageDom r 0) (ruleVal r [tup]) := by + refine exactMap_ext hex ?_ ?_ + · intro m; rw [stageDom_zero_iff hwf m, hrhs]; simp [Side.toBank] + · intro m ⟨j, _, hm⟩; subst hm; simp only [Side.toBank, ruleVal]; exact (argPiece_eq_getD rfl).symm + simpa using MGInv.stageReady hrid (Nat.zero_le _) hyl hex0 + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | @initBinLex rid r B C hrid hrhs => + cases ih2 with + | ntReady hy hex => + simpa using MGInv.initBinMid hrid hrhs hy hex + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | @buildLex rid k r comp hrid hcomp => + cases ih2 with + | @stageReady _ _ _ r' args _ hrid' _ hyl hex => + rw [hrid] at hrid'; injection hrid' with hr_eq; subst hr_eq + have hex' : ExactMap ms (buildDom r k comp.reverse) (ruleVal r args) := + exactMap_ext hex (stageDom_eq_buildDom_start hcomp) (fun _ _ => rfl) + have hsplit : comp = comp.reverse.reverse ++ [] := by simp + simpa [MCFG.evalComp] using MGInv.buildActive hrid hcomp hsplit rfl hyl hex' + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | parkBuiltLex _ _ => + cases ih2 with + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | @bridgeLex rid r side hrid => + cases ih2 with + | @stageReady _ _ _ r' args _ hrid' _ hyl hex => + rw [hrid] at hrid'; injection hrid' with hr_eq; subst hr_eq + have hwf := G.rules_wf r (List.mem_of_getElem? hrid) + have hy : MCFG.Yield G r.lhs (MCFG.evalYield args r.yield) := + MCFG.Yield.rule (List.mem_of_getElem? hrid) hyl + have hex' : ExactMap ms (copyDom (G.dim r.lhs) side 0) + (fun m => ((MCFG.evalYield args r.yield)[m.2]?).getD []) := by + refine exactMap_ext hex (stageDom_end_eq_copyDom_zero (G.dim r.lhs) hwf.1 side) ?_ + intro ⟨bank, m⟩ hm + cases bank with + | O => exact ruleVal_O_eq_evalYield + | L => simp [stageDom, compsVars] at hm + | R => simp [stageDom, compsVars] at hm + simpa using MGInv.copyStageReady hrid (G.dim_pos r.lhs) hy hex' + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | @copyLiftLex rid k r side hrid hk => + cases ih2 with + | @copyStageReady _ _ r' _ tup _ hrid' _ hy hex => + rw [hrid] at hrid'; injection hrid' with hr_eq; subst hr_eq + simpa using MGInv.copyLiftMid hrid hk hy hex + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | parkCopiedLex _ _ => + cases ih2 with + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + +private theorem binMCFGToMG_merge3 {N T : Type} {G : MCFG N T} + {s t : List T} {x : MGBase N T} {f : MGLic} {γ δ' : List (MGFeature (MGBase N T) MGLic)} {b1 b2 : Bool} + {ms1 ms2 : List (MGChain (MGBase N T) MGLic T)} + (ih1 : MGInv G { isLex := b1, head := { str := s, feats := MGFeature.sel x :: γ }, movers := ms1 }) + (ih2 : + MGInv G + { isLex := b2, head := { str := t, feats := MGFeature.cat x :: MGFeature.licensee f :: δ' }, movers := ms2 }) : + MGInv G + { isLex := false, head := { str := s, feats := γ }, + movers := ms1 ++ { str := t, feats := MGFeature.licensee f :: δ' } :: ms2 } := by + cases ih2 with + | @buildActive rid k r comp revPref suf args _ _ hrid hcomp hsplit hα hyl hex => + cases revPref with + | cons atom rest => + cases atom with + | tm _ => simp [atomToFeat] at hα + | var i _ => cases i <;> simp [atomToFeat] at hα + | nil => + simp only [List.map_nil, List.nil_append, List.cons.injEq, MGFeature.cat.injEq, + MGFeature.licensee.injEq] at hα + obtain ⟨rfl, rfl, rfl⟩ := hα + simp only [List.reverse_nil, List.nil_append] at hsplit + cases ih1 with + | @parkBuiltLex _ _ r' comp' hrid' hcomp' => + rw [hrid] at hrid'; injection hrid' with hr_eq; subst hr_eq + have hklt : k < r.yield.length := by + by_cases hlt : k < r.yield.length + · exact hlt + · rw [List.getElem?_eq_none (Nat.le_of_not_lt hlt)] at hcomp; simp at hcomp + have hfresh : ¬buildDom r k [] (Bank.O, k) := by simp [buildDom] + have hvalk : ruleVal r args (Bank.O, k) = MCFG.evalComp args suf := by + subst hsplit; simp [ruleVal, hcomp] + have hex' : ExactMap (⟨MCFG.evalComp args suf, [MGFeature.licensee (Bank.O, k)]⟩ :: ms2) + (stageDom r (k + 1)) (ruleVal r args) := + exactMap_ext (exactMap_cons_fresh hex hfresh hvalk) + buildDom_end_insert (fun _ _ => rfl) + simpa using MGInv.stageReady hrid (by omega) hyl hex' + | @buildActive _ _ _ _ revPref1 _ _ _ _ _ _ _ hα1 _ _ => + cases revPref1 with + | nil => simp at hα1 + | cons a1 _ => + cases a1 with + | tm _ => simp [atomToFeat] at hα1 + | var i _ => cases i <;> simp [atomToFeat] at hα1 + | @copiedReady rid k r side tup _ hrid hk hy hex => + cases ih1 with + | @parkCopiedLex _ _ r' _ hrid' hk' => + rw [hrid] at hrid'; injection hrid' with hr_eq; subst hr_eq + have hfresh : ¬(copyDom (G.dim r.lhs) side k (side.toBank, k) ∧ + (side.toBank, k) ≠ (Bank.O, k)) := by + rintro ⟨(⟨j, hj, heq⟩ | ⟨j, _, _, heq⟩), _⟩ + · have : k = j := by injection heq + omega + · have : side.toBank = Bank.O := by injection heq + exact Side.toBank_ne_O side this + have hex_next : + ExactMap (⟨(tup[k]?).getD [], [MGFeature.licensee (side.toBank, k)]⟩ :: ms2) + (copyDom (G.dim r.lhs) side (k + 1)) (fun m => (tup[m.2]?).getD []) := + exactMap_ext (exactMap_cons_fresh hex hfresh rfl) (copyDom_step hk) (fun _ _ => rfl) + by_cases hlt' : k + 1 < G.dim r.lhs + · simpa [hlt'] using MGInv.copyStageReady hrid hlt' hy hex_next + · have heq_d : k + 1 = G.dim r.lhs := by omega + rw [heq_d] at hex_next + simpa [hlt'] using MGInv.ntReady hy (exactMap_ext hex_next copyDom_end (fun _ _ => rfl)) + | @buildActive _ _ _ _ revPref1 _ _ _ _ _ _ _ hα1 _ _ => + cases revPref1 with + | nil => simp at hα1 + | cons a1 _ => + cases a1 with + | tm _ => simp [atomToFeat] at hα1 + | var i _ => cases i <;> simp [atomToFeat] at hα1 + +/-- Soundness of `binMCFGToMG`: every derivable MG expression satisfies `MGInv G`. -/ +theorem binMCFGToMG_sound {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) + {e : MGExpr (MGBase N T) MGLic T} (h : MG.Derives (binMCFGToMG G) e) : + MGInv G e := by + induction h with + | @lex w α hlex => + change (w, α) ∈ buildLexicon G at hlex + unfold buildLexicon at hlex + simp only [List.mem_cons, List.mem_append, List.mem_map, List.mem_flatMap] at hlex + rcases hlex with heq | ⟨a, _, heq⟩ | ⟨⟨rid, r⟩, hrid_mem, hrl⟩ + · injection heq with hw hα; subst hw; subst hα + exact MGInv.startLex + · injection heq with hw hα; subst hw; subst hα + exact MGInv.litLex a + · have hrid : G.rules[rid]? = some r := (mem_indexFrom_zero_iff G.rules rid r).mp hrid_mem + have hwf := G.rules_wf r (List.mem_of_getElem? hrid) + unfold ruleLexicon at hrl + simp only [List.mem_append] at hrl + rcases hrl with (hinit | hbuild) | hcopy + · cases hrhs : r.rhs with + | nil => + simp [hrhs] at hinit + obtain ⟨rfl, rfl⟩ := hinit + have hyl : MCFG.YieldList G r.rhs [] := by rw [hrhs]; exact MCFG.YieldList.nil + have hdom0 : ∀ m, False ↔ stageDom r 0 m := by + intro m; rw [stageDom_zero_iff hwf m, hrhs]; simp + exact MGInv.stageReady hrid (Nat.zero_le _) hyl + (exactMap_ext (exactMap_nil (ruleVal r [])) hdom0 (fun _ hf => False.elim hf)) + | cons B rest => + cases rest with + | nil => + simp [hrhs] at hinit + obtain ⟨rfl, rfl⟩ := hinit + exact MGInv.initUnaryLex hrid hrhs + | cons C rest' => + cases rest' with + | nil => + simp [hrhs] at hinit + obtain ⟨rfl, rfl⟩ := hinit + exact MGInv.initBinLex hrid hrhs + | cons _ _ => simp [hrhs] at hinit + · simp only [List.mem_flatMap, List.mem_cons, List.not_mem_nil, or_false] at hbuild + obtain ⟨⟨k, comp⟩, hk_mem, h1 | h2⟩ := hbuild + · have hcomp : r.yield[k]? = some comp := (mem_indexFrom_zero_iff r.yield k comp).mp hk_mem + injection h1 with hw hα; subst hw; subst hα + exact MGInv.buildLex hrid hcomp + · have hcomp : r.yield[k]? = some comp := (mem_indexFrom_zero_iff r.yield k comp).mp hk_mem + injection h2 with hw hα; subst hw; subst hα + exact MGInv.parkBuiltLex hrid hcomp + · simp only [List.mem_flatMap, List.mem_cons] at hcopy + obtain ⟨side, _, hbr | hcp⟩ := hcopy + · injection hbr with hw hα; subst hw; subst hα + exact MGInv.bridgeLex hrid + · simp only [List.not_mem_nil, or_false] at hcp + obtain ⟨k, hk_mem, h1 | h2⟩ := hcp + · have hk : k < G.dim r.lhs := List.mem_range.mp hk_mem + injection h1 with hw hα; subst hw; subst hα + exact MGInv.copyLiftLex hrid hk + · have hk : k < G.dim r.lhs := List.mem_range.mp hk_mem + injection h2 with hw hα; subst hw; subst hα + exact MGInv.parkCopiedLex hrid hk + | @merge1 s t x γ b ms h1 h2 ih1 ih2 => + exact binMCFGToMG_merge1 ih1 ih2 + | @merge2 s t x γ b ms1 ms2 h1 h2 hsmc12 ih1 ih2 => + cases ih1 with + | @initBinMid rid r B C tup0 _ hrid hrhs hyB hexB => + cases ih2 with + | @ntReady _ _ tup1 _ hyC hexC => + have hwf := G.rules_wf r (List.mem_of_getElem? hrid) + have hyl : MCFG.YieldList G r.rhs [tup0, tup1] := by + rw [hrhs] + exact MCFG.YieldList.cons hyB (MCFG.YieldList.cons hyC MCFG.YieldList.nil) + have hexB' : ExactMap ms1 (fun m => ∃ j, j < G.dim B ∧ m = (Bank.L, j)) + (ruleVal r [tup0, tup1]) := by + refine exactMap_ext hexB (fun _ => Iff.rfl) ?_ + intro m ⟨j, _, hm⟩; subst hm; simp only [ruleVal]; exact (argPiece_eq_getD rfl).symm + have hexC' : ExactMap ms2 (fun m => ∃ j, j < G.dim C ∧ m = (Bank.R, j)) + (ruleVal r [tup0, tup1]) := by + refine exactMap_ext hexC (fun _ => Iff.rfl) ?_ + intro m ⟨j, _, hm⟩; subst hm; simp only [Side.toBank, ruleVal]; exact (argPiece_eq_getD rfl).symm + have hdisj : ∀ m, (∃ j, j < G.dim B ∧ m = (Bank.L, j)) → + ¬(∃ j, j < G.dim C ∧ m = (Bank.R, j)) := by + rintro m ⟨_, _, rfl⟩ ⟨_, _, heq⟩; simp at heq + have hexBC := exactMap_disjoint_append hexB' hexC' hdisj + have hex0 : ExactMap (ms1 ++ ms2) (stageDom r 0) (ruleVal r [tup0, tup1]) := by + refine exactMap_ext hexBC ?_ (fun _ _ => rfl) + intro m; rw [stageDom_zero_iff hwf m, hrhs]; simp + simpa using MGInv.stageReady hrid (Nat.zero_le _) hyl hex0 + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + | @buildActive rid k r comp revPref suf args _ _ hrid hcomp hsplit hα hyl hex => + cases revPref with + | nil => simp at hα + | cons atom rest => + cases atom with + | tm a => + simp only [List.map_cons, atomToFeat, List.cons_append, List.cons.injEq, + MGFeature.sel.injEq] at hα + obtain ⟨rfl, rfl⟩ := hα + cases ih2 with + | litLex _ => + have hsplit' : comp = rest.reverse ++ (MCFGAtom.tm a :: suf) := by + simpa [List.reverse_cons, List.append_assoc] using hsplit + have hex' : ExactMap (ms1 ++ []) (buildDom r k rest) (ruleVal r args) := by + simpa using exactMap_ext hex (buildDom_step_tm a rest) (fun _ _ => rfl) + simpa [MCFG.evalComp] using MGInv.buildActive hrid hcomp hsplit' rfl hyl hex' + | buildActive _ _ _ hα2 _ _ => exact absurd hα2.symm buildActive_feats_ne_singleton + | var i j => + cases i <;> simp [atomToFeat] at hα + | @merge3 s t x f γ δ' b1 b2 ms1 ms2 h1 h2 hsmc3 ih1 ih2 => + exact binMCFGToMG_merge3 ih1 ih2 + | @move1 s t f γ ms1 ms2 h1 ih1 => + cases ih1 with + | @startMid w _ hlang hex => + have ⟨_, ht_eq, hrem⟩ := exactMap_remove hex + have hnil : ms1 ++ ms2 = [] := by + apply exactMap_empty_eq_nil hrem + intro m ⟨hm, hne⟩; exact hne hm + rw [ht_eq, hnil] + simpa using MGInv.startDone hlang + | @buildActive rid k r comp revPref suf args _ _ hrid hcomp hsplit hα hyl hex => + have hr_mem : r ∈ G.rules := List.mem_of_getElem? hrid + have hwf := G.rules_wf r hr_mem + have hcomp_mem : comp ∈ r.yield := List.mem_of_getElem? hcomp + cases revPref with + | nil => simp at hα + | cons atom rest => + cases atom with + | tm _ => simp [atomToFeat] at hα + | var i j => + have hsplit' : comp = rest.reverse ++ (MCFGAtom.var i j :: suf) := by + simpa [List.reverse_cons, List.append_assoc] using hsplit + have hv_in : (i, j) ∈ r.varOccurrences := by + simp only [MCFGRule.varOccurrences, List.mem_flatMap, List.mem_filterMap] + refine ⟨comp, hcomp_mem, MCFGAtom.var i j, ?_, rfl⟩ + rw [hsplit']; exact List.mem_append_right _ (List.mem_cons_self ..) + rcases var_index_lt_two hwf (hrank r hr_mem) hv_in with rfl | rfl + · -- i = 0 + simp only [List.map_cons, atomToFeat, List.cons_append, List.cons.injEq, + MGFeature.licensor.injEq] at hα + obtain ⟨rfl, rfl⟩ := hα + have ⟨_, ht_eq, hrem⟩ := exactMap_remove hex + have hex' : ExactMap (ms1 ++ ms2) (buildDom r k rest) (ruleVal r args) := + exactMap_ext hrem (buildDom_step_var0 hwf.2.1 hcomp hsplit) (fun _ _ => rfl) + rw [ht_eq] + exact MGInv.buildActive hrid hcomp hsplit' rfl hyl hex' + · -- i = 1 + simp only [List.map_cons, atomToFeat, List.cons_append, List.cons.injEq, + MGFeature.licensor.injEq] at hα + obtain ⟨rfl, rfl⟩ := hα + have ⟨_, ht_eq, hrem⟩ := exactMap_remove hex + have hex' : ExactMap (ms1 ++ ms2) (buildDom r k rest) (ruleVal r args) := + exactMap_ext hrem (buildDom_step_var1 hwf.2.1 hcomp hsplit) (fun _ _ => rfl) + rw [ht_eq] + exact MGInv.buildActive hrid hcomp hsplit' rfl hyl hex' + | @copyLiftMid rid k r side tup _ hrid hk hy hex => + have ⟨_, ht_eq, hrem⟩ := exactMap_remove hex + rw [ht_eq] + simpa using MGInv.copiedReady hrid hk hy hrem + | @move2 s t f f' γ δ' ms1 ms2 h1 hsmcNew ih1 => + exact False.elim (singleMover_no_move2 ih1.singleMover) + +theorem mcfg_of_binMCFGToMG_lang {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) {w : List T} + (h : (binMCFGToMG G).Lang w) : G.Lang w := by + obtain ⟨b, hder⟩ := h + have hinv := binMCFGToMG_sound hrank hder + cases hinv with + | startDone hlang => exact hlang + | buildActive _ _ _ hα _ _ => exact absurd hα.symm buildActive_feats_ne_singleton + +/-- Weak equivalence for any rank-≤-2 Linear Non-Erasing MCFG. -/ +theorem binMCFGToMG_lang {G : MCFG N T} + (hrank : ∀ r, r ∈ G.rules → r.rhs.length ≤ 2) (w : List T) : + (binMCFGToMG G).Lang w ↔ G.Lang w := + ⟨mcfg_of_binMCFGToMG_lang hrank, binMCFGToMG_lang_of_mcfg hrank⟩ + +/-! ### Part 6: General `MCFG → MG` Theorem (Arbitrary Rank; Michaelis 2001 / Harkema 2001) -/ + +/-- The Minimalist Grammar weakly equivalent to ANY finite Linear Non-Erasing MCFG `G` + (of arbitrary rank `k`), obtained by binarizing `G` and compiling via the 3-bank compiler. -/ +def mcfgToMG (G : MCFG N T) : MG (MGBase (BinMCFGNT N) T) MGLic T := + binMCFGToMG (BinMCFG.binarizeMCFG G) + +/-- **Harkema (2001) / Michaelis (2001) — Direction 2 (`MCFG → MG`)**: + Every finite Linear Non-Erasing MCFG (LCFRS) has a weakly equivalent Minimalist Grammar. -/ +theorem mcfgToMG_lang (G : MCFG N T) (w : List T) : + (mcfgToMG G).Lang w ↔ G.Lang w := by + unfold mcfgToMG + rw [binMCFGToMG_lang (BinMCFG.binarizeMCFG_rank_le_two G) w, BinMCFG.binarizeMCFG_lang G w] + +end MCFGtoMG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/MG.lean b/LeanPool/FormalLinguistics/MG.lean new file mode 100644 index 0000000000..0f6511c985 --- /dev/null +++ b/LeanPool/FormalLinguistics/MG.lean @@ -0,0 +1,226 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import Init + +/-! + Chain-Based Minimalist Grammars (Stabler 1997; Stabler & Keenan 2003) + + Canonical algebraic formalization of Chomsky's Minimalist Program: + • Syntactic features: category `x`, selector `=x`, licensor `+f`, licensee `-f`. + • Expressions: `(isLex, headChain, movers)` obeying the Shortest Move Constraint (SMC). + • Structure-building operations: `lex`, `merge1`, `merge2`, `merge3`, `move1`, `move2`. + + The SMC is built into the rules as an invariant of every derived expression. + Stabler & Keenan impose it on `move` only; `MGOriginal.lean` states their rules + literally and proves that both presentations generate the same languages. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Minimalist syntactic features over base categories `Base` and movement features `Lic`. -/ +inductive MGFeature (Base Lic : Type) where + | cat : Base → MGFeature Base Lic -- `x` (syntactic category) + | sel : Base → MGFeature Base Lic -- `=x` (selector) + | licensor : Lic → MGFeature Base Lic -- `+f` (movement attractor) + | licensee : Lic → MGFeature Base Lic -- `-f` (movement licensee) + deriving DecidableEq, Repr + +/-- A syntactic chain pairing a phonetic string with its remaining feature stack. -/ +structure MGChain (Base Lic T : Type) where + /-- Terminal string carried by the chain. -/ + str : List T + /-- Remaining ordered feature sequence. -/ + feats : List (MGFeature Base Lic) + deriving DecidableEq, Repr + +/-- A Minimalist Grammar expression: + `isLex = true` denotes a lexical item (`::` in Stabler & Keenan's notation), + `isLex = false` denotes a derived expression (`:`), + `head` is the main chain, and `movers` are pending displaced chains. -/ +structure MGExpr (Base Lic T : Type) where + /-- Whether the expression is a lexical item rather than the result of a rule. -/ + isLex : Bool + /-- Head chain of the expression. -/ + head : MGChain Base Lic T + /-- Chains waiting to discharge licensee features by movement. -/ + movers : List (MGChain Base Lic T) + deriving DecidableEq, Repr + +/-- Extract the leading licensee feature `f` if a chain begins with `licensee f`. -/ +def MGChain.headLic {Base Lic T : Type} (c : MGChain Base Lic T) : Option Lic := + match c.feats with + | MGFeature.licensee f :: _ => some f + | _ => none + +/-- Shortest Move Constraint (SMC) & mover well-formedness: + every mover starts with a licensee feature `-f`, and all leading licensee features + among active movers are pairwise distinct. -/ +def SMC {Base Lic T : Type} (ms : List (MGChain Base Lic T)) : Prop := + (∀ c, c ∈ ms → ∃ f δ, c.feats = MGFeature.licensee f :: δ) ∧ + (ms.filterMap MGChain.headLic).Nodup + +/-- A finite Minimalist Grammar over base categories `Base`, movement features `Lic`, + and terminal alphabet `T`. -/ +structure MG (Base Lic T : Type) where + /-- Category of complete expressions. -/ + start : Base + /-- Finite list of lexical strings paired with nonempty feature sequences. -/ + lexicon : List (List T × List (MGFeature Base Lic)) + lex_nonempty : ∀ entry, entry ∈ lexicon → entry.2 ≠ [] + +namespace MG + +variable {Base Lic T : Type} + +/-- Derivable expressions of a Minimalist Grammar via Stabler & Keenan's (2003) + five structure-building rules (`merge1`, `merge2`, `merge3`, `move1`, `move2`) + plus lexical insertion (`lex`). -/ +inductive Derives (G : MG Base Lic T) : MGExpr Base Lic T → Prop where + /-- Lexical insertion: `(w, α) ∈ G.lexicon` yields a lexical (`isLex = true`) expression. -/ + | lex {w : List T} {α : List (MGFeature Base Lic)} : + (w, α) ∈ G.lexicon → + Derives G ⟨true, ⟨w, α⟩, []⟩ + + /-- Merge 1 (complement of a lexical head, right-adjoined: `s ++ t`). -/ + | merge1 {s t : List T} {x : Base} {γ : List (MGFeature Base Lic)} + {b : Bool} {ms : List (MGChain Base Lic T)} : + Derives G ⟨true, ⟨s, MGFeature.sel x :: γ⟩, []⟩ → + Derives G ⟨b, ⟨t, [MGFeature.cat x]⟩, ms⟩ → + Derives G ⟨false, ⟨s ++ t, γ⟩, ms⟩ + + /-- Merge 2 (specifier of a derived head, left-adjoined: `t ++ s`). -/ + | merge2 {s t : List T} {x : Base} {γ : List (MGFeature Base Lic)} + {b : Bool} {ms1 ms2 : List (MGChain Base Lic T)} : + Derives G ⟨false, ⟨s, MGFeature.sel x :: γ⟩, ms1⟩ → + Derives G ⟨b, ⟨t, [MGFeature.cat x]⟩, ms2⟩ → + SMC (ms1 ++ ms2) → + Derives G ⟨false, ⟨t ++ s, γ⟩, ms1 ++ ms2⟩ + + /-- Merge 3 (merging a phrase with remaining features `δ = licensee f :: δ'`; becomes a mover). -/ + | merge3 {s t : List T} {x : Base} {f : Lic} + {γ δ' : List (MGFeature Base Lic)} + {b1 b2 : Bool} {ms1 ms2 : List (MGChain Base Lic T)} : + Derives G ⟨b1, ⟨s, MGFeature.sel x :: γ⟩, ms1⟩ → + Derives G ⟨b2, ⟨t, MGFeature.cat x :: MGFeature.licensee f :: δ'⟩, ms2⟩ → + SMC (ms1 ++ ⟨t, MGFeature.licensee f :: δ'⟩ :: ms2) → + Derives G ⟨false, ⟨s, γ⟩, ms1 ++ ⟨t, MGFeature.licensee f :: δ'⟩ :: ms2⟩ + + /-- Move 1 (final landing of a mover checking its last feature `-f`, left-adjoined: `t ++ s`). -/ + | move1 {s t : List T} {f : Lic} {γ : List (MGFeature Base Lic)} + {ms1 ms2 : List (MGChain Base Lic T)} : + Derives G ⟨false, ⟨s, MGFeature.licensor f :: γ⟩, + ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2⟩ → + Derives G ⟨false, ⟨t ++ s, γ⟩, ms1 ++ ms2⟩ + + /-- Move 2 (non-final movement: `-f` checked, mover retains `licensee f' :: δ'`). -/ + | move2 {s t : List T} {f f' : Lic} {γ δ' : List (MGFeature Base Lic)} + {ms1 ms2 : List (MGChain Base Lic T)} : + Derives G ⟨false, ⟨s, MGFeature.licensor f :: γ⟩, + ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2⟩ → + SMC (ms1 ++ ⟨t, MGFeature.licensee f' :: δ'⟩ :: ms2) → + Derives G ⟨false, ⟨s, γ⟩, ms1 ++ ⟨t, MGFeature.licensee f' :: δ'⟩ :: ms2⟩ + +/-- The string language generated by a Minimalist Grammar: + all strings `w` derivable as a complete `G.start` expression with no remaining movers. -/ +def Lang (G : MG Base Lic T) (w : List T) : Prop := + ∃ b, Derives G ⟨b, ⟨w, [MGFeature.cat G.start]⟩, []⟩ + +/-- Helper: removing one element preserves `SMC`. -/ +theorem smc_remove {ms1 ms2 : List (MGChain Base Lic T)} {c : MGChain Base Lic T} + (h : SMC (ms1 ++ c :: ms2)) : SMC (ms1 ++ ms2) := by + obtain ⟨hall, hnd⟩ := h + refine ⟨?_, ?_⟩ + · intro x hx + apply hall x + rcases List.mem_append.mp hx with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem c h2) + · simp only [List.filterMap_append, List.filterMap_cons] at hnd ⊢ + cases hc : c.headLic with + | none => simpa [hc] using hnd + | some f => + rw [hc] at hnd + exact List.Nodup.sublist (List.Sublist.append_left (List.sublist_cons_self f _) _) hnd + +/-- Every derivable MG expression satisfies the Shortest Move Constraint (`SMC`). -/ +theorem Derives.smc {G : MG Base Lic T} {e : MGExpr Base Lic T} (h : Derives G e) : + SMC e.movers := by + induction h with + | lex _ => + exact ⟨fun _ h => by simp at h, List.nodup_nil⟩ + | merge1 _ _ _ ih2 => exact ih2 + | merge2 _ _ hsmc _ _ => exact hsmc + | merge3 _ _ hsmc _ _ => exact hsmc + | move1 _ ih => exact smc_remove ih + | move2 _ hsmc _ => exact hsmc + +/-- Every chain in a derivable MG expression carries a suffix of some lexical feature list. -/ +def isSuffix {α : Type} (s l : List α) : Prop := + ∃ p, p ++ s = l + +theorem isSuffix_refl {α : Type} (l : List α) : isSuffix l l := + ⟨[], rfl⟩ + +theorem isSuffix_tail {α : Type} {a : α} {s l : List α} (h : isSuffix (a :: s) l) : + isSuffix s l := by + obtain ⟨p, hp⟩ := h + exact ⟨p ++ [a], by simpa [List.append_assoc] using hp⟩ + +/-- Sub-suffix property of Minimalist Grammars: + both the head feature stack and every mover's feature stack are suffixes of + feature lists occurring in `G.lexicon`. -/ +theorem Derives.feats_suffix {G : MG Base Lic T} {e : MGExpr Base Lic T} (h : Derives G e) : + (∃ entry, entry ∈ G.lexicon ∧ isSuffix e.head.feats entry.2) ∧ + (∀ c, c ∈ e.movers → ∃ entry, entry ∈ G.lexicon ∧ isSuffix c.feats entry.2) := by + induction h with + | @lex w α hlex => + exact ⟨⟨(w, α), hlex, isSuffix_refl α⟩, fun _ hm => by simp at hm⟩ + | merge1 _ _ ih1 ih2 => + obtain ⟨⟨e1, he1, hs1⟩, _⟩ := ih1 + exact ⟨⟨e1, he1, isSuffix_tail hs1⟩, ih2.2⟩ + | merge2 _ _ _ ih1 ih2 => + obtain ⟨⟨e1, he1, hs1⟩, hm1⟩ := ih1 + refine ⟨⟨e1, he1, isSuffix_tail hs1⟩, ?_⟩ + intro c hc + rcases List.mem_append.mp hc with h1 | h2 + · exact hm1 c h1 + · exact ih2.2 c h2 + | merge3 _ _ _ ih1 ih2 => + obtain ⟨⟨e1, he1, hs1⟩, hm1⟩ := ih1 + obtain ⟨⟨e2, he2, hs2⟩, hm2⟩ := ih2 + refine ⟨⟨e1, he1, isSuffix_tail hs1⟩, ?_⟩ + intro c hc + rcases List.mem_append.mp hc with h1 | h2 + · exact hm1 c h1 + · rcases List.mem_cons.mp h2 with rfl | h2' + · exact ⟨e2, he2, isSuffix_tail hs2⟩ + · exact hm2 c h2' + | move1 _ ih => + obtain ⟨⟨e1, he1, hs1⟩, hm⟩ := ih + refine ⟨⟨e1, he1, isSuffix_tail hs1⟩, ?_⟩ + intro c hc + apply hm c + rcases List.mem_append.mp hc with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2) + | move2 _ _ ih => + obtain ⟨⟨e1, he1, hs1⟩, hm⟩ := ih + refine ⟨⟨e1, he1, isSuffix_tail hs1⟩, ?_⟩ + intro c hc + rcases List.mem_append.mp hc with h1 | h2 + · exact hm c (List.mem_append_left _ h1) + · rcases List.mem_cons.mp h2 with rfl | h2' + · obtain ⟨e2, he2, hs2⟩ := hm _ (List.mem_append_right _ (List.mem_cons_self ..)) + exact ⟨e2, he2, isSuffix_tail hs2⟩ + · exact hm c (List.mem_append_right _ (List.mem_cons_of_mem _ h2')) + +end MG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/MGMCFGEquiv.lean b/LeanPool/FormalLinguistics/MGMCFGEquiv.lean new file mode 100644 index 0000000000..4d78ae669a --- /dev/null +++ b/LeanPool/FormalLinguistics/MGMCFGEquiv.lean @@ -0,0 +1,472 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.MGtoMCFG +public import LeanPool.FormalLinguistics.MCFGtoMG + +/-! + Michaelis (1998, 2001) & Harkema (2001) Equivalence Theorem + + Main machine-checked result: + The class of languages generated by finite chain-based Minimalist Grammars + (Stabler 1997; Stabler & Keenan 2003) coincides exactly with the class of + languages generated by finite Linear Non-Erasing Multiple Context-Free + Grammars / Linear Context-Free Rewriting Systems (Seki et al. 1991; + Vijay-Shanker, Weir & Joshi 1987): + + L(MG) = L(MCFG / LCFRS). + + Also includes a verified mildly context-sensitive (non-context-free) + cross-serial dependency witness: + • `abcMCFG`: a 3-rule 3-dimensional MCFG whose exact language is + `{ a^n b^n c^n | n ≥ 1 }`, automatically compiled to an equivalent MG + `abcCompiledMG = MCFGtoMG.mcfgToMG abcMCFG`. + • `abcDirectMG`: a 9-item hand-crafted Minimalist Grammar generating + `a^n b^n c^n` for all `n ≥ 1`, automatically compiled to an equivalent + MCFG `abcCompiledMCFG = MGtoMCFG.mgToMCFG abcDirectMG`. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-! ### Part 1: Main Weak Equivalence Theorems (`L(MG) = L(MCFG)`) -/ + +/-- A language `L` over terminal alphabet `T` is generated by a finite Minimalist Grammar + with decidable syntactic feature equality. -/ +def IsDecMGLang {T : Type} (L : List T → Prop) : Prop := + ∃ (Base Lic : Type) (_ : DecidableEq Base) (_ : DecidableEq Lic) + (G : MG Base Lic T), ∀ w, G.Lang w ↔ L w + +/-- A language `L` over terminal alphabet `T` is generated by a finite Linear Non-Erasing MCFG + with decidable nonterminal equality. -/ +def IsDecMCFGLang {T : Type} (L : List T → Prop) : Prop := + ∃ (N : Type) (_ : DecidableEq N) (G : MCFG N T), ∀ w, G.Lang w ↔ L w + +/-- **Decidable-Alphabet Michaelis–Harkema Equivalence Theorem**: + For any decidable terminal alphabet `T`, a language is generated by a finite + Minimalist Grammar (with decidable feature equality) iff it is generated by a + finite Linear Non-Erasing MCFG (LCFRS) (with decidable nonterminal equality). -/ +theorem michaelis_harkema_equivalence_decidable {T : Type} [DecidableEq T] + (L : List T → Prop) : + IsDecMGLang L ↔ IsDecMCFGLang L := by + constructor + · rintro ⟨Base, Lic, hB, hL, G, hG⟩ + refine ⟨MGMCFGNT Base Lic, inferInstance, MGtoMCFG.mgToMCFG G, ?_⟩ + intro w + rw [MGtoMCFG.mgToMCFG_lang G w, hG w] + · rintro ⟨N, hN, G, hG⟩ + refine ⟨MCFGtoMG.MGBase (BinMCFGNT N) T, MCFGtoMG.MGLic, inferInstance, inferInstance, + MCFGtoMG.mcfgToMG G, ?_⟩ + intro w + rw [MCFGtoMG.mcfgToMG_lang G w, hG w] + +/-- General language class of finite Minimalist Grammars over an arbitrary alphabet `T`. -/ +def IsMGLang {T : Type} (L : List T → Prop) : Prop := + ∃ (Base Lic : Type) (G : MG Base Lic T), ∀ w, G.Lang w ↔ L w + +/-- General language class of finite Linear Non-Erasing MCFGs (LCFRSs) over an arbitrary alphabet `T`. -/ +def IsMCFGLang {T : Type} (L : List T → Prop) : Prop := + ∃ (N : Type) (G : MCFG N T), ∀ w, G.Lang w ↔ L w + +/-- **Michaelis–Harkema Equivalence Theorem** (`L(MG) = L(MCFG)` over any alphabet `T`): + Every Minimalist Grammar language is an MCFG/LCFRS language (Michaelis 1998, 2001), + and every MCFG/LCFRS language is a Minimalist Grammar language (Harkema 2001; Michaelis 2001). -/ +theorem michaelis_harkema_equivalence {T : Type} (L : List T → Prop) : + IsMGLang L ↔ IsMCFGLang L := by + constructor + · rintro ⟨Base, Lic, G, hG⟩ + letI : DecidableEq Base := Classical.typeDecidableEq Base + letI : DecidableEq Lic := Classical.typeDecidableEq Lic + refine ⟨MGMCFGNT Base Lic, MGtoMCFG.mgToMCFG G, ?_⟩ + intro w + rw [MGtoMCFG.mgToMCFG_lang G w, hG w] + · rintro ⟨N, G, hG⟩ + refine ⟨MCFGtoMG.MGBase (BinMCFGNT N) T, MCFGtoMG.MGLic, MCFGtoMG.mcfgToMG G, ?_⟩ + intro w + rw [MCFGtoMG.mcfgToMG_lang G w, hG w] + +/-! ### Part 2: Verified Cross-Serial Dependency Example (`{ a^n b^n c^n | n ≥ 1 }`) -/ + +namespace CrossSerialExample + +/-- Three-symbol terminal alphabet `{a, b, c}`. -/ +inductive ABCTerm where + | a | b | c + deriving DecidableEq, Repr + +/-- The non-context-free copy-count language `{ a^n b^n c^n | n ≥ 1 }`. -/ +def abcWord (n : Nat) : List ABCTerm := + List.replicate n .a ++ List.replicate n .b ++ List.replicate n .c + +/-- The language of equal positive runs of a, b, and c in that order. -/ +def ABCLang (w : List ABCTerm) : Prop := + ∃ n, 1 ≤ n ∧ w = abcWord n + +/-! #### 2A. Exact 3-Rule MCFG for `{ a^n b^n c^n | n ≥ 1 }` and Its Compiled MG -/ + +/-- Nonterminals for complete words and for their three separate components. -/ +inductive ABCNT where + | S -- dim 1: full sentence `a^n b^n c^n` + | T -- dim 3: triple `(a^n, b^n, c^n)` + deriving DecidableEq, Repr + +/-- The sentence symbol yields one component and the counting symbol yields three. -/ +def abcDim : ABCNT → Nat + | .S => 1 + | .T => 3 + +/-- Concatenate the three letter runs into a sentence. -/ +def rJoin : MCFGRule ABCNT ABCTerm := + { lhs := .S + rhs := [.T] + yield := [[.var 0 0, .var 0 1, .var 0 2]] } + +/-- Start the derivation with three runs of length one. -/ +def rBase : MCFGRule ABCNT ABCTerm := + { lhs := .T + rhs := [] + yield := [[.tm .a], [.tm .b], [.tm .c]] } + +/-- Extend each of the three runs by one letter. -/ +def rStep : MCFGRule ABCNT ABCTerm := + { lhs := .T + rhs := [.T] + yield := [[.tm .a, .var 0 0], [.tm .b, .var 0 1], [.tm .c, .var 0 2]] } + +theorem abcMCFG_rules_wf : + ∀ r, r ∈ [rJoin, rBase, rStep] → r.WellFormed abcDim := by + intro r hr + simp only [List.mem_cons, List.not_mem_nil, or_false] at hr + rcases hr with rfl | rfl | rfl + · refine ⟨rfl, by simp [MCFGRule.isLinear, MCFGRule.varOccurrences, rJoin], ?_⟩ + intro i j + simp only [rJoin, MCFGRule.varOccurrences, List.flatMap_cons, List.flatMap_nil, + List.filterMap_cons, List.filterMap_nil, List.append_nil, List.mem_cons, + List.not_mem_nil, or_false, Prod.mk.injEq] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) + · exact ⟨.T, rfl, by decide⟩ + · exact ⟨.T, rfl, by decide⟩ + · exact ⟨.T, rfl, by decide⟩ + · rintro ⟨B, hB, hj⟩ + cases i with + | zero => + simp at hB; subst hB; simp [abcDim] at hj + omega + | succ _ => simp at hB + · refine ⟨rfl, by simp [MCFGRule.isLinear, MCFGRule.varOccurrences, rBase], ?_⟩ + intro i j + simp [rBase, MCFGRule.varOccurrences] + · refine ⟨rfl, by simp [MCFGRule.isLinear, MCFGRule.varOccurrences, rStep], ?_⟩ + intro i j + simp only [rStep, MCFGRule.varOccurrences, List.flatMap_cons, List.flatMap_nil, + List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.append_nil, List.mem_cons, List.not_mem_nil, or_false, Prod.mk.injEq] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) + · exact ⟨.T, rfl, by decide⟩ + · exact ⟨.T, rfl, by decide⟩ + · exact ⟨.T, rfl, by decide⟩ + · rintro ⟨B, hB, hj⟩ + cases i with + | zero => + simp at hB; subst hB; simp [abcDim] at hj + omega + | succ _ => simp at hB + +/-- 3-rule Linear Non-Erasing MCFG generating exactly `{ a^n b^n c^n | n ≥ 1 }`. -/ +def abcMCFG : MCFG ABCNT ABCTerm where + start := .S + dim := abcDim + dim_pos := fun A => by cases A <;> simp [abcDim] + dim_start := rfl + rules := [rJoin, rBase, rStep] + rules_wf := abcMCFG_rules_wf + +/-- Semantic invariant characterizing every tuple yielded by `abcMCFG`. -/ +def abcInterp : ABCNT → List (List ABCTerm) → Prop + | .S, tup => ∃ n, 1 ≤ n ∧ tup = [abcWord n] + | .T, tup => ∃ n, 1 ≤ n ∧ tup = [List.replicate n .a, List.replicate n .b, List.replicate n .c] + +/-- Interpret a list of example nonterminals by tuples of the expected shape. -/ +inductive ABCInterpList : List ABCNT → List (List (List ABCTerm)) → Prop where + | nil : ABCInterpList [] [] + | cons {A As tup tups} : + abcInterp A tup → ABCInterpList As tups → ABCInterpList (A :: As) (tup :: tups) + +mutual + theorem abcMCFG_sound {A : ABCNT} {tup : List (List ABCTerm)} : + MCFG.Yield abcMCFG A tup → abcInterp A tup + | MCFG.Yield.rule hr hargs_raw => by + have hargs := abcMCFG_sound_list hargs_raw + change _ ∈ [rJoin, rBase, rStep] at hr + simp only [List.mem_cons, List.not_mem_nil, or_false] at hr + rcases hr with rfl | rfl | rfl + · cases hargs with + | cons hT hnil => + cases hnil + obtain ⟨n, hn, rfl⟩ := hT + exact ⟨n, hn, by simp [rJoin, MCFG.evalYield, MCFG.evalComp, abcWord, List.append_assoc]⟩ + · cases hargs + exact ⟨1, Nat.le_refl 1, by simp [rBase, MCFG.evalYield, MCFG.evalComp]⟩ + · cases hargs with + | cons hT hnil => + cases hnil + obtain ⟨n, hn, rfl⟩ := hT + exact ⟨n + 1, by omega, by simp [rStep, MCFG.evalYield, MCFG.evalComp, List.replicate_succ]⟩ + + theorem abcMCFG_sound_list {As : List ABCNT} {args : List (List (List ABCTerm))} : + MCFG.YieldList abcMCFG As args → ABCInterpList As args + | MCFG.YieldList.nil => ABCInterpList.nil + | MCFG.YieldList.cons hy hrest => ABCInterpList.cons (abcMCFG_sound hy) (abcMCFG_sound_list hrest) +end + +theorem abcMCFG_T_complete : + ∀ n, 1 ≤ n → + MCFG.Yield abcMCFG .T [List.replicate n .a, List.replicate n .b, List.replicate n .c] := by + intro n + induction n with + | zero => intro h; omega + | succ k ih => + intro _ + cases k with + | zero => + have hr : rBase ∈ abcMCFG.rules := by simp [abcMCFG] + simpa [rBase, MCFG.evalYield, MCFG.evalComp] using MCFG.Yield.rule hr MCFG.YieldList.nil + | succ k' => + have hprev := ih (by omega) + have hr : rStep ∈ abcMCFG.rules := by simp [abcMCFG] + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons hprev MCFG.YieldList.nil) + simpa [rStep, MCFG.evalYield, MCFG.evalComp, List.replicate_succ] using hy + +/-- Exact language theorem for `abcMCFG`: `L(abcMCFG) = { a^n b^n c^n | n ≥ 1 }`. -/ +theorem abcMCFG_lang_iff (w : List ABCTerm) : + abcMCFG.Lang w ↔ ABCLang w := by + constructor + · intro h + obtain ⟨n, hn, heq⟩ := abcMCFG_sound h + simp at heq + exact ⟨n, hn, heq⟩ + · rintro ⟨n, hn, rfl⟩ + have hT := abcMCFG_T_complete n hn + have hr : rJoin ∈ abcMCFG.rules := by simp [abcMCFG] + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons hT MCFG.YieldList.nil) + change MCFG.Yield abcMCFG .S [abcWord n] + simpa [rJoin, MCFG.evalYield, MCFG.evalComp, abcWord, List.append_assoc] using hy + +/-- Automatically compiled Minimalist Grammar for `{ a^n b^n c^n | n ≥ 1 }` via `MCFGtoMG.mcfgToMG`. -/ +def abcCompiledMG := MCFGtoMG.mcfgToMG abcMCFG + +/-- Exact language theorem transferred automatically to `abcCompiledMG`. -/ +theorem abcCompiledMG_lang_iff (w : List ABCTerm) : + abcCompiledMG.Lang w ↔ ABCLang w := by + rw [abcCompiledMG, MCFGtoMG.mcfgToMG_lang abcMCFG w, abcMCFG_lang_iff w] + +/-- Concrete witness: `"aabbcc"` is generated by `abcCompiledMG`. -/ +theorem aabbcc_in_abcCompiledMG : + abcCompiledMG.Lang [.a, .a, .b, .b, .c, .c] := + (abcCompiledMG_lang_iff _).mpr ⟨2, by omega, rfl⟩ + +/-! #### 2B. Hand-Crafted 9-Item Minimalist Grammar for `{ a^n b^n c^n | n ≥ 1 }` and Its Compiled MCFG -/ + +/-- Categories for the sentence, the counting loop, and the movement stages. -/ +inductive ABCBase where + | Start | Loop | C0 | B0 | A0 | S1 | S2 | S3 + deriving DecidableEq, Repr + +/-- Licensee features tracking the three letter runs. -/ +inductive ABCLic where + | fa | fb | fc + deriving DecidableEq, Repr + +/-- Lexical items for the direct minimalist derivation of three equal letter runs. -/ +def abcDirectLexicon : List (List ABCTerm × List (MGFeature ABCBase ABCLic)) := + [ ([.c], [.cat .C0, .licensee .fc]), + ([.b], [.sel .C0, .cat .B0, .licensee .fb]), + ([.a], [.sel .B0, .cat .A0, .licensee .fa]), + ([], [.sel .A0, .cat .Loop]), + ([.c], [.sel .Loop, .licensor .fc, .cat .S1, .licensee .fc]), + ([.b], [.sel .S1, .licensor .fb, .cat .S2, .licensee .fb]), + ([.a], [.sel .S2, .licensor .fa, .cat .S3, .licensee .fa]), + ([], [.sel .S3, .cat .Loop]), + ([], [.sel .Loop, .licensor .fc, .licensor .fb, .licensor .fa, .cat .Start]) ] + +/-- Direct 9-item Minimalist Grammar generating `{ a^n b^n c^n | n ≥ 1 }`. -/ +def abcDirectMG : MG ABCBase ABCLic ABCTerm where + start := .Start + lexicon := abcDirectLexicon + lex_nonempty := by + intro e he + simp only [abcDirectLexicon, List.mem_cons, List.not_mem_nil, or_false] at he + rcases he with rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl <;> simp + +theorem replicate_append_singleton {α : Type} (n : Nat) (x : α) : + List.replicate n x ++ [x] = List.replicate (n + 1) x := by + induction n with + | zero => rfl + | succ k ih => simp [List.replicate_succ, ih] + +theorem abcDirectMG_loop : + ∀ n, 1 ≤ n → + MG.Derives abcDirectMG + ⟨false, ⟨[], [.cat .Loop]⟩, + [⟨List.replicate n .a, [.licensee .fa]⟩, + ⟨List.replicate n .b, [.licensee .fb]⟩, + ⟨List.replicate n .c, [.licensee .fc]⟩]⟩ := by + intro n + induction n with + | zero => intro h; omega + | succ k ih => + intro _ + cases k with + | zero => + -- Base case n = 1 + have hC0 : MG.Derives abcDirectMG ⟨true, ⟨[.c], [.cat .C0, .licensee .fc]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + have hB0lex : MG.Derives abcDirectMG ⟨true, ⟨[.b], [.sel .C0, .cat .B0, .licensee .fb]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + have hB0 : MG.Derives abcDirectMG + ⟨false, ⟨[.b], [.cat .B0, .licensee .fb]⟩, [⟨[.c], [.licensee .fc]⟩]⟩ := + MG.Derives.merge3 hB0lex hC0 ⟨by intro c hc; simp at hc; subst hc; exact ⟨.fc, [], rfl⟩, by decide⟩ + have hA0lex : MG.Derives abcDirectMG ⟨true, ⟨[.a], [.sel .B0, .cat .A0, .licensee .fa]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + have hA0 : MG.Derives abcDirectMG + ⟨false, ⟨[.a], [.cat .A0, .licensee .fa]⟩, + [⟨[.b], [.licensee .fb]⟩, ⟨[.c], [.licensee .fc]⟩]⟩ := + MG.Derives.merge3 hA0lex hB0 + ⟨by intro c hc; simp at hc; rcases hc with rfl | rfl; exact ⟨.fb, [], rfl⟩; exact ⟨.fc, [], rfl⟩, + by decide⟩ + have hLlex : MG.Derives abcDirectMG ⟨true, ⟨[], [.sel .A0, .cat .Loop]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + exact MG.Derives.merge3 hLlex hA0 + ⟨by intro c hc; simp at hc; rcases hc with rfl | rfl | rfl + · exact ⟨.fa, [], rfl⟩ + · exact ⟨.fb, [], rfl⟩ + · exact ⟨.fc, [], rfl⟩, + by decide⟩ + | succ k' => + -- Inductive step: n = k' + 1 → n + 1 + let m := k' + 1 + have hprev := ih (by omega) + -- 1. Advance c^m → c^{m+1} + have hS1lex : MG.Derives abcDirectMG + ⟨true, ⟨[.c], [.sel .Loop, .licensor .fc, .cat .S1, .licensee .fc]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + have hS1a : MG.Derives abcDirectMG + ⟨false, ⟨[.c], [.licensor .fc, .cat .S1, .licensee .fc]⟩, + [⟨List.replicate m .a, [.licensee .fa]⟩, + ⟨List.replicate m .b, [.licensee .fb]⟩] ++ + ⟨List.replicate m .c, [.licensee .fc]⟩ :: []⟩ := by + simpa [m] using MG.Derives.merge1 hS1lex hprev + have hS1 : MG.Derives abcDirectMG + ⟨false, ⟨List.replicate (m + 1) .c, [.cat .S1, .licensee .fc]⟩, + [⟨List.replicate m .a, [.licensee .fa]⟩, + ⟨List.replicate m .b, [.licensee .fb]⟩]⟩ := by + simpa [replicate_append_singleton] using MG.Derives.move1 hS1a + -- 2. Advance b^m → b^{m+1} + have hS2lex : MG.Derives abcDirectMG + ⟨true, ⟨[.b], [.sel .S1, .licensor .fb, .cat .S2, .licensee .fb]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + have hS2a : MG.Derives abcDirectMG + ⟨false, ⟨[.b], [.licensor .fb, .cat .S2, .licensee .fb]⟩, + [⟨List.replicate (m + 1) .c, [.licensee .fc]⟩, + ⟨List.replicate m .a, [.licensee .fa]⟩] ++ + ⟨List.replicate m .b, [.licensee .fb]⟩ :: []⟩ := by + have h3 := MG.Derives.merge3 hS2lex hS1 + ⟨by intro c hc; simp at hc; rcases hc with rfl | rfl | rfl + · exact ⟨.fc, [], rfl⟩ + · exact ⟨.fa, [], rfl⟩ + · exact ⟨.fb, [], rfl⟩, + by simp [MGChain.headLic]⟩ + simpa using h3 + have hS2 : MG.Derives abcDirectMG + ⟨false, ⟨List.replicate (m + 1) .b, [.cat .S2, .licensee .fb]⟩, + [⟨List.replicate (m + 1) .c, [.licensee .fc]⟩, + ⟨List.replicate m .a, [.licensee .fa]⟩]⟩ := by + simpa [replicate_append_singleton] using MG.Derives.move1 hS2a + -- 3. Advance a^m → a^{m+1} + have hS3lex : MG.Derives abcDirectMG + ⟨true, ⟨[.a], [.sel .S2, .licensor .fa, .cat .S3, .licensee .fa]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + have hS3a : MG.Derives abcDirectMG + ⟨false, ⟨[.a], [.licensor .fa, .cat .S3, .licensee .fa]⟩, + [⟨List.replicate (m + 1) .b, [.licensee .fb]⟩, + ⟨List.replicate (m + 1) .c, [.licensee .fc]⟩] ++ + ⟨List.replicate m .a, [.licensee .fa]⟩ :: []⟩ := by + have h3 := MG.Derives.merge3 hS3lex hS2 + ⟨by intro c hc; simp at hc; rcases hc with rfl | rfl | rfl + · exact ⟨.fb, [], rfl⟩ + · exact ⟨.fc, [], rfl⟩ + · exact ⟨.fa, [], rfl⟩, + by simp [MGChain.headLic]⟩ + simpa using h3 + have hS3 : MG.Derives abcDirectMG + ⟨false, ⟨List.replicate (m + 1) .a, [.cat .S3, .licensee .fa]⟩, + [⟨List.replicate (m + 1) .b, [.licensee .fb]⟩, + ⟨List.replicate (m + 1) .c, [.licensee .fc]⟩]⟩ := by + simpa [replicate_append_singleton] using MG.Derives.move1 hS3a + -- 4. Park a^{m+1} and close loop + have hLlex : MG.Derives abcDirectMG ⟨true, ⟨[], [.sel .S3, .cat .Loop]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + exact MG.Derives.merge3 hLlex hS3 + ⟨by intro c hc; simp at hc; rcases hc with rfl | rfl | rfl + · exact ⟨.fa, [], rfl⟩ + · exact ⟨.fb, [], rfl⟩ + · exact ⟨.fc, [], rfl⟩, + by simp [MGChain.headLic]⟩ + +/-- Every word `a^n b^n c^n` (`n ≥ 1`) is generated by the direct 9-item Minimalist Grammar. -/ +theorem abcDirectMG_generates_all (n : Nat) (hn : 1 ≤ n) : + abcDirectMG.Lang (abcWord n) := by + have hLoop := abcDirectMG_loop n hn + have hFinLex : MG.Derives abcDirectMG + ⟨true, ⟨[], [.sel .Loop, .licensor .fc, .licensor .fb, .licensor .fa, .cat .Start]⟩, []⟩ := + MG.Derives.lex (by simp [abcDirectMG, abcDirectLexicon]) + have h1 : MG.Derives abcDirectMG + ⟨false, ⟨[], [.licensor .fc, .licensor .fb, .licensor .fa, .cat .Start]⟩, + [⟨List.replicate n .a, [.licensee .fa]⟩, + ⟨List.replicate n .b, [.licensee .fb]⟩] ++ + ⟨List.replicate n .c, [.licensee .fc]⟩ :: []⟩ := by + simpa using MG.Derives.merge1 hFinLex hLoop + have h2 : MG.Derives abcDirectMG + ⟨false, ⟨List.replicate n .c, [.licensor .fb, .licensor .fa, .cat .Start]⟩, + [⟨List.replicate n .a, [.licensee .fa]⟩] ++ + ⟨List.replicate n .b, [.licensee .fb]⟩ :: []⟩ := by + simpa using MG.Derives.move1 h1 + have h3 : MG.Derives abcDirectMG + ⟨false, ⟨List.replicate n .b ++ List.replicate n .c, [.licensor .fa, .cat .Start]⟩, + [] ++ ⟨List.replicate n .a, [.licensee .fa]⟩ :: []⟩ := by + simpa using MG.Derives.move1 h2 + have h4 : MG.Derives abcDirectMG + ⟨false, ⟨List.replicate n .a ++ (List.replicate n .b ++ List.replicate n .c), [.cat .Start]⟩, + []⟩ := by + simpa using MG.Derives.move1 h3 + refine ⟨false, ?_⟩ + change MG.Derives abcDirectMG ⟨false, ⟨abcWord n, [.cat .Start]⟩, []⟩ + simpa [abcWord, List.append_assoc] using h4 + +/-- Automatically compiled MCFG from the direct 9-item MG via Michaelis's construction. -/ +def abcCompiledMCFG := MGtoMCFG.mgToMCFG abcDirectMG + +/-- Every word `a^n b^n c^n` (`n ≥ 1`) is automatically transferred to `abcCompiledMCFG`. -/ +theorem abcCompiledMCFG_generates_all (n : Nat) (hn : 1 ≤ n) : + abcCompiledMCFG.Lang (abcWord n) := + (MGtoMCFG.mgToMCFG_lang abcDirectMG (abcWord n)).mpr (abcDirectMG_generates_all n hn) + +/-- Concrete witness: `"aaabbbccc"` is generated by `abcCompiledMCFG`. -/ +theorem aaabbbccc_in_abcCompiledMCFG : + abcCompiledMCFG.Lang [.a, .a, .a, .b, .b, .b, .c, .c, .c] := + abcCompiledMCFG_generates_all 3 (by omega) + +end CrossSerialExample + +/-! ### Part 3: Kernel Axiom Audit -/ + + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/MGOriginal.lean b/LeanPool/FormalLinguistics/MGOriginal.lean new file mode 100644 index 0000000000..64ea7b8730 --- /dev/null +++ b/LeanPool/FormalLinguistics/MGOriginal.lean @@ -0,0 +1,283 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.MGMCFGEquiv + +/-! + Minimalist Grammars exactly as stated by Stabler & Keenan (2003), and their + equivalence with the invariant-carrying presentation used in `MG.lean`. + + `MG.Derives` (in `MG.lean`) differs from the textbook definition in two ways: + + 1. The Shortest Move Constraint is imposed as an invariant on every derived + expression (`merge2`, `merge3`, `move2` all carry an `SMC` premise), + whereas Stabler & Keenan impose it only as a side condition on `move`: + "none of the other chains has `-f` as its first feature". + 2. `merge3` and `move2` require the remaining feature string of the mover to + begin with a licensee, whereas Stabler & Keenan only require it to be + non-empty. + + This file defines `MG.DerivesSK`, which follows Stabler & Keenan literally. + The rules were checked against Stabler & Keenan (2003), p. 347, whose + `merge1`–`merge3`, `move1`–`move2` and (SMC) are the constructors below, and + against Harkema (2000), "A recognizer for minimalist grammars" (IWPT), + §3.2.2, whose six inference rules correspond to them as follows: + + Harkema Merge-1 ↦ `merge1` + Harkema Merge-2 (δ ≠ ε) ↦ `merge3` with a lexical selector + Harkema Merge-3 ↦ `merge2` + Harkema Merge-4 (δ ≠ ε) ↦ `merge3` with a derived selector + Harkema Move-1 ↦ `move1` + Harkema Move-2 (δ ≠ ε) ↦ `move2` + + with Harkema's side condition on Move ("if `γⱼ` is one of the other chains, + then the first feature of `γⱼ` is not `-f`") rendered as + `∀ c ∈ ms1 ++ ms2, c.headLic ≠ some f`. + + Three minor differences from Stabler & Keenan remain. They index all four + kinds of feature by a single set `base`, whereas `MG` keeps category names + (`Base`) and licensing features (`Lic`) in separate types, as in Stabler + (1997); their grammars are the special case `Base = Lic`. Their lexical items + may have an empty feature string, which `MG.lex_nonempty` excludes, and their + merge/move rules require the remaining feature string `γ` of the head chain + to be non-empty (`γ ∈ F⁺`), whereas `DerivesSK` permits `γ = []`; in both + cases, an empty head-chain feature string matches the premise of no rule and + is not a complete expression, so the generated language is unaffected. + + We prove: + + • `MG.derives_iff_SK_and_smc`: + `Derives G e ↔ DerivesSK G e ∧ SMC e.movers` + i.e. `Derives` derives exactly the Stabler–Keenan expressions whose + movers satisfy the SMC invariant. + • `MG.langSK_iff_lang`: both presentations generate the same string language. + • `michaelis_harkema_equivalence_SK`: the main `L(MG) = L(MCFG)` theorem, + restated for the literal Stabler–Keenan definition. +-/ + +@[expose] public section + +namespace FormalLinguistics + +namespace MG + +variable {Base Lic T : Type} + +/-- Derivable expressions of a Minimalist Grammar, following Stabler & Keenan (2003) + literally: `merge` has no SMC condition and admits any non-empty remaining + feature string `δ` on the selected phrase; `move` applies only when no *other* + mover has `-f` as its first feature (the Shortest Move Constraint). -/ +inductive DerivesSK (G : MG Base Lic T) : MGExpr Base Lic T → Prop where + /-- Lexical insertion. -/ + | lex {w : List T} {α : List (MGFeature Base Lic)} : + (w, α) ∈ G.lexicon → + DerivesSK G ⟨true, ⟨w, α⟩, []⟩ + + /-- merge1: `s :: =x γ` and `t · x, ms` give `st : γ, ms`. -/ + | merge1 {s t : List T} {x : Base} {γ : List (MGFeature Base Lic)} + {b : Bool} {ms : List (MGChain Base Lic T)} : + DerivesSK G ⟨true, ⟨s, MGFeature.sel x :: γ⟩, []⟩ → + DerivesSK G ⟨b, ⟨t, [MGFeature.cat x]⟩, ms⟩ → + DerivesSK G ⟨false, ⟨s ++ t, γ⟩, ms⟩ + + /-- merge2: `s : =x γ, ms1` and `t · x, ms2` give `ts : γ, ms1, ms2`. -/ + | merge2 {s t : List T} {x : Base} {γ : List (MGFeature Base Lic)} + {b : Bool} {ms1 ms2 : List (MGChain Base Lic T)} : + DerivesSK G ⟨false, ⟨s, MGFeature.sel x :: γ⟩, ms1⟩ → + DerivesSK G ⟨b, ⟨t, [MGFeature.cat x]⟩, ms2⟩ → + DerivesSK G ⟨false, ⟨t ++ s, γ⟩, ms1 ++ ms2⟩ + + /-- merge3: `s · =x γ, ms1` and `t · x δ, ms2` with `δ ≠ ε` give + `s : γ, ms1, t : δ, ms2`. -/ + | merge3 {s t : List T} {x : Base} {γ δ : List (MGFeature Base Lic)} + {b1 b2 : Bool} {ms1 ms2 : List (MGChain Base Lic T)} : + DerivesSK G ⟨b1, ⟨s, MGFeature.sel x :: γ⟩, ms1⟩ → + DerivesSK G ⟨b2, ⟨t, MGFeature.cat x :: δ⟩, ms2⟩ → + δ ≠ [] → + DerivesSK G ⟨false, ⟨s, γ⟩, ms1 ++ ⟨t, δ⟩ :: ms2⟩ + + /-- move1: `s : +f γ, ms1, t : -f, ms2` gives `ts : γ, ms1, ms2`, + provided no other mover has `-f` as its first feature (SMC). -/ + | move1 {s t : List T} {f : Lic} {γ : List (MGFeature Base Lic)} + {ms1 ms2 : List (MGChain Base Lic T)} : + DerivesSK G ⟨false, ⟨s, MGFeature.licensor f :: γ⟩, + ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2⟩ → + (∀ c, c ∈ ms1 ++ ms2 → c.headLic ≠ some f) → + DerivesSK G ⟨false, ⟨t ++ s, γ⟩, ms1 ++ ms2⟩ + + /-- move2: `s : +f γ, ms1, t : -f δ, ms2` with `δ ≠ ε` gives + `s : γ, ms1, t : δ, ms2`, provided no other mover has `-f` as its first + feature (SMC). -/ + | move2 {s t : List T} {f : Lic} {γ δ : List (MGFeature Base Lic)} + {ms1 ms2 : List (MGChain Base Lic T)} : + DerivesSK G ⟨false, ⟨s, MGFeature.licensor f :: γ⟩, + ms1 ++ ⟨t, MGFeature.licensee f :: δ⟩ :: ms2⟩ → + δ ≠ [] → + (∀ c, c ∈ ms1 ++ ms2 → c.headLic ≠ some f) → + DerivesSK G ⟨false, ⟨s, γ⟩, ms1 ++ ⟨t, δ⟩ :: ms2⟩ + +/-- The string language of a Minimalist Grammar under the literal + Stabler–Keenan definition. -/ +def LangSK (G : MG Base Lic T) (w : List T) : Prop := + ∃ b, DerivesSK G ⟨b, ⟨w, [MGFeature.cat G.start]⟩, []⟩ + +/-! ### Elementary facts about the `SMC` invariant -/ + +theorem smc_nil : SMC ([] : List (MGChain Base Lic T)) := + ⟨fun _ h => by simp at h, List.nodup_nil⟩ + +theorem mem_filterMap_headLic {ms : List (MGChain Base Lic T)} {f : Lic} : + f ∈ ms.filterMap MGChain.headLic ↔ ∃ c, c ∈ ms ∧ c.headLic = some f := by + simp [List.mem_filterMap] + +theorem smc_append_left {ms1 ms2 : List (MGChain Base Lic T)} + (h : SMC (ms1 ++ ms2)) : SMC ms1 := by + obtain ⟨hall, hnd⟩ := h + refine ⟨fun c hc => hall c (List.mem_append_left _ hc), ?_⟩ + rw [List.filterMap_append] at hnd + exact (List.nodup_append.mp hnd).1 + +theorem smc_append_right {ms1 ms2 : List (MGChain Base Lic T)} + (h : SMC (ms1 ++ ms2)) : SMC ms2 := by + obtain ⟨hall, hnd⟩ := h + refine ⟨fun c hc => hall c (List.mem_append_right _ hc), ?_⟩ + rw [List.filterMap_append] at hnd + exact (List.nodup_append.mp hnd).2.1 + +/-- The distinguished chain of an SMC-valid mover list begins with a licensee. -/ +theorem smc_mid {ms1 ms2 : List (MGChain Base Lic T)} {c : MGChain Base Lic T} + (h : SMC (ms1 ++ c :: ms2)) : ∃ f δ, c.feats = MGFeature.licensee f :: δ := + h.1 c (List.mem_append_right _ (List.mem_cons_self ..)) + +/-- In an SMC-valid mover list, no *other* chain shares the head licensee of `c`. -/ +theorem smc_others {ms1 ms2 : List (MGChain Base Lic T)} {c : MGChain Base Lic T} {f : Lic} + (h : SMC (ms1 ++ c :: ms2)) (hc : c.headLic = some f) : + ∀ c', c' ∈ ms1 ++ ms2 → c'.headLic ≠ some f := by + obtain ⟨_, hnd⟩ := h + rw [List.filterMap_append, List.filterMap_cons, hc] at hnd + obtain ⟨_, hnd2, hdisj⟩ := List.nodup_append.mp hnd + obtain ⟨hnot, _⟩ := List.nodup_cons.mp hnd2 + intro c' hc' hf + rcases List.mem_append.mp hc' with h1 | h2 + · exact hdisj f (mem_filterMap_headLic.mpr ⟨c', h1, hf⟩) f (List.mem_cons_self ..) rfl + · exact hnot (mem_filterMap_headLic.mpr ⟨c', h2, hf⟩) + +/-- Inserting a licensee-initial chain whose head licensee is fresh preserves `SMC`. -/ +theorem smc_insert {ms1 ms2 : List (MGChain Base Lic T)} {c : MGChain Base Lic T} + {f : Lic} {δ : List (MGFeature Base Lic)} + (h : SMC (ms1 ++ ms2)) (hc : c.feats = MGFeature.licensee f :: δ) + (hfresh : ∀ c', c' ∈ ms1 ++ ms2 → c'.headLic ≠ some f) : + SMC (ms1 ++ c :: ms2) := by + obtain ⟨hall, hnd⟩ := h + have hhead : c.headLic = some f := by simp [MGChain.headLic, hc] + refine ⟨?_, ?_⟩ + · intro x hx + rcases List.mem_append.mp hx with h1 | h2 + · exact hall x (List.mem_append_left _ h1) + · rcases List.mem_cons.mp h2 with rfl | h2' + · exact ⟨f, δ, hc⟩ + · exact hall x (List.mem_append_right _ h2') + · rw [List.filterMap_append] at hnd + obtain ⟨hnd1, hnd2, hdisj⟩ := List.nodup_append.mp hnd + rw [List.filterMap_append, List.filterMap_cons, hhead] + refine List.nodup_append.mpr ⟨hnd1, List.nodup_cons.mpr ⟨?_, hnd2⟩, ?_⟩ + · intro hmem + obtain ⟨c', hc', hf⟩ := mem_filterMap_headLic.mp hmem + exact hfresh c' (List.mem_append_right _ hc') hf + · intro a ha b hb + rcases List.mem_cons.mp hb with rfl | hb' + · intro hab + subst hab + obtain ⟨c', hc', hf⟩ := mem_filterMap_headLic.mp ha + exact hfresh c' (List.mem_append_left _ hc') hf + · exact hdisj a ha b hb' + +/-! ### The two presentations coincide -/ + +/-- Every expression derivable in the invariant-carrying presentation is derivable + under the literal Stabler–Keenan rules. -/ +theorem Derives.toSK {G : MG Base Lic T} {e : MGExpr Base Lic T} (h : Derives G e) : + DerivesSK G e := by + induction h with + | lex hl => exact DerivesSK.lex hl + | merge1 _ _ ih1 ih2 => exact DerivesSK.merge1 ih1 ih2 + | merge2 _ _ _ ih1 ih2 => exact DerivesSK.merge2 ih1 ih2 + | merge3 _ _ _ ih1 ih2 => exact DerivesSK.merge3 ih1 ih2 (by simp) + | move1 h ih => + exact DerivesSK.move1 ih (smc_others h.smc (by simp [MGChain.headLic])) + | move2 h _ ih => + exact DerivesSK.move2 ih (by simp) (smc_others h.smc (by simp [MGChain.headLic])) + +/-- Conversely, a Stabler–Keenan derivation whose *conclusion* satisfies the SMC + invariant is a derivation in the invariant-carrying presentation: the + invariant propagates backwards through every rule. -/ +theorem DerivesSK.toDerives {G : MG Base Lic T} {e : MGExpr Base Lic T} + (h : DerivesSK G e) : SMC e.movers → Derives G e := by + induction h with + | lex hl => intro _; exact Derives.lex hl + | merge1 _ _ ih1 ih2 => + intro hs + exact Derives.merge1 (ih1 smc_nil) (ih2 hs) + | merge2 _ _ ih1 ih2 => + intro hs + exact Derives.merge2 (ih1 (smc_append_left hs)) (ih2 (smc_append_right hs)) hs + | merge3 _ _ _ ih1 ih2 => + intro hs + obtain ⟨f, δ', hfe⟩ := smc_mid hs + simp only at hfe + subst hfe + have hrest := smc_remove hs + exact Derives.merge3 (ih1 (smc_append_left hrest)) (ih2 (smc_append_right hrest)) hs + | move1 _ hfresh ih => + intro hs + exact Derives.move1 (ih (smc_insert hs rfl hfresh)) + | move2 _ _ hfresh ih => + intro hs + obtain ⟨f', δ', hfe⟩ := smc_mid hs + simp only at hfe + subst hfe + exact Derives.move2 (ih (smc_insert (smc_remove hs) rfl hfresh)) hs + +/-- `Derives` derives exactly the Stabler–Keenan expressions whose movers satisfy + the SMC invariant. -/ +theorem derives_iff_SK_and_smc {G : MG Base Lic T} {e : MGExpr Base Lic T} : + Derives G e ↔ DerivesSK G e ∧ SMC e.movers := + ⟨fun h => ⟨h.toSK, h.smc⟩, fun ⟨h, hs⟩ => h.toDerives hs⟩ + +/-- Both presentations of Minimalist Grammars generate the same string language. -/ +theorem langSK_iff_lang (G : MG Base Lic T) (w : List T) : + G.LangSK w ↔ G.Lang w := + ⟨fun ⟨b, h⟩ => ⟨b, h.toDerives smc_nil⟩, fun ⟨b, h⟩ => ⟨b, h.toSK⟩⟩ + +end MG + +/-! ### Main theorem for the literal Stabler–Keenan definition -/ + +/-- Language class of finite Minimalist Grammars under the literal + Stabler–Keenan (2003) definition. -/ +def IsMGLangSK {T : Type} (L : List T → Prop) : Prop := + ∃ (Base Lic : Type) (G : MG Base Lic T), ∀ w, G.LangSK w ↔ L w + +theorem isMGLangSK_iff_isMGLang {T : Type} (L : List T → Prop) : + IsMGLangSK L ↔ IsMGLang L := by + constructor + · rintro ⟨Base, Lic, G, hG⟩ + exact ⟨Base, Lic, G, fun w => by rw [← MG.langSK_iff_lang, hG]⟩ + · rintro ⟨Base, Lic, G, hG⟩ + exact ⟨Base, Lic, G, fun w => by rw [MG.langSK_iff_lang, hG]⟩ + +/-- **Michaelis–Harkema Equivalence Theorem for Stabler–Keenan Minimalist Grammars**: + a language is generated by a finite Minimalist Grammar, in the literal sense of + Stabler & Keenan (2003), iff it is generated by a finite linear non-erasing + MCFG (LCFRS). -/ +theorem michaelis_harkema_equivalence_SK {T : Type} (L : List T → Prop) : + IsMGLangSK L ↔ IsMCFGLang L := by + rw [isMGLangSK_iff_isMGLang, michaelis_harkema_equivalence] + + +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/MGtoMCFG.lean b/LeanPool/FormalLinguistics/MGtoMCFG.lean new file mode 100644 index 0000000000..061cf6f9d4 --- /dev/null +++ b/LeanPool/FormalLinguistics/MGtoMCFG.lean @@ -0,0 +1,3217 @@ +/- +Copyright (c) 2026 bocchitherock888-ux. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: bocchitherock888-ux +-/ + +module + +public import LeanPool.FormalLinguistics.MCFG +public import LeanPool.FormalLinguistics.MG +public import LeanPool.FormalLinguistics.CNF + +/-! + Direction 1 of Michaelis (1998, 2001) & Harkema (2001): + Every Minimalist Grammar (Stabler & Keenan 2003) has a weakly equivalent + Linear Non-Erasing Multiple Context-Free Grammar (MCFG / LCFRS). + + Key idea (after Michaelis 1998, Sect. 4, who fixes an enumeration of the licensees + and indexes the components of each nonterminal by it): + 1. By the sub-suffix property (`MG.Derives.feats_suffix`), every feature stack + in any derivation lies in the finite list `allFeats G`. + 2. Let `L = allLics G` be the duplicate-free finite list of licensee features + occurring in `G.lexicon`. By the Shortest Move Constraint (`SMC`), every + active mover list `ms` maps canonically to an `L`-indexed slot vector + `slotsOf L ms : List (Option (List (MGFeature Base Lic)))` and corresponding + string tuple `strsOf L ms : List (List T)`. + 3. Every MG rule (`lex`, `merge1`, `merge2`, `merge3`, `move1`, `move2`) + translates directly into linear, non-erasing MCFG rules over the finite + universe of canonical feature profiles `allProfiles G`. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Nonterminals of the MCFG constructed from a Minimalist Grammar. -/ +inductive MGMCFGNT (Base Lic : Type) where + | start : MGMCFGNT Base Lic + | prof : Bool → List (MGFeature Base Lic) → + List (Option (List (MGFeature Base Lic))) → MGMCFGNT Base Lic + deriving DecidableEq, Repr + +namespace MGtoMCFG + +variable {Base Lic T : Type} + +/-! ### Part 1: Finite Feature-Suffix & Licensee-Feature Universes -/ + +/-- All suffixes of a list `l` (from `l` down to `[]`). -/ +def listSuffixes {α : Type} : List α → List (List α) + | [] => [[]] + | a :: t => (a :: t) :: listSuffixes t + +theorem mem_listSuffixes_iff {α : Type} {s l : List α} : + s ∈ listSuffixes l ↔ MG.isSuffix s l := by + induction l with + | nil => + simp [listSuffixes, MG.isSuffix] + | cons a t ih => + simp only [listSuffixes, List.mem_cons, ih] + constructor + · rintro (rfl | ⟨p, hp⟩) + · exact ⟨[], rfl⟩ + · exact ⟨a :: p, by simp [hp]⟩ + · rintro ⟨p, hp⟩ + cases p with + | nil => left; simpa using hp + | cons b p' => + simp at hp + right + exact ⟨p', hp.2⟩ + +/-- Finite deduplicated list of all feature suffixes occurring in `G.lexicon`. -/ +def allFeats [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + List (List (MGFeature Base Lic)) := + dedupList (G.lexicon.flatMap fun entry => listSuffixes entry.2) + +theorem mem_allFeats_of_suffix [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {fs : List (MGFeature Base Lic)} {entry : List T × List (MGFeature Base Lic)} + (he : entry ∈ G.lexicon) (hs : MG.isSuffix fs entry.2) : + fs ∈ allFeats G := by + rw [allFeats, mem_dedupList] + exact List.mem_flatMap.mpr ⟨entry, he, mem_listSuffixes_iff.mpr hs⟩ + +/-- Finite deduplicated list of all licensee features `f` appearing in `G.lexicon`. -/ +def allLics [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : List Lic := + dedupList ((allFeats G).filterMap fun + | MGFeature.licensee f :: _ => some f + | _ => none) + +theorem nodup_allLics [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + (allLics G).Nodup := + nodup_dedupList _ + +theorem mem_allLics_of_suffix [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {f : Lic} {δ : List (MGFeature Base Lic)} + {entry : List T × List (MGFeature Base Lic)} + (he : entry ∈ G.lexicon) (hs : MG.isSuffix (MGFeature.licensee f :: δ) entry.2) : + f ∈ allLics G := by + rw [allLics, mem_dedupList, List.mem_filterMap] + exact ⟨MGFeature.licensee f :: δ, mem_allFeats_of_suffix he hs, rfl⟩ + +/-- All feature suffixes in `G` starting with `MGFeature.licensee f`. -/ +def licFeats [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) (f : Lic) : + List (List (MGFeature Base Lic)) := + (allFeats G).filter fun fs => + match fs with + | MGFeature.licensee f' :: _ => decide (f' = f) + | _ => false + +theorem mem_licFeats_iff [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {f : Lic} {fs : List (MGFeature Base Lic)} : + fs ∈ licFeats G f ↔ fs ∈ allFeats G ∧ ∃ δ, fs = MGFeature.licensee f :: δ := by + simp only [licFeats, List.mem_filter] + constructor + · rintro ⟨h1, h2⟩ + refine ⟨h1, ?_⟩ + cases fs with + | nil => simp at h2 + | cons hd tl => + cases hd with + | licensee f' => + simp at h2; subst h2; exact ⟨tl, rfl⟩ + | _ => simp at h2 + · rintro ⟨h1, δ, rfl⟩ + exact ⟨h1, by simp⟩ + +/-! ### Part 2: Canonical `L`-Indexed Mover Slot Representation -/ + +/-- Find the unique mover in `ms` whose leading feature is `licensee f`. -/ +def findChain [DecidableEq Lic] (f : Lic) (ms : List (MGChain Base Lic T)) : + Option (MGChain Base Lic T) := + ms.find? fun c => decide (c.headLic = some f) + +/-- Canonical `L`-indexed feature-slot list for a mover list `ms`. -/ +def slotsOf [DecidableEq Lic] (L : List Lic) (ms : List (MGChain Base Lic T)) : + List (Option (List (MGFeature Base Lic))) := + L.map fun f => (findChain f ms).map MGChain.feats + +/-- Canonical `L`-indexed string tuple for a mover list `ms`. -/ +def strsOf [DecidableEq Lic] (L : List Lic) (ms : List (MGChain Base Lic T)) : + List (List T) := + L.filterMap fun f => (findChain f ms).map MGChain.str + +/-- Dimension of an `MGMCFGNT`: `1` for `start`, `1 + activeSlots` for a profile. -/ +def ntDim : MGMCFGNT Base Lic → Nat + | MGMCFGNT.start => 1 + | MGMCFGNT.prof _ _ slots => 1 + slots.countP Option.isSome + +theorem ntDim_pos (A : MGMCFGNT Base Lic) : 1 ≤ ntDim A := by + cases A <;> simp [ntDim] + +theorem slotsOf_length [DecidableEq Lic] (L : List Lic) (ms : List (MGChain Base Lic T)) : + (slotsOf L ms).length = L.length := by + simp [slotsOf] + +theorem slotsOf_cons [DecidableEq Lic] (f : Lic) (t : List Lic) (ms : List (MGChain Base Lic T)) : + slotsOf (f :: t) ms = (findChain f ms).map MGChain.feats :: slotsOf t ms := rfl + +theorem strsOf_cons_none [DecidableEq Lic] {f : Lic} {t : List Lic} {ms : List (MGChain Base Lic T)} + (h : findChain f ms = none) : + strsOf (f :: t) ms = strsOf t ms := by + simp [strsOf, h] + +theorem strsOf_cons_some [DecidableEq Lic] {f : Lic} {t : List Lic} {ms : List (MGChain Base Lic T)} + {c : MGChain Base Lic T} (h : findChain f ms = some c) : + strsOf (f :: t) ms = c.str :: strsOf t ms := by + simp [strsOf, h] + +theorem strsOf_length [DecidableEq Lic] (L : List Lic) (ms : List (MGChain Base Lic T)) : + (strsOf L ms).length = (slotsOf L ms).countP Option.isSome := by + induction L with + | nil => simp [strsOf, slotsOf] + | cons f t ih => + cases h : findChain f ms with + | none => rw [strsOf_cons_none h, slotsOf_cons, h]; simpa using ih + | some c => rw [strsOf_cons_some h, slotsOf_cons, h]; simp [ih] + +/-- Under `SMC ms`, there is at most one chain in `ms` with leading licensee `f`. -/ +theorem smc_unique_chain {ms : List (MGChain Base Lic T)} (hsmc : SMC ms) + {c1 c2 : MGChain Base Lic T} {f : Lic} + (h1 : c1 ∈ ms) (hf1 : c1.headLic = some f) + (h2 : c2 ∈ ms) (hf2 : c2.headLic = some f) : c1 = c2 := by + induction ms with + | nil => simp at h1 + | cons a t ih => + obtain ⟨hall, hnd⟩ := hsmc + have hsmct : SMC t := by + refine ⟨fun x hx => hall x (List.mem_cons_of_mem a hx), ?_⟩ + simp only [List.filterMap_cons] at hnd + cases ha : a.headLic with + | none => simpa [ha] using hnd + | some fa => rw [ha] at hnd; exact (List.nodup_cons.mp hnd).2 + rcases List.mem_cons.mp h1 with rfl | ht1 + · rcases List.mem_cons.mp h2 with rfl | ht2 + · rfl + · simp only [List.filterMap_cons, hf1, List.nodup_cons] at hnd + have hf_in : f ∈ t.filterMap MGChain.headLic := + List.mem_filterMap.mpr ⟨c2, ht2, hf2⟩ + exact absurd hf_in hnd.1 + · rcases List.mem_cons.mp h2 with rfl | ht2 + · simp only [List.filterMap_cons, hf2, List.nodup_cons] at hnd + have hf_in : f ∈ t.filterMap MGChain.headLic := + List.mem_filterMap.mpr ⟨c1, ht1, hf1⟩ + exact absurd hf_in hnd.1 + · exact ih hsmct ht1 ht2 + +/-- Under `SMC ms`, `findChain f ms = some c` iff `c ∈ ms` and `c.headLic = some f`. -/ +theorem findChain_eq_some_iff [DecidableEq Lic] {ms : List (MGChain Base Lic T)} (hsmc : SMC ms) + {f : Lic} {c : MGChain Base Lic T} : + findChain f ms = some c ↔ c ∈ ms ∧ c.headLic = some f := by + constructor + · intro h + have h1 := List.mem_of_find?_eq_some h + have h2 := List.find?_some h + simp only [decide_eq_true_eq] at h2 + exact ⟨h1, h2⟩ + · rintro ⟨hc, hf⟩ + cases hfind : findChain f ms with + | none => + have hnot := List.find?_eq_none.mp hfind c hc + simp [hf] at hnot + | some c' => + have hc' := List.mem_of_find?_eq_some hfind + have hf' := List.find?_some hfind + simp only [decide_eq_true_eq] at hf' + have heq := smc_unique_chain hsmc hc' hf' hc hf + subst heq; rfl + +theorem findChain_eq_none_iff [DecidableEq Lic] {ms : List (MGChain Base Lic T)} {f : Lic} : + findChain f ms = none ↔ ∀ c, c ∈ ms → c.headLic ≠ some f := by + simp [findChain, List.find?_eq_none] + +theorem findChain_nil [DecidableEq Lic] (f : Lic) : + findChain f ([] : List (MGChain Base Lic T)) = none := rfl + +theorem slotsOf_nil [DecidableEq Lic] (L : List Lic) : + slotsOf (Base := Base) (T := T) L [] = L.map (fun _ => none) := by + simp [slotsOf, findChain_nil] + +theorem strsOf_nil [DecidableEq Lic] (L : List Lic) : + strsOf (Base := Base) (T := T) L [] = [] := by + induction L with + | nil => rfl + | cons f t _ => simp [strsOf, findChain_nil] + +/-- If every chain in `ms` has its leading licensee in `L`, and `slotsOf L ms` is all `none`, + then `ms = []`. -/ +theorem movers_nil_of_slotsOf_all_none [DecidableEq Lic] {L : List Lic} + {ms : List (MGChain Base Lic T)} + (hsmc : SMC ms) + (hL : ∀ c, c ∈ ms → ∀ f, c.headLic = some f → f ∈ L) + (hall : slotsOf L ms = L.map (fun _ => none)) : ms = [] := by + cases ms with + | nil => rfl + | cons c t => + obtain ⟨f, δ, hfeats⟩ := hsmc.1 c (List.mem_cons_self ..) + have hlic : c.headLic = some f := by simp [MGChain.headLic, hfeats] + have hfL : f ∈ L := hL c (List.mem_cons_self ..) f hlic + have hfind : findChain f (c :: t) = some c := + (findChain_eq_some_iff hsmc).mpr ⟨List.mem_cons_self .., hlic⟩ + have hmem_some : some c.feats ∈ slotsOf L (c :: t) := by + simp only [slotsOf, List.mem_map] + exact ⟨f, hfL, by simp [hfind]⟩ + rw [hall] at hmem_some + simp at hmem_some + +/-! ### Part 3: Slot Combinators & Linear Non-Erasing Variable Generators -/ + +/-- Pointwise disjoint merge of two slot lists (returns `none` on SMC collision or length mismatch). -/ +def mergeSlots {α : Type} : List (Option α) → List (Option α) → Option (List (Option α)) + | [], [] => some [] + | none :: t1, o2 :: t2 => (mergeSlots t1 t2).map (o2 :: ·) + | some a :: t1, none :: t2 => (mergeSlots t1 t2).map (some a :: ·) + | some _ :: _, some _ :: _ => none + | _, _ => none + +/-- Linear variable components produced by merging two slot lists, starting at component + indices `c1` (for RHS 0) and `c2` (for RHS 1). -/ +def mergeVars {α : Type} (c1 c2 : Nat) : + List (Option α) → List (Option α) → List (List (MCFGAtom T)) + | none :: t1, none :: t2 => mergeVars c1 c2 t1 t2 + | some _ :: t1, none :: t2 => [MCFGAtom.var 0 c1] :: mergeVars (c1 + 1) c2 t1 t2 + | none :: t1, some _ :: t2 => [MCFGAtom.var 1 c2] :: mergeVars c1 (c2 + 1) t1 t2 + | _, _ => [] + +/-- Collect variable coordinates occurring in a list of component templates. -/ +def compsVars (cs : List (List (MCFGAtom T))) : List (Nat × Nat) := + cs.flatMap fun comp => + comp.filterMap fun + | MCFGAtom.tm _ => none + | MCFGAtom.var i j => some (i, j) + +theorem compsVars_nil : compsVars (T := T) [] = [] := rfl + +theorem compsVars_cons_var (i j : Nat) (cs : List (List (MCFGAtom T))) : + compsVars ([MCFGAtom.var i j] :: cs) = (i, j) :: compsVars cs := rfl + +theorem mergeSlots_countP {α : Type} {s1 s2 s : List (Option α)} + (h : mergeSlots s1 s2 = some s) : + s.countP Option.isSome = s1.countP Option.isSome + s2.countP Option.isSome := by + induction s1 generalizing s2 s with + | nil => + cases s2 with + | nil => simp [mergeSlots] at h; subst h; rfl + | cons _ _ => simp [mergeSlots] at h + | cons o1 t1 ih => + cases s2 with + | nil => cases o1 <;> simp [mergeSlots] at h + | cons o2 t2 => + cases o1 with + | none => + simp only [mergeSlots, Option.map_eq_some_iff] at h + obtain ⟨s', hs', rfl⟩ := h + have ih' := ih hs' + cases o2 <;> simp [ih'] <;> omega + | some a => + cases o2 with + | none => + simp only [mergeSlots, Option.map_eq_some_iff] at h + obtain ⟨s', hs', rfl⟩ := h + have ih' := ih hs' + simp [ih']; omega + | some b => simp [mergeSlots] at h + +theorem mergeVars_props {α : Type} {s1 s2 s : List (Option α)} + (h : mergeSlots s1 s2 = some s) : + ∀ c1 c2, + (mergeVars (T := T) c1 c2 s1 s2).length = s.countP Option.isSome ∧ + (compsVars (mergeVars (T := T) c1 c2 s1 s2)).Nodup ∧ + (∀ i j, (i, j) ∈ compsVars (mergeVars (T := T) c1 c2 s1 s2) ↔ + (i = 0 ∧ c1 ≤ j ∧ j < c1 + s1.countP Option.isSome) ∨ + (i = 1 ∧ c2 ≤ j ∧ j < c2 + s2.countP Option.isSome)) := by + induction s1 generalizing s2 s with + | nil => + cases s2 with + | nil => + simp [mergeSlots] at h; subst h + intro c1 c2 + refine ⟨rfl, List.nodup_nil, ?_⟩ + intro i j; simp [mergeVars, compsVars_nil] + | cons _ _ => simp [mergeSlots] at h + | cons o1 t1 ih => + cases s2 with + | nil => cases o1 <;> simp [mergeSlots] at h + | cons o2 t2 => + cases o1 with + | none => + simp only [mergeSlots, Option.map_eq_some_iff] at h + obtain ⟨s', hs', rfl⟩ := h + intro c1 c2 + cases o2 with + | none => + obtain ⟨hlen, hnd, hmem⟩ := ih hs' c1 c2 + refine ⟨by simpa [mergeVars] using hlen, by simpa [mergeVars] using hnd, ?_⟩ + intro i j; simpa [mergeVars] using hmem i j + | some b => + obtain ⟨hlen, hnd, hmem⟩ := ih hs' c1 (c2 + 1) + refine ⟨?_, ?_, ?_⟩ + · simp [mergeVars, hlen] + · simp only [mergeVars] + rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hbad + have := (hmem 1 c2).mp hbad + omega + · intro i j + simp only [mergeVars] + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp only [List.countP_cons, Option.isSome_none, Option.isSome_some, + Bool.false_eq_true, ↓reduceIte] + constructor + · rintro (⟨rfl, rfl⟩ | h0 | h1) + · right; refine ⟨rfl, Nat.le_refl _, ?_⟩; omega + · left; omega + · right; omega + · rintro (⟨rfl, hlo, hhi⟩ | ⟨rfl, hlo, hhi⟩) + · right; left; omega + · by_cases hj : j = c2 + · left; exact ⟨rfl, hj⟩ + · right; right; omega + | some a => + cases o2 with + | some b => simp [mergeSlots] at h + | none => + simp only [mergeSlots, Option.map_eq_some_iff] at h + obtain ⟨s', hs', rfl⟩ := h + intro c1 c2 + obtain ⟨hlen, hnd, hmem⟩ := ih hs' (c1 + 1) c2 + refine ⟨?_, ?_, ?_⟩ + · simp [mergeVars, hlen] + · simp only [mergeVars] + rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hbad + have := (hmem 0 c1).mp hbad + omega + · intro i j + simp only [mergeVars] + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp only [List.countP_cons, Option.isSome_none, Option.isSome_some, + Bool.false_eq_true, ↓reduceIte] + constructor + · rintro (⟨rfl, rfl⟩ | h0 | h1) + · left; refine ⟨rfl, Nat.le_refl _, ?_⟩; omega + · left; omega + · right; omega + · rintro (⟨rfl, hlo, hhi⟩ | ⟨rfl, hlo, hhi⟩) + · by_cases hj : j = c1 + · left; exact ⟨rfl, hj⟩ + · right; left; omega + · right; right; omega + +/-- Evaluate `mergeVars` on string lists `args = [p1 ++ strs1, p2 ++ strs2]` with prefix lengths `c1, c2`. -/ +theorem evalYield_mergeVars [DecidableEq Lic] + (L : List Lic) {ms1 ms2 : List (MGChain Base Lic T)} + (hsmc1 : SMC ms1) (hsmc2 : SMC ms2) (hsmc12 : SMC (ms1 ++ ms2)) : + mergeSlots (slotsOf L ms1) (slotsOf L ms2) = some (slotsOf L (ms1 ++ ms2)) ∧ + ∀ (p1 p2 : List (List T)), + MCFG.evalYield [p1 ++ strsOf L ms1, p2 ++ strsOf L ms2] + (mergeVars p1.length p2.length (slotsOf L ms1) (slotsOf L ms2)) = + strsOf L (ms1 ++ ms2) := by + induction L with + | nil => + exact ⟨rfl, fun _ _ => rfl⟩ + | cons f t ih => + obtain ⟨hms, heval⟩ := ih + have hcase : + (findChain f ms1 = none ∧ findChain f ms2 = none ∧ findChain f (ms1 ++ ms2) = none) ∨ + (∃ c, findChain f ms1 = some c ∧ findChain f ms2 = none ∧ findChain f (ms1 ++ ms2) = some c) ∨ + (∃ c, findChain f ms1 = none ∧ findChain f ms2 = some c ∧ findChain f (ms1 ++ ms2) = some c) := by + cases h1 : findChain f ms1 with + | none => + cases h2 : findChain f ms2 with + | none => + left + refine ⟨rfl, rfl, ?_⟩ + rw [findChain_eq_none_iff] at h1 h2 ⊢ + intro c hc + rcases List.mem_append.mp hc with hm1 | hm2 + · exact h1 c hm1 + · exact h2 c hm2 + | some c => + right; right + obtain ⟨hc2, hf2⟩ := (findChain_eq_some_iff hsmc2).mp h2 + exact ⟨c, rfl, rfl, (findChain_eq_some_iff hsmc12).mpr ⟨List.mem_append_right _ hc2, hf2⟩⟩ + | some c => + cases h2 : findChain f ms2 with + | none => + right; left + obtain ⟨hc1, hf1⟩ := (findChain_eq_some_iff hsmc1).mp h1 + exact ⟨c, rfl, rfl, (findChain_eq_some_iff hsmc12).mpr ⟨List.mem_append_left _ hc1, hf1⟩⟩ + | some c2 => + -- Impossible by SMC (ms1 ++ ms2)! + obtain ⟨hc1, hf1⟩ := (findChain_eq_some_iff hsmc1).mp h1 + obtain ⟨hc2, hf2⟩ := (findChain_eq_some_iff hsmc2).mp h2 + have hnd := hsmc12.2 + rw [List.filterMap_append, List.nodup_append] at hnd + have hm1 : f ∈ ms1.filterMap MGChain.headLic := List.mem_filterMap.mpr ⟨c, hc1, hf1⟩ + have hm2 : f ∈ ms2.filterMap MGChain.headLic := List.mem_filterMap.mpr ⟨c2, hc2, hf2⟩ + exact absurd rfl (hnd.2.2 f hm1 f hm2) + rcases hcase with ⟨h1, h2, h12⟩ | ⟨c, h1, h2, h12⟩ | ⟨c, h1, h2, h12⟩ + · refine ⟨?_, fun p1 p2 => ?_⟩ + · rw [slotsOf_cons, slotsOf_cons, slotsOf_cons, h1, h2, h12]; simp [mergeSlots, hms] + · rw [slotsOf_cons, slotsOf_cons, h1, h2, strsOf_cons_none h1, strsOf_cons_none h2, + strsOf_cons_none h12] + simpa [mergeVars] using heval p1 p2 + · refine ⟨?_, fun p1 p2 => ?_⟩ + · rw [slotsOf_cons, slotsOf_cons, slotsOf_cons, h1, h2, h12]; simp [mergeSlots, hms] + · rw [slotsOf_cons, slotsOf_cons, h1, h2, strsOf_cons_some h1, strsOf_cons_none h2, + strsOf_cons_some h12] + simp only [Option.map_some, Option.map_none, mergeVars, MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [p1 ++ c.str :: strsOf t ms1, p2 ++ strsOf t ms2] + [MCFGAtom.var 0 p1.length] = c.str := by + simp [MCFG.evalComp] + have htail := heval (p1 ++ [c.str]) p2 + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append] at htail + rw [hhead] + exact congrArg (c.str :: ·) htail + · refine ⟨?_, fun p1 p2 => ?_⟩ + · rw [slotsOf_cons, slotsOf_cons, slotsOf_cons, h1, h2, h12]; simp [mergeSlots, hms] + · rw [slotsOf_cons, slotsOf_cons, h1, h2, strsOf_cons_none h1, strsOf_cons_some h2, + strsOf_cons_some h12] + simp only [Option.map_some, Option.map_none, mergeVars, MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [p1 ++ strsOf t ms1, p2 ++ c.str :: strsOf t ms2] + [MCFGAtom.var 1 p2.length] = c.str := by + simp [MCFG.evalComp] + have htail := heval p1 (p2 ++ [c.str]) + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append] at htail + rw [hhead] + exact congrArg (c.str :: ·) htail + +/-- Converse of `mergeSlots`: if `mergeSlots (slotsOf L ms1) (slotsOf L ms2) = some s`, + and all mover heads of `ms1, ms2` lie in `L`, then `SMC (ms1 ++ ms2)`. -/ +theorem smc_append_of_mergeSlots [DecidableEq Lic] {L : List Lic} + {ms1 ms2 : List (MGChain Base Lic T)} {s : List (Option (List (MGFeature Base Lic)))} + (hsmc1 : SMC ms1) (hsmc2 : SMC ms2) + (hL1 : ∀ c, c ∈ ms1 → ∀ f, c.headLic = some f → f ∈ L) + (hm : mergeSlots (slotsOf L ms1) (slotsOf L ms2) = some s) : + SMC (ms1 ++ ms2) := by + refine ⟨?_, ?_⟩ + · intro c hc + rcases List.mem_append.mp hc with h1 | h2 + · exact hsmc1.1 c h1 + · exact hsmc2.1 c h2 + · rw [List.filterMap_append, List.nodup_append] + refine ⟨hsmc1.2, hsmc2.2, ?_⟩ + intro f1 hf1 f2 hf2 heq + subst heq + obtain ⟨c1, hc1, hlic1⟩ := List.mem_filterMap.mp hf1 + obtain ⟨c2, hc2, hlic2⟩ := List.mem_filterMap.mp hf2 + have hfL : f1 ∈ L := hL1 c1 hc1 f1 hlic1 + have hfind1 := (findChain_eq_some_iff hsmc1).mpr ⟨hc1, hlic1⟩ + have hfind2 := (findChain_eq_some_iff hsmc2).mpr ⟨hc2, hlic2⟩ + clear hL1 + induction L generalizing s with + | nil => simp at hfL + | cons g t ih => + rcases List.mem_cons.mp hfL with rfl | ht + · rw [slotsOf_cons, slotsOf_cons, hfind1, hfind2] at hm + simp [mergeSlots] at hm + · rw [slotsOf_cons, slotsOf_cons] at hm + cases hfg1 : findChain g ms1 <;> cases hfg2 : findChain g ms2 + · simp [hfg1, hfg2, mergeSlots] at hm + obtain ⟨s', hs', _⟩ := hm + exact ih hs' ht + · simp [hfg1, hfg2, mergeSlots] at hm + obtain ⟨s', hs', _⟩ := hm + exact ih hs' ht + · simp [hfg1, hfg2, mergeSlots] at hm + obtain ⟨s', hs', _⟩ := hm + exact ih hs' ht + · simp [hfg1, hfg2, mergeSlots] at hm + +/-- Insert a new mover `(f, δ)` into an `L`-indexed slot list (fails if `f ∉ L` or slot already occupied). -/ +def insertSlot [DecidableEq Lic] (f : Lic) (δ : List (MGFeature Base Lic)) : + List Lic → List (Option (List (MGFeature Base Lic))) → + Option (List (Option (List (MGFeature Base Lic)))) + | [], [] => none + | g :: t, o :: os => + if g = f then + match o with + | none => some (some δ :: os) + | some _ => none + else + (insertSlot f δ t os).map (o :: ·) + | _, _ => none + +/-- Linear variable components for `Merge3`: inserts `[var 1 0]` at slot `f` and shifts + the merged components `mergeVars` around it. -/ +def merge3Vars [DecidableEq Lic] (f : Lic) (c1 c2 : Nat) : + List Lic → List (Option (List (MGFeature Base Lic))) → + List (Option (List (MGFeature Base Lic))) → List (List (MCFGAtom T)) + | g :: t, none :: t1, none :: t2 => + if g = f then + [MCFGAtom.var 1 0] :: mergeVars c1 c2 t1 t2 + else + merge3Vars f c1 c2 t t1 t2 + | g :: t, some _ :: t1, none :: t2 => + if g = f then [] + else [MCFGAtom.var 0 c1] :: merge3Vars f (c1 + 1) c2 t t1 t2 + | g :: t, none :: t1, some _ :: t2 => + if g = f then [] + else [MCFGAtom.var 1 c2] :: merge3Vars f c1 (c2 + 1) t t1 t2 + | _, _, _ => [] + +theorem merge3Vars_props [DecidableEq Lic] {f : Lic} {δ : List (MGFeature Base Lic)} + {L : List Lic} {s1 s2 s12 s : List (Option (List (MGFeature Base Lic)))} + (hm : mergeSlots s1 s2 = some s12) + (hi : insertSlot f δ L s12 = some s) : + ∀ c1 c2, 1 ≤ c2 → + (merge3Vars (T := T) f c1 c2 L s1 s2).length = s.countP Option.isSome ∧ + (compsVars (merge3Vars (T := T) f c1 c2 L s1 s2)).Nodup ∧ + (∀ i j, (i, j) ∈ compsVars (merge3Vars (T := T) f c1 c2 L s1 s2) ↔ + (i = 1 ∧ j = 0) ∨ + (i = 0 ∧ c1 ≤ j ∧ j < c1 + s1.countP Option.isSome) ∨ + (i = 1 ∧ c2 ≤ j ∧ j < c2 + s2.countP Option.isSome)) := by + induction L generalizing s1 s2 s12 s with + | nil => + cases s12 <;> simp [insertSlot] at hi + | cons g t ih => + cases s1 with + | nil => + cases s2 with + | nil => simp [mergeSlots] at hm; subst hm; simp [insertSlot] at hi + | cons _ _ => simp [mergeSlots] at hm + | cons o1 t1 => + cases s2 with + | nil => cases o1 <;> simp [mergeSlots] at hm + | cons o2 t2 => + cases o1 with + | none => + simp only [mergeSlots, Option.map_eq_some_iff] at hm + obtain ⟨s12', hm', rfl⟩ := hm + cases o2 with + | none => + simp only [insertSlot] at hi + by_cases hgf : g = f + · subst hgf + simp at hi; subst hi + intro c1 c2 hc2 + obtain ⟨hlen, hnd, hmem⟩ := mergeVars_props (T := T) hm' c1 c2 + refine ⟨?_, ?_, ?_⟩ + · simp [merge3Vars, hlen] + · simp only [merge3Vars, ↓reduceIte] + rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hbad + have := (hmem 1 0).mp hbad + omega + · intro i j + simp only [merge3Vars, ↓reduceIte] + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp only [List.countP_cons, Option.isSome_none, Bool.false_eq_true, ↓reduceIte] + rfl + · simp only [hgf, ↓reduceIte, Option.map_eq_some_iff] at hi + obtain ⟨s', hi', rfl⟩ := hi + intro c1 c2 hc2 + obtain ⟨hlen, hnd, hmem⟩ := ih hm' hi' c1 c2 hc2 + refine ⟨by simpa [merge3Vars, hgf] using hlen, by simpa [merge3Vars, hgf] using hnd, ?_⟩ + intro i j; simpa [merge3Vars, hgf] using hmem i j + | some b => + simp only [insertSlot] at hi + by_cases hgf : g = f + · simp [hgf] at hi + · simp only [hgf, ↓reduceIte, Option.map_eq_some_iff] at hi + obtain ⟨s', hi', rfl⟩ := hi + intro c1 c2 hc2 + obtain ⟨hlen, hnd, hmem⟩ := ih hm' hi' c1 (c2 + 1) (by omega) + refine ⟨?_, ?_, ?_⟩ + · simp [merge3Vars, hgf, hlen] + · simp only [merge3Vars, hgf, ↓reduceIte] + rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hbad + have := (hmem 1 c2).mp hbad + omega + · intro i j + simp only [merge3Vars, hgf, ↓reduceIte] + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp only [List.countP_cons, Option.isSome_none, Option.isSome_some, + Bool.false_eq_true, ↓reduceIte] + constructor + · rintro (⟨rfl, rfl⟩ | h0 | h1 | h2) + · right; right; refine ⟨rfl, Nat.le_refl _, ?_⟩; omega + · left; exact h0 + · right; left; exact h1 + · right; right; omega + · rintro (h0 | h1 | ⟨rfl, hlo, hhi⟩) + · right; left; exact h0 + · right; right; left; exact h1 + · by_cases hj : j = c2 + · left; exact ⟨rfl, hj⟩ + · right; right; right; omega + | some a => + cases o2 with + | some b => simp [mergeSlots] at hm + | none => + simp only [mergeSlots, Option.map_eq_some_iff] at hm + obtain ⟨s12', hm', rfl⟩ := hm + simp only [insertSlot] at hi + by_cases hgf : g = f + · simp [hgf] at hi + · simp only [hgf, ↓reduceIte, Option.map_eq_some_iff] at hi + obtain ⟨s', hi', rfl⟩ := hi + intro c1 c2 hc2 + obtain ⟨hlen, hnd, hmem⟩ := ih hm' hi' (c1 + 1) c2 hc2 + refine ⟨?_, ?_, ?_⟩ + · simp [merge3Vars, hgf, hlen] + · simp only [merge3Vars, hgf, ↓reduceIte] + rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hbad + have := (hmem 0 c1).mp hbad + omega + · intro i j + simp only [merge3Vars, hgf, ↓reduceIte] + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp only [List.countP_cons, Option.isSome_none, Option.isSome_some, + Bool.false_eq_true, ↓reduceIte] + constructor + · rintro (⟨rfl, rfl⟩ | h0 | h1 | h2) + · right; left; refine ⟨rfl, Nat.le_refl _, ?_⟩; omega + · left; exact h0 + · right; left; omega + · right; right; exact h2 + · rintro (h0 | ⟨rfl, hlo, hhi⟩ | h2) + · right; left; exact h0 + · by_cases hj : j = c1 + · left; exact ⟨rfl, hj⟩ + · right; right; left; omega + · right; right; right; exact h2 + +/-- Evaluation lemma for `Merge3`. -/ +theorem evalYield_merge3Vars [DecidableEq Lic] + (L : List Lic) (hLnd : L.Nodup) {f : Lic} (hfL : f ∈ L) + {tStr : List T} {δ' : List (MGFeature Base Lic)} + {ms1 ms2 : List (MGChain Base Lic T)} + (hsmc1 : SMC ms1) (hsmc2 : SMC ms2) + (hsmc3 : SMC (ms1 ++ ⟨tStr, MGFeature.licensee f :: δ'⟩ :: ms2)) : + let δ := MGFeature.licensee f :: δ' + let ms3 := ms1 ++ ⟨tStr, δ⟩ :: ms2 + insertSlot f δ L (slotsOf L (ms1 ++ ms2)) = some (slotsOf L ms3) ∧ + ∀ (p1 p2 : List (List T)), p2[0]? = some tStr → + MCFG.evalYield [p1 ++ strsOf L ms1, p2 ++ strsOf L ms2] + (merge3Vars f p1.length p2.length L (slotsOf L ms1) (slotsOf L ms2)) = + strsOf L ms3 := by + have hsmc12 : SMC (ms1 ++ ms2) := MG.smc_remove hsmc3 + induction L with + | nil => simp at hfL + | cons g t ih => + rw [List.nodup_cons] at hLnd + obtain ⟨hg_not, ht_nd⟩ := hLnd + let δ := MGFeature.licensee f :: δ' + let newC : MGChain Base Lic T := ⟨tStr, δ⟩ + let ms3 := ms1 ++ newC :: ms2 + have hnew_lic : newC.headLic = some f := rfl + have hnew_in : newC ∈ ms3 := List.mem_append_right _ (List.mem_cons_self ..) + by_cases hgf : g = f + · subst hgf + have h1 : findChain g ms1 = none := by + rw [findChain_eq_none_iff] + intro c hc hlic + have hnd := hsmc3.2 + simp only [List.filterMap_append, List.filterMap_cons, List.nodup_append] at hnd + have hm1 : g ∈ ms1.filterMap MGChain.headLic := List.mem_filterMap.mpr ⟨c, hc, hlic⟩ + exact hnd.2.2 g hm1 g (List.mem_cons_self ..) rfl + have h2 : findChain g ms2 = none := by + rw [findChain_eq_none_iff] + intro c hc hlic + have hnd := hsmc3.2 + simp only [List.filterMap_append, List.filterMap_cons, List.nodup_append] at hnd + have hm2 : g ∈ ms2.filterMap MGChain.headLic := List.mem_filterMap.mpr ⟨c, hc, hlic⟩ + exact (List.nodup_cons.mp hnd.2.1).1 hm2 + have h12 : findChain g (ms1 ++ ms2) = none := by + rw [findChain_eq_none_iff] + intro c hc + rcases List.mem_append.mp hc with hm1 | hm2 + · exact (findChain_eq_none_iff.mp h1) c hm1 + · exact (findChain_eq_none_iff.mp h2) c hm2 + have h3 : findChain g ms3 = some newC := + (findChain_eq_some_iff hsmc3).mpr ⟨hnew_in, hnew_lic⟩ + -- For every g' ∈ t, g' ≠ g, so findChain g' ms3 = findChain g' (ms1 ++ ms2) + have htail_find : ∀ g', g' ∈ t → findChain g' ms3 = findChain g' (ms1 ++ ms2) := by + intro g' hg' + have hne : g' ≠ g := fun heq => hg_not (heq ▸ hg') + cases hf12 : findChain g' (ms1 ++ ms2) with + | none => + rw [findChain_eq_none_iff] at hf12 ⊢ + intro c hc + rcases List.mem_append.mp hc with hm1 | hm2 + · exact hf12 c (List.mem_append_left _ hm1) + · rcases List.mem_cons.mp hm2 with rfl | hm2' + · simp [hnew_lic, hne.symm] + · exact hf12 c (List.mem_append_right _ hm2') + | some c => + obtain ⟨hc12, hlic⟩ := (findChain_eq_some_iff hsmc12).mp hf12 + have hc3 : c ∈ ms3 := by + rcases List.mem_append.mp hc12 with hm1 | hm2 + · exact List.mem_append_left _ hm1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ hm2) + exact (findChain_eq_some_iff hsmc3).mpr ⟨hc3, hlic⟩ + have hslots_tail : slotsOf t ms3 = slotsOf t (ms1 ++ ms2) := by + apply List.map_congr_left + intro g' hg'; rw [htail_find g' hg'] + have hstrs_tail : strsOf t ms3 = strsOf t (ms1 ++ ms2) := by + simp only [strsOf] + have : ∀ l : List Lic, (∀ g', g' ∈ l → findChain g' ms3 = findChain g' (ms1 ++ ms2)) → + l.filterMap (fun x => (findChain x ms3).map MGChain.str) = + l.filterMap (fun x => (findChain x (ms1 ++ ms2)).map MGChain.str) := by + intro l hl + induction l with + | nil => rfl + | cons a b ihb => + simp only [List.filterMap_cons, hl a (List.mem_cons_self ..)] + cases (findChain a (ms1 ++ ms2)).map MGChain.str with + | none => exact ihb (fun x hx => hl x (List.mem_cons_of_mem _ hx)) + | some s => exact congrArg (s :: ·) (ihb (fun x hx => hl x (List.mem_cons_of_mem _ hx))) + exact this t htail_find + have ⟨_, heval_mv⟩ := evalYield_mergeVars t hsmc1 hsmc2 hsmc12 + refine ⟨?_, fun p1 p2 hp2 => ?_⟩ + · rw [slotsOf_cons, slotsOf_cons, h12, h3, hslots_tail] + simp [insertSlot, newC, δ] + · rw [slotsOf_cons, slotsOf_cons, h1, h2, strsOf_cons_none h1, strsOf_cons_none h2, + strsOf_cons_some h3] + simp only [Option.map_none, merge3Vars, ↓reduceIte, MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [p1 ++ strsOf t ms1, p2 ++ strsOf t ms2] + [MCFGAtom.var 1 0] = tStr := by + have hp2_len : 0 < p2.length := by + cases p2 with + | nil => simp at hp2 + | cons _ _ => simp + simp only [MCFG.evalComp, List.getElem?_cons_succ, List.getElem?_cons_zero, + List.getElem?_append_left hp2_len, hp2, List.append_nil] + rw [hhead, hstrs_tail] + exact congrArg (tStr :: ·) (heval_mv p1 p2) + · have hf_in_t : f ∈ t := by + rcases List.mem_cons.mp hfL with rfl | ht + · exact absurd rfl hgf + · exact ht + obtain ⟨hins_t, heval_t⟩ := ih ht_nd hf_in_t + have hg_same : findChain g ms3 = findChain g (ms1 ++ ms2) := by + cases hf12 : findChain g (ms1 ++ ms2) with + | none => + rw [findChain_eq_none_iff] at hf12 ⊢ + intro c hc + rcases List.mem_append.mp hc with hm1 | hm2 + · exact hf12 c (List.mem_append_left _ hm1) + · rcases List.mem_cons.mp hm2 with rfl | hm2' + · simp [hnew_lic, Ne.symm hgf] + · exact hf12 c (List.mem_append_right _ hm2') + | some c => + obtain ⟨hc12, hlic⟩ := (findChain_eq_some_iff hsmc12).mp hf12 + have hc3 : c ∈ ms3 := by + rcases List.mem_append.mp hc12 with hm1 | hm2 + · exact List.mem_append_left _ hm1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ hm2) + exact (findChain_eq_some_iff hsmc3).mpr ⟨hc3, hlic⟩ + have hcase : + (findChain g ms1 = none ∧ findChain g ms2 = none ∧ findChain g (ms1 ++ ms2) = none) ∨ + (∃ c, findChain g ms1 = some c ∧ findChain g ms2 = none ∧ findChain g (ms1 ++ ms2) = some c) ∨ + (∃ c, findChain g ms1 = none ∧ findChain g ms2 = some c ∧ findChain g (ms1 ++ ms2) = some c) := by + cases h1 : findChain g ms1 with + | none => + cases h2 : findChain g ms2 with + | none => + left; refine ⟨rfl, rfl, ?_⟩ + rw [findChain_eq_none_iff] at h1 h2 ⊢ + intro c hc; rcases List.mem_append.mp hc with hm1 | hm2 + · exact h1 c hm1 + · exact h2 c hm2 + | some c => + right; right + obtain ⟨hc2, hf2⟩ := (findChain_eq_some_iff hsmc2).mp h2 + exact ⟨c, rfl, rfl, (findChain_eq_some_iff hsmc12).mpr ⟨List.mem_append_right _ hc2, hf2⟩⟩ + | some c => + cases h2 : findChain g ms2 with + | none => + right; left + obtain ⟨hc1, hf1⟩ := (findChain_eq_some_iff hsmc1).mp h1 + exact ⟨c, rfl, rfl, (findChain_eq_some_iff hsmc12).mpr ⟨List.mem_append_left _ hc1, hf1⟩⟩ + | some c2 => + obtain ⟨hc1, hf1⟩ := (findChain_eq_some_iff hsmc1).mp h1 + obtain ⟨hc2, hf2⟩ := (findChain_eq_some_iff hsmc2).mp h2 + have hnd := hsmc12.2 + rw [List.filterMap_append, List.nodup_append] at hnd + exact absurd rfl (hnd.2.2 g (List.mem_filterMap.mpr ⟨c, hc1, hf1⟩) g + (List.mem_filterMap.mpr ⟨c2, hc2, hf2⟩)) + rcases hcase with ⟨h1, h2, h12⟩ | ⟨c, h1, h2, h12⟩ | ⟨c, h1, h2, h12⟩ + · refine ⟨?_, fun p1 p2 hp2 => ?_⟩ + · rw [slotsOf_cons, slotsOf_cons, h12, hg_same, h12]; simp [insertSlot, hgf, hins_t] + · rw [slotsOf_cons, slotsOf_cons, h1, h2, strsOf_cons_none h1, strsOf_cons_none h2, + strsOf_cons_none (hg_same.trans h12)] + simpa [merge3Vars, hgf] using heval_t p1 p2 hp2 + · refine ⟨?_, fun p1 p2 hp2 => ?_⟩ + · rw [slotsOf_cons, slotsOf_cons, h12, hg_same, h12]; simp [insertSlot, hgf, hins_t] + · rw [slotsOf_cons, slotsOf_cons, h1, h2, strsOf_cons_some h1, strsOf_cons_none h2, + strsOf_cons_some (hg_same.trans h12)] + simp only [Option.map_some, Option.map_none, merge3Vars, hgf, ↓reduceIte, MCFG.evalYield, + List.map_cons] + have hhead : MCFG.evalComp [p1 ++ c.str :: strsOf t ms1, p2 ++ strsOf t ms2] + [MCFGAtom.var 0 p1.length] = c.str := by simp [MCFG.evalComp] + have htail := heval_t (p1 ++ [c.str]) p2 hp2 + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append] at htail + rw [hhead] + exact congrArg (c.str :: ·) htail + · refine ⟨?_, fun p1 p2 hp2 => ?_⟩ + · rw [slotsOf_cons, slotsOf_cons, h12, hg_same, h12]; simp [insertSlot, hgf, hins_t] + · rw [slotsOf_cons, slotsOf_cons, h1, h2, strsOf_cons_none h1, strsOf_cons_some h2, + strsOf_cons_some (hg_same.trans h12)] + simp only [Option.map_some, Option.map_none, merge3Vars, hgf, ↓reduceIte, MCFG.evalYield, + List.map_cons] + have hhead : MCFG.evalComp [p1 ++ strsOf t ms1, p2 ++ c.str :: strsOf t ms2] + [MCFGAtom.var 1 p2.length] = c.str := by simp [MCFG.evalComp] + have hp2' : (p2 ++ [c.str])[0]? = some tStr := by + cases p2 with + | nil => simp at hp2 + | cons x xs => simpa using hp2 + have htail := heval_t p1 (p2 ++ [c.str]) hp2' + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append] at htail + rw [hhead] + exact congrArg (c.str :: ·) htail + +/-- Converse of `insertSlot`: if `insertSlot f δ L (slotsOf L ms12) = some s`, then no chain in + `ms12` has leading licensee `f`. -/ +theorem not_mem_headLic_of_insertSlot [DecidableEq Lic] {f : Lic} {δ : List (MGFeature Base Lic)} + {L : List Lic} {ms : List (MGChain Base Lic T)} + {s : List (Option (List (MGFeature Base Lic)))} + (_hsmc : SMC ms) + (hi : insertSlot f δ L (slotsOf L ms) = some s) : + ∀ c, c ∈ ms → c.headLic ≠ some f := by + induction L generalizing s with + | nil => simp [slotsOf, insertSlot] at hi + | cons g t ih => + simp only [slotsOf, List.map_cons, insertSlot] at hi + by_cases hgf : g = f + · subst hgf + simp only [↓reduceIte] at hi + cases hfg : findChain g ms with + | none => exact findChain_eq_none_iff.mp hfg + | some _ => simp [hfg] at hi + · simp only [hgf, ↓reduceIte, Option.map_eq_some_iff] at hi + obtain ⟨s', hs', _⟩ := hi + exact ih hs' + +/-! ### Part 4: Move1 & Move2 Slot Operations -/ + +/-- Find the active component index (starting from `c`) and remaining slot list when clearing + a final mover `[licensee f]` at slot `f`. -/ +def clearSlot [DecidableEq Lic] (f : Lic) (c : Nat) : + List Lic → List (Option (List (MGFeature Base Lic))) → + Option (Nat × List (Option (List (MGFeature Base Lic))) × List (List (MCFGAtom T))) + | [], [] => none + | g :: t, o :: os => + if g = f then + match o with + | some [MGFeature.licensee f'] => + if f' = f then + let restVars := (List.range (os.countP Option.isSome)).map fun k => + [MCFGAtom.var 0 (c + 1 + k)] + some (c, none :: os, restVars) + else none + | _ => none + else + match o with + | none => + (clearSlot f c t os).map fun (p, os', vs) => (p, none :: os', vs) + | some fs => + (clearSlot f (c + 1) t os).map fun (p, os', vs) => + (p, some fs :: os', [MCFGAtom.var 0 c] :: vs) + | _, _ => none + +theorem range_vars_props (base len : Nat) : + let vs : List (List (MCFGAtom T)) := (List.range len).map fun k => [MCFGAtom.var 0 (base + k)] + vs.length = len ∧ + (compsVars vs).Nodup ∧ + (∀ i j, (i, j) ∈ compsVars vs ↔ i = 0 ∧ base ≤ j ∧ j < base + len) := by + induction len generalizing base with + | zero => + refine ⟨rfl, List.nodup_nil, ?_⟩ + intro i j; simp [compsVars] + | succ len ih => + have hr : List.range (len + 1) = 0 :: (List.range len).map Nat.succ := + List.range_succ_eq_map (n := len) + obtain ⟨hlen, hnd, hmem⟩ := ih (base + 1) + have hmap : ((List.range (len + 1)).map fun k => [MCFGAtom.var (T := T) 0 (base + k)]) = + [MCFGAtom.var 0 base] :: ((List.range len).map fun k => [MCFGAtom.var 0 (base + 1 + k)]) := by + rw [hr, List.map_cons, List.map_map] + simp only [Nat.add_zero] + congr 1 + apply List.map_congr_left + intro k _ + have hidx : base + k.succ = base + 1 + k := by omega + simp [Function.comp, hidx] + simp only [hmap] + refine ⟨?_, ?_, ?_⟩ + · simp [hlen] + · rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hbad + have := (hmem 0 base).mp hbad + omega + · intro i j + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi⟩) + · refine ⟨rfl, Nat.le_refl _, ?_⟩; omega + · refine ⟨rfl, ?_, ?_⟩ <;> omega + · rintro ⟨rfl, hlo, hhi⟩ + by_cases hj : j = base + · left; exact ⟨rfl, hj⟩ + · right; refine ⟨rfl, ?_, ?_⟩ <;> omega + +theorem clearSlot_props [DecidableEq Lic] {f : Lic} + {L : List Lic} {s s' : List (Option (List (MGFeature Base Lic)))} + {p : Nat} {vs : List (List (MCFGAtom T))} {c : Nat} + (h : clearSlot f c L s = some (p, s', vs)) : + c ≤ p ∧ p < c + s.countP Option.isSome ∧ + vs.length = s'.countP Option.isSome ∧ + (compsVars vs).Nodup ∧ + (∀ i j, (i, j) ∈ compsVars vs ↔ + i = 0 ∧ c ≤ j ∧ j < c + s.countP Option.isSome ∧ j ≠ p) := by + induction L generalizing s s' p vs c with + | nil => cases s <;> simp [clearSlot] at h + | cons g t ih => + cases s with + | nil => simp [clearSlot] at h + | cons o os => + simp only [clearSlot] at h + by_cases hgf : g = f + · subst hgf + simp only [↓reduceIte] at h + cases o with + | none => simp at h + | some fs => + cases fs with + | nil => simp at h + | cons hd tl => + cases hd with + | licensee f' => + cases tl with + | cons _ _ => simp at h + | nil => + by_cases hff' : f' = g + · subst hff' + simp at h + obtain ⟨rfl, rfl, rfl⟩ := h + obtain ⟨hlen, hnd, hmem⟩ := range_vars_props (T := T) (c + 1) (os.countP Option.isSome) + refine ⟨Nat.le_refl _, ?_, ?_, hnd, ?_⟩ + · simp + · simp [hlen] + · intro i j + rw [hmem i j] + simp only [List.countP_cons, Option.isSome_some, ↓reduceIte] + omega + · simp [hff'] at h + | _ => simp at h + · simp only [hgf, ↓reduceIte] at h + cases o with + | none => + simp only [Option.map_eq_some_iff] at h + obtain ⟨⟨p', os', vs'⟩, hrec, heq⟩ := h + simp at heq; obtain ⟨rfl, rfl, rfl⟩ := heq + obtain ⟨h1, h2, h3, h4, h5⟩ := ih hrec + simpa using ⟨h1, h2, h3, h4, h5⟩ + | some fs => + simp only [Option.map_eq_some_iff] at h + obtain ⟨⟨p', os', vs'⟩, hrec, heq⟩ := h + simp at heq; obtain ⟨rfl, rfl, rfl⟩ := heq + obtain ⟨h1, h2, h3, h4, h5⟩ := ih hrec + refine ⟨by omega, ?_, ?_, ?_, ?_⟩ + · simp; omega + · simp [h3] + · rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, h4⟩ + intro hbad + have := (h5 0 c).mp hbad + omega + · intro i j + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, h5 i j] + simp only [List.countP_cons, Option.isSome_some, ↓reduceIte] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi, hne⟩) + · refine ⟨rfl, Nat.le_refl _, ?_, ?_⟩ <;> omega + · refine ⟨rfl, ?_, ?_, hne⟩ <;> omega + · rintro ⟨rfl, hlo, hhi, hne⟩ + by_cases hj : j = c + · left; exact ⟨rfl, hj⟩ + · right; refine ⟨rfl, ?_, ?_, hne⟩ <;> omega + +theorem evalYield_range_vars (pre mid : List (List T)) : + MCFG.evalYield [pre ++ mid] + ((List.range mid.length).map fun k => [MCFGAtom.var 0 (pre.length + k)]) = mid := by + induction mid generalizing pre with + | nil => rfl + | cons a t ih => + have hr : List.range (t.length + 1) = 0 :: (List.range t.length).map Nat.succ := + List.range_succ_eq_map (n := t.length) + simp only [List.length_cons, hr, List.map_cons, List.map_map, MCFG.evalYield] + have hhead : MCFG.evalComp [pre ++ a :: t] [MCFGAtom.var 0 (pre.length + 0)] = a := by + simp [MCFG.evalComp] + rw [hhead] + congr 1 + have htail := ih (pre ++ [a]) + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append, MCFG.evalYield, List.map_map] at htail + refine Eq.trans ?_ htail + apply List.map_congr_left + intro k _ + have hidx : pre.length + k.succ = pre.length + 1 + k := by omega + simp [Function.comp, hidx] + +theorem evalYield_range_vars1 (u0 pre mid : List (List T)) : + MCFG.evalYield [u0, pre ++ mid] + ((List.range mid.length).map fun k => [MCFGAtom.var 1 (pre.length + k)]) = mid := by + induction mid generalizing pre with + | nil => rfl + | cons a t ih => + have hr : List.range (t.length + 1) = 0 :: (List.range t.length).map Nat.succ := + List.range_succ_eq_map (n := t.length) + simp only [List.length_cons, hr, List.map_cons, List.map_map, MCFG.evalYield] + have hhead : MCFG.evalComp [u0, pre ++ a :: t] [MCFGAtom.var 1 (pre.length + 0)] = a := by + simp [MCFG.evalComp] + rw [hhead] + congr 1 + have htail := ih (pre ++ [a]) + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append, MCFG.evalYield, List.map_map] at htail + refine Eq.trans ?_ htail + apply List.map_congr_left + intro k _ + have hidx : pre.length + k.succ = pre.length + 1 + k := by omega + simp [Function.comp, hidx] + +/-- Evaluation & soundness helper for `Move1` (`clearSlot`). -/ +theorem clearSlot_eval_and_mem [DecidableEq Lic] + (L : List Lic) (hLnd : L.Nodup) {f : Lic} + {ms : List (MGChain Base Lic T)} (hsmc : SMC ms) + {p : Nat} {s' : List (Option (List (MGFeature Base Lic)))} {vs : List (List (MCFGAtom T))} : + ∀ (pre : List (List T)), + clearSlot f pre.length L (slotsOf L ms) = some (p, s', vs) → + ∃ tStr ms1 ms2, + ms = ms1 ++ ⟨tStr, [MGFeature.licensee f]⟩ :: ms2 ∧ + slotsOf L (ms1 ++ ms2) = s' ∧ + (pre ++ strsOf L ms)[p]? = some tStr ∧ + MCFG.evalYield [pre ++ strsOf L ms] vs = strsOf L (ms1 ++ ms2) := by + induction L generalizing p s' vs with + | nil => intro pre h; simp [slotsOf, clearSlot] at h + | cons g t ih => + rw [List.nodup_cons] at hLnd + obtain ⟨hg_not, ht_nd⟩ := hLnd + intro pre h + rw [slotsOf_cons] at h + simp only [clearSlot] at h + by_cases hgf : g = f + · subst hgf + simp only [↓reduceIte] at h + cases hfg : findChain g ms with + | none => simp [hfg] at h + | some c => + rw [hfg] at h + simp only [Option.map_some] at h + cases hcf : c.feats with + | nil => simp [hcf] at h + | cons hd tl => + cases hd with + | licensee f' => + cases tl with + | cons _ _ => simp [hcf] at h + | nil => + by_cases hff' : f' = g + · subst f' + simp [hcf] at h + obtain ⟨rfl, rfl, rfl⟩ := h + obtain ⟨hc_in, hlic⟩ := (findChain_eq_some_iff hsmc).mp hfg + obtain ⟨ms1, ms2, hms_eq⟩ := List.append_of_mem hc_in + have hce : c = ⟨c.str, [MGFeature.licensee g]⟩ := by + cases c; simp at hcf; subst hcf; rfl + have hms_eq' : ms = ms1 ++ ⟨c.str, [MGFeature.licensee g]⟩ :: ms2 := by + rw [← hce]; exact hms_eq + have hsmc' : SMC (ms1 ++ ms2) := MG.smc_remove (hms_eq ▸ hsmc) + have htail_find : ∀ x, x ∈ t → findChain x (ms1 ++ ms2) = findChain x ms := by + intro x hx + have hne : x ≠ g := fun heq => hg_not (heq ▸ hx) + cases hfx : findChain x ms with + | none => + rw [findChain_eq_none_iff] at hfx ⊢ + intro y hy + apply hfx y + rw [hms_eq] + rcases List.mem_append.mp hy with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2) + | some y => + obtain ⟨hy_in, hy_lic⟩ := (findChain_eq_some_iff hsmc).mp hfx + have hy_ne : y ≠ c := fun heq => by subst heq; rw [hlic] at hy_lic; simp at hy_lic; exact hne hy_lic.symm + have hy_in' : y ∈ ms1 ++ ms2 := by + rw [hms_eq] at hy_in + rcases List.mem_append.mp hy_in with h1 | h2 + · exact List.mem_append_left _ h1 + · rcases List.mem_cons.mp h2 with rfl | h2' + · exact absurd rfl hy_ne + · exact List.mem_append_right _ h2' + exact (findChain_eq_some_iff hsmc').mpr ⟨hy_in', hy_lic⟩ + have hfg' : findChain g (ms1 ++ ms2) = none := by + rw [findChain_eq_none_iff] + intro y hy hy_lic + have hy_in : y ∈ ms := by + rw [hms_eq] + rcases List.mem_append.mp hy with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2) + have hy_eq := smc_unique_chain hsmc hy_in hy_lic hc_in hlic + subst hy_eq + have hnd := hsmc.2 + rw [hms_eq] at hnd + simp only [List.filterMap_append, List.filterMap_cons, hlic, List.nodup_append] at hnd + rcases List.mem_append.mp hy with h1 | h2 + · exact hnd.2.2 g (List.mem_filterMap.mpr ⟨y, h1, hlic⟩) g (List.mem_cons_self ..) rfl + · exact (List.nodup_cons.mp hnd.2.1).1 (List.mem_filterMap.mpr ⟨y, h2, hlic⟩) + have hslots_tail : slotsOf t (ms1 ++ ms2) = slotsOf t ms := by + apply List.map_congr_left; intro x hx; rw [htail_find x hx] + have hstrs_tail : strsOf t (ms1 ++ ms2) = strsOf t ms := by + simp only [strsOf] + have : ∀ l : List Lic, (∀ x, x ∈ l → findChain x (ms1 ++ ms2) = findChain x ms) → + l.filterMap (fun x => (findChain x (ms1 ++ ms2)).map MGChain.str) = + l.filterMap (fun x => (findChain x ms).map MGChain.str) := by + intro l hl + induction l with + | nil => rfl + | cons a b ihb => + simp only [List.filterMap_cons, hl a (List.mem_cons_self ..)] + cases (findChain a ms).map MGChain.str with + | none => exact ihb (fun x hx => hl x (List.mem_cons_of_mem _ hx)) + | some s => exact congrArg (s :: ·) (ihb (fun x hx => hl x (List.mem_cons_of_mem _ hx))) + exact this t htail_find + refine ⟨c.str, ms1, ms2, hms_eq', ?_, ?_, ?_⟩ + · rw [slotsOf_cons, hfg']; simp [hslots_tail] + · rw [strsOf_cons_some hfg]; simp + · rw [strsOf_cons_some hfg, strsOf_cons_none hfg', hstrs_tail, ← strsOf_length t ms] + have hev := evalYield_range_vars (pre ++ [c.str]) (strsOf t ms) + simp only [List.length_append, List.length_singleton, List.append_assoc, + List.singleton_append] at hev + exact hev + · simp [hcf, hff'] at h + | _ => simp [hcf] at h + · simp only [hgf, ↓reduceIte] at h + cases hfg : findChain g ms with + | none => + simp only [hfg, Option.map_none, Option.map_eq_some_iff] at h + obtain ⟨⟨p', os', vs'⟩, hrec, heq⟩ := h + simp at heq; obtain ⟨rfl, rfl, rfl⟩ := heq + obtain ⟨tStr, ms1, ms2, hms_eq, hslots_t, hget, heval⟩ := ih ht_nd pre hrec + have hfg' : findChain g (ms1 ++ ms2) = none := by + rw [findChain_eq_none_iff] at hfg ⊢ + intro y hy + apply hfg y + rw [hms_eq] + rcases List.mem_append.mp hy with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2) + refine ⟨tStr, ms1, ms2, hms_eq, ?_, ?_, ?_⟩ + · rw [slotsOf_cons, hfg']; simp [hslots_t] + · rw [strsOf_cons_none hfg]; exact hget + · rw [strsOf_cons_none hfg, strsOf_cons_none hfg']; exact heval + | some c => + simp only [hfg, Option.map_some, Option.map_eq_some_iff] at h + obtain ⟨⟨p', os', vs'⟩, hrec, heq⟩ := h + simp at heq; obtain ⟨rfl, rfl, rfl⟩ := heq + have hrec' : clearSlot f (pre ++ [c.str]).length t (slotsOf t ms) = some (p', os', vs') := by + simpa [List.length_append] using hrec + obtain ⟨tStr, ms1, ms2, hms_eq, hslots_t, hget, heval⟩ := ih ht_nd (pre ++ [c.str]) hrec' + obtain ⟨hc_in, hlic⟩ := (findChain_eq_some_iff hsmc).mp hfg + have hsmc' : SMC (ms1 ++ ms2) := MG.smc_remove (hms_eq ▸ hsmc) + have hc_in' : c ∈ ms1 ++ ms2 := by + rw [hms_eq] at hc_in + rcases List.mem_append.mp hc_in with h1 | h2 + · exact List.mem_append_left _ h1 + · rcases List.mem_cons.mp h2 with heq | h2' + · subst heq; simp [MGChain.headLic] at hlic; exact absurd hlic.symm hgf + · exact List.mem_append_right _ h2' + have hfg' : findChain g (ms1 ++ ms2) = some c := + (findChain_eq_some_iff hsmc').mpr ⟨hc_in', hlic⟩ + refine ⟨tStr, ms1, ms2, hms_eq, ?_, ?_, ?_⟩ + · rw [slotsOf_cons, hfg']; simp [hslots_t] + · rw [strsOf_cons_some hfg]; simpa [List.append_assoc] using hget + · rw [strsOf_cons_some hfg, strsOf_cons_some hfg'] + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [pre ++ c.str :: strsOf t ms] + [MCFGAtom.var 0 pre.length] = c.str := by simp [MCFG.evalComp] + rw [hhead] + congr 1 + simpa [MCFG.evalYield, List.append_assoc] using heval + +/-- Completeness helper for `Move1`: if `ms = ms1 ++ ⟨tStr, [licensee f]⟩ :: ms2` and `f ∈ L`, + then `clearSlot f c L (slotsOf L ms)` succeeds. -/ +theorem clearSlot_complete [DecidableEq Lic] + (L : List Lic) {f : Lic} (hfL : f ∈ L) + {tStr : List T} {ms1 ms2 : List (MGChain Base Lic T)} + (hsmc : SMC (ms1 ++ ⟨tStr, [MGFeature.licensee f]⟩ :: ms2)) : + ∀ c, ∃ p s' vs, + clearSlot (T := T) f c L (slotsOf L (ms1 ++ ⟨tStr, [MGFeature.licensee f]⟩ :: ms2)) = + some (p, s', vs) := by + let ms := ms1 ++ ⟨tStr, [MGFeature.licensee f]⟩ :: ms2 + induction L with + | nil => simp at hfL + | cons g t ih => + intro c + rw [slotsOf_cons] + simp only [clearSlot] + by_cases hgf : g = f + · subst g + have hfind : findChain f ms = some ⟨tStr, [MGFeature.licensee f]⟩ := + (findChain_eq_some_iff hsmc).mpr + ⟨List.mem_append_right _ (List.mem_cons_self ..), rfl⟩ + simp [ms, hfind] + · simp only [hgf, ↓reduceIte] + have hft : f ∈ t := by + rcases List.mem_cons.mp hfL with rfl | ht + · exact absurd rfl hgf + · exact ht + cases hfg : findChain g ms with + | none => + obtain ⟨p, s', vs, hrec⟩ := ih hft c + exact ⟨p, none :: s', vs, by simp [hrec]⟩ + | some ch => + obtain ⟨p, s', vs, hrec⟩ := ih hft (c + 1) + exact ⟨p, some ch.feats :: s', [MCFGAtom.var 0 c] :: vs, by simp [hrec]⟩ + +/-! ### Move2: Relocating a Mover from Slot `f` to Slot `f'` -/ + +/-- Find the active component index (starting from `c`) of slot `f` in `L`, plus its feature stack. -/ +def locateSlot [DecidableEq Lic] (f : Lic) (c : Nat) : + List Lic → List (Option (List (MGFeature Base Lic))) → + Option (Nat × List (MGFeature Base Lic)) + | [], [] => none + | g :: t, o :: os => + if g = f then + match o with + | some fs => some (c, fs) + | none => none + else + match o with + | none => locateSlot f c t os + | some _ => locateSlot f (c + 1) t os + | _, _ => none + +/-- Traverse the slots while indexing the nonempty components of the original tuple. -/ +def relocateSlot.go [DecidableEq Lic] (f f' : Lic) + (δ : List (MGFeature Base Lic)) (pSrc : Nat) (c : Nat) : + List Lic → List (Option (List (MGFeature Base Lic))) → + Option (List (Option (List (MGFeature Base Lic))) × List (List (MCFGAtom T))) + | [], [] => some ([], []) + | g :: t, o :: os => + if g = f ∧ g = f' then + -- Same slot: feature stack updates in place, variable stays `[var 0 pSrc]` (= `[var 0 c]`). + (go f f' δ pSrc (c + 1) t os).map fun (os', vs) => (some δ :: os', [MCFGAtom.var 0 pSrc] :: vs) + else if g = f then + -- Source slot becomes `none` (skip `c`). + (go f f' δ pSrc (c + 1) t os).map fun (os', vs) => (none :: os', vs) + else if g = f' then + -- Destination slot must currently be `none` (by SMC!). + match o with + | none => (go f f' δ pSrc c t os).map fun (os', vs) => (some δ :: os', [MCFGAtom.var 0 pSrc] :: vs) + | some _ => none + else + match o with + | none => (go f f' δ pSrc c t os).map fun (os', vs) => (none :: os', vs) + | some fs' => (go f f' δ pSrc (c + 1) t os).map fun (os', vs) => (some fs' :: os', [MCFGAtom.var 0 c] :: vs) + | _, _ => none + +/-- Compute the updated slot list and variable permutation for `Move2`: + slot `f` had `licensee f :: licensee f' :: δ'`; move it to slot `f'` with `licensee f' :: δ'`. -/ +def relocateSlot [DecidableEq Base] [DecidableEq Lic] (f f' : Lic) (δ : List (MGFeature Base Lic)) + (L : List Lic) (s : List (Option (List (MGFeature Base Lic)))) : + Option (List (Option (List (MGFeature Base Lic))) × List (List (MCFGAtom T))) := + match locateSlot f 1 L s with + | none => none + | some (pSrc, fs) => + if fs = MGFeature.licensee f :: δ then + if f' ∈ L then relocateSlot.go f f' δ pSrc 1 L s else none + else none + +/-- Auxiliary properties of `locateSlot`. -/ +theorem locateSlot_props [DecidableEq Lic] {f : Lic} {c p : Nat} + {L : List Lic} {s : List (Option (List (MGFeature Base Lic)))} + {fs : List (MGFeature Base Lic)} + (h : locateSlot f c L s = some (p, fs)) : + f ∈ L ∧ c ≤ p ∧ p < c + s.countP Option.isSome := by + induction L generalizing s c with + | nil => cases s <;> simp [locateSlot] at h + | cons g t ih => + cases s with + | nil => simp [locateSlot] at h + | cons o os => + simp only [locateSlot] at h + by_cases hgf : g = f + · subst hgf + cases o with + | none => simp at h + | some fs' => + simp at h; obtain ⟨rfl, rfl⟩ := h + exact ⟨List.mem_cons_self .., Nat.le_refl _, by simp⟩ + · simp only [hgf, ↓reduceIte] at h + cases o with + | none => + obtain ⟨h1, h2, h3⟩ := ih h + exact ⟨List.mem_cons_of_mem _ h1, h2, by simp; omega⟩ + | some _ => + obtain ⟨h1, h2, h3⟩ := ih h + exact ⟨List.mem_cons_of_mem _ h1, by omega, by simp; omega⟩ + +/-- Auxiliary properties of `relocateSlot.go` guaranteeing exact linearity & non-erasing bijection. -/ +theorem relocateSlot_go_props [DecidableEq Lic] {f f' : Lic} {δ : List (MGFeature Base Lic)} + {pSrc : Nat} : + ∀ (c : Nat) (L : List Lic) (s s' : List (Option (List (MGFeature Base Lic)))) + (vs : List (List (MCFGAtom T))), + L.Nodup → + (f ∈ L → ∃ fs, locateSlot f c L s = some (pSrc, fs)) → + (f ∉ L → pSrc < c) → + relocateSlot.go f f' δ pSrc c L s = some (s', vs) → + vs.length = s'.countP Option.isSome ∧ + (compsVars vs).Nodup ∧ + (∀ i j, (i, j) ∈ compsVars vs ↔ + (i = 0 ∧ f' ∈ L ∧ j = pSrc) ∨ + (i = 0 ∧ c ≤ j ∧ j < c + s.countP Option.isSome ∧ (f ∈ L → j ≠ pSrc))) := by + intro c L + induction L generalizing c with + | nil => + intro s s' vs _ _ _ hgo + cases s with + | nil => + simp [relocateSlot.go] at hgo + obtain ⟨rfl, rfl⟩ := hgo + refine ⟨rfl, List.nodup_nil, ?_⟩ + intro i j; simp [compsVars] + | cons _ _ => simp [relocateSlot.go] at hgo + | cons g t ih => + intro s s' vs hnd hloc hnot hgo + rw [List.nodup_cons] at hnd + obtain ⟨hg_not, ht_nd⟩ := hnd + cases s with + | nil => simp [relocateSlot.go] at hgo + | cons o os => + simp only [relocateSlot.go] at hgo + by_cases hgf : g = f + · subst hgf + obtain ⟨fs, hloc_g⟩ := hloc (List.mem_cons_self ..) + simp only [locateSlot, ↓reduceIte] at hloc_g + cases o with + | none => simp at hloc_g + | some fs0 => + simp at hloc_g; obtain ⟨rfl, rfl⟩ := hloc_g + by_cases hgf' : g = f' + · subst hgf' + simp only [and_self, ↓reduceIte, Option.map_eq_some_iff] at hgo + obtain ⟨⟨os', vs'⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + obtain ⟨hlen, hnd', hmem⟩ := ih (c + 1) os os' vs' ht_nd + (fun hbad => absurd hbad hg_not) (fun _ => by omega) hrec + refine ⟨by simp [hlen], ?_, ?_⟩ + · rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd'⟩ + intro hbad + have := (hmem 0 c).mp hbad + rcases this with ⟨_, hbad', _⟩ | ⟨_, hlo, _, _⟩ + · exact hg_not hbad' + · omega + · intro i j + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp only [List.mem_cons, true_or, List.countP_cons, Option.isSome_some, ↓reduceIte, + hg_not, false_and, and_false, false_or, false_implies, and_true, true_and, true_implies] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi⟩) + · left; exact ⟨rfl, rfl⟩ + · right; refine ⟨rfl, ?_, ?_, ?_⟩ <;> omega + · rintro (⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi, hne⟩) + · left; exact ⟨rfl, rfl⟩ + · right; refine ⟨rfl, ?_, ?_⟩ <;> omega + · simp only [hgf', and_false, ↓reduceIte, Option.map_eq_some_iff] at hgo + obtain ⟨⟨os', vs'⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + obtain ⟨hlen, hnd', hmem⟩ := ih (c + 1) os os' vs' ht_nd + (fun hbad => absurd hbad hg_not) (fun _ => by omega) hrec + refine ⟨by simp [hlen], hnd', ?_⟩ + intro i j + rw [hmem i j] + simp only [List.mem_cons, Ne.symm hgf', false_or, true_or, List.countP_cons, + Option.isSome_some, ↓reduceIte, hg_not, false_implies, and_true, true_implies] + constructor + · rintro (h1 | ⟨rfl, hlo, hhi⟩) + · left; exact h1 + · right; refine ⟨rfl, ?_, ?_, ?_⟩ <;> omega + · rintro (h1 | ⟨rfl, hlo, hhi, hne⟩) + · left; exact h1 + · right; refine ⟨rfl, ?_, ?_⟩ <;> omega + · simp only [hgf, false_and, ↓reduceIte] at hgo + by_cases hgf' : g = f' + · subst hgf' + simp only [↓reduceIte] at hgo + cases o with + | some _ => simp at hgo + | none => + simp only [Option.map_eq_some_iff] at hgo + obtain ⟨⟨os', vs'⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hloc_t : f ∈ t → ∃ fs, locateSlot f c t os = some (pSrc, fs) := by + intro hft + obtain ⟨fs, h1⟩ := hloc (List.mem_cons_of_mem _ hft) + exact ⟨fs, by simpa [locateSlot, hgf] using h1⟩ + have hnot_t : f ∉ t → pSrc < c := fun hnt => + hnot (fun hm => by + rcases List.mem_cons.mp hm with rfl | ht' + · exact hgf rfl + · exact hnt ht') + obtain ⟨hlen, hnd', hmem⟩ := ih c os os' vs' ht_nd hloc_t hnot_t hrec + refine ⟨by simp [hlen], ?_, ?_⟩ + · rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd'⟩ + intro hbad + have := (hmem 0 pSrc).mp hbad + rcases this with ⟨_, hbad', _⟩ | ⟨_, hlo, _, hne⟩ + · exact hg_not hbad' + · by_cases hft : f ∈ t + · exact hne hft rfl + · have := hnot_t hft; omega + · intro i j + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp [List.mem_cons, hg_not, Ne.symm hgf] + · simp only [hgf', ↓reduceIte] at hgo + cases o with + | none => + simp only [Option.map_eq_some_iff] at hgo + obtain ⟨⟨os', vs'⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hloc_t : f ∈ t → ∃ fs, locateSlot f c t os = some (pSrc, fs) := by + intro hft + obtain ⟨fs, h1⟩ := hloc (List.mem_cons_of_mem _ hft) + exact ⟨fs, by simpa [locateSlot, hgf] using h1⟩ + have hnot_t : f ∉ t → pSrc < c := fun hnt => + hnot (fun hm => by + rcases List.mem_cons.mp hm with rfl | ht' + · exact hgf rfl + · exact hnt ht') + obtain ⟨hlen, hnd', hmem⟩ := ih c os os' vs' ht_nd hloc_t hnot_t hrec + refine ⟨by simp [hlen], hnd', ?_⟩ + intro i j + rw [hmem i j] + simp [List.mem_cons, Ne.symm hgf', Ne.symm hgf] + | some fs0 => + simp only [Option.map_eq_some_iff] at hgo + obtain ⟨⟨os', vs'⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hloc_t : f ∈ t → ∃ fs, locateSlot f (c + 1) t os = some (pSrc, fs) := by + intro hft + obtain ⟨fs, h1⟩ := hloc (List.mem_cons_of_mem _ hft) + exact ⟨fs, by simpa [locateSlot, hgf] using h1⟩ + have hnot_t : f ∉ t → pSrc < c + 1 := fun hnt => by + have := hnot (fun hm => by + rcases List.mem_cons.mp hm with rfl | ht' + · exact hgf rfl + · exact hnt ht') + omega + have hp_ne_c : pSrc ≠ c := by + by_cases hft : f ∈ t + · obtain ⟨fs, hl⟩ := hloc_t hft + have ⟨_, hge, _⟩ := locateSlot_props hl + omega + · have := hnot (fun hm => by + rcases List.mem_cons.mp hm with rfl | ht' + · exact hgf rfl + · exact hft ht') + omega + obtain ⟨hlen, hnd', hmem⟩ := ih (c + 1) os os' vs' ht_nd hloc_t hnot_t hrec + refine ⟨by simp [hlen], ?_, ?_⟩ + · rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd'⟩ + intro hbad + have := (hmem 0 c).mp hbad + rcases this with ⟨_, _, heq⟩ | ⟨_, hlo, _, _⟩ + · exact hp_ne_c heq.symm + · omega + · intro i j + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + simp only [List.mem_cons, Ne.symm hgf', Ne.symm hgf, false_or, + List.countP_cons, Option.isSome_some, ↓reduceIte] + constructor + · rintro (⟨rfl, rfl⟩ | h1 | ⟨rfl, hlo, hhi, hne⟩) + · right; refine ⟨rfl, Nat.le_refl _, ?_, fun _ => Ne.symm hp_ne_c⟩; omega + · left; exact h1 + · right; refine ⟨rfl, ?_, ?_, hne⟩ <;> omega + · rintro (h1 | ⟨rfl, hlo, hhi, hne⟩) + · right; left; exact h1 + · by_cases hj : j = c + · left; exact ⟨rfl, hj⟩ + · right; right; refine ⟨rfl, ?_, ?_, hne⟩ <;> omega + +theorem relocateSlot_props [DecidableEq Base] [DecidableEq Lic] {f f' : Lic} {δ : List (MGFeature Base Lic)} + {L : List Lic} (hnd : L.Nodup) + {s s' : List (Option (List (MGFeature Base Lic)))} {vs : List (List (MCFGAtom T))} + (h : relocateSlot f f' δ L s = some (s', vs)) : + vs.length = s'.countP Option.isSome ∧ + (compsVars vs).Nodup ∧ + (∀ i j, (i, j) ∈ compsVars vs ↔ i = 0 ∧ 1 ≤ j ∧ j < 1 + s.countP Option.isSome) := by + unfold relocateSlot at h + cases hloc : locateSlot f 1 L s with + | none => simp [hloc] at h + | some pr => + obtain ⟨pSrc, fs⟩ := pr + simp only [hloc] at h + by_cases hfs : fs = MGFeature.licensee f :: δ + · simp only [hfs, ↓reduceIte] at h + by_cases hf' : f' ∈ L + · simp only [hf', ↓reduceIte] at h + have ⟨hfL, hge, hlt⟩ := locateSlot_props hloc + obtain ⟨hlen, hnd', hmem⟩ := relocateSlot_go_props (T := T) 1 L s s' vs hnd + (fun _ => ⟨fs, hloc⟩) (fun hnot => absurd hfL hnot) h + refine ⟨hlen, hnd', ?_⟩ + intro i j + rw [hmem i j] + simp only [hf', hfL, true_and, true_implies] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, h1, h2, _⟩) + · exact ⟨rfl, hge, hlt⟩ + · exact ⟨rfl, h1, h2⟩ + · rintro ⟨rfl, h1, h2⟩ + by_cases hj : j = pSrc + · left; exact ⟨rfl, hj⟩ + · right; exact ⟨rfl, h1, h2, hj⟩ + · simp [hf'] at h + · simp [hfs] at h + +/-- Helper: `locateSlot` recovers the exact chain and string at position `pSrc`. -/ +theorem locateSlot_eval [DecidableEq Lic] {f : Lic} + (L : List Lic) {ms : List (MGChain Base Lic T)} (_hsmc : SMC ms) + {p : Nat} {fs : List (MGFeature Base Lic)} : + ∀ (pre : List (List T)), + locateSlot f pre.length L (slotsOf L ms) = some (p, fs) → + ∃ c, findChain f ms = some c ∧ c.feats = fs ∧ (pre ++ strsOf L ms)[p]? = some c.str := by + induction L generalizing p with + | nil => intro pre h; simp [slotsOf, locateSlot] at h + | cons g t ih => + intro pre h + rw [slotsOf_cons] at h + simp only [locateSlot] at h + by_cases hgf : g = f + · subst hgf + simp only [↓reduceIte] at h + cases hfg : findChain g ms with + | none => simp [hfg] at h + | some c => + simp [hfg] at h; obtain ⟨rfl, rfl⟩ := h + exact ⟨c, rfl, rfl, by rw [strsOf_cons_some hfg]; simp⟩ + · simp only [hgf, ↓reduceIte] at h + cases hfg : findChain g ms with + | none => + simp only [hfg, Option.map_none] at h + obtain ⟨c, hc, hcf, hget⟩ := ih pre h + exact ⟨c, hc, hcf, by rw [strsOf_cons_none hfg]; exact hget⟩ + | some cg => + simp only [hfg, Option.map_some] at h + have h' : locateSlot f (pre ++ [cg.str]).length t (slotsOf t ms) = some (p, fs) := by + simpa [List.length_append] using h + obtain ⟨c, hc, hcf, hget⟩ := ih (pre ++ [cg.str]) h' + exact ⟨c, hc, hcf, by rw [strsOf_cons_some hfg]; simpa [List.append_assoc] using hget⟩ + +private theorem relocateSlot_go_eval [DecidableEq Lic] + {f f' : Lic} {δ' : List (MGFeature Base Lic)} + (L : List Lic) {ms : List (MGChain Base Lic T)} (hsmc : SMC ms) + (sHead : List T) (pSrc : Nat) (c : MGChain Base Lic T) + (hfc : findChain f ms = some c) (hgetSrc : (sHead :: strsOf L ms)[pSrc]? = some c.str) + (hc_in : c ∈ ms) (hlic : c.headLic = some f) + (ms1 ms2 : List (MGChain Base Lic T)) (hms_eq : ms = ms1 ++ c :: ms2) : + let δ := MGFeature.licensee f' :: δ' + let newC : MGChain Base Lic T := ⟨c.str, MGFeature.licensee f' :: δ'⟩ + let msNew := ms1 ++ newC :: ms2 + SMC msNew → + ∀ (L0 : List Lic) (pre : List (List T)) + (os' : List (Option (List (MGFeature Base Lic)))) (vs0 : List (List (MCFGAtom T))), + pre ++ strsOf L0 ms = sHead :: strsOf L ms → + relocateSlot.go f f' δ pSrc pre.length L0 (slotsOf L0 ms) = some (os', vs0) → + slotsOf L0 msNew = os' ∧ + MCFG.evalYield [sHead :: strsOf L ms] vs0 = strsOf L0 msNew := by + intro δ newC msNew hsmcNew + intro L0 + induction L0 with + | nil => + intro pre os' vs0 _ hgo + simp [slotsOf, relocateSlot.go] at hgo + obtain ⟨rfl, rfl⟩ := hgo + exact ⟨rfl, rfl⟩ + | cons g t ih => + intro pre os' vs0 hpre hgo + rw [slotsOf_cons] at hgo + simp only [relocateSlot.go] at hgo + have hfind_other : g ≠ f → g ≠ f' → findChain g msNew = findChain g ms := by + intro hgf hgf' + cases hfg : findChain g ms with + | none => + rw [findChain_eq_none_iff] at hfg ⊢ + intro y hy + rcases List.mem_append.mp hy with h1 | h2 + · exact hfg y (hms_eq ▸ List.mem_append_left _ h1) + · rcases List.mem_cons.mp h2 with rfl | h2' + · simp [newC, MGChain.headLic, Ne.symm hgf'] + · exact hfg y (hms_eq ▸ List.mem_append_right _ (List.mem_cons_of_mem _ h2')) + | some y => + obtain ⟨hy_in, hy_lic⟩ := (findChain_eq_some_iff hsmc).mp hfg + have hy_in' : y ∈ msNew := by + rw [hms_eq] at hy_in + rcases List.mem_append.mp hy_in with h1 | h2 + · exact List.mem_append_left _ h1 + · rcases List.mem_cons.mp h2 with rfl | h2' + · rw [hlic] at hy_lic; simp at hy_lic; exact absurd hy_lic.symm hgf + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2') + exact (findChain_eq_some_iff hsmcNew).mpr ⟨hy_in', hy_lic⟩ + have hfind_f' : findChain f' msNew = some newC := + (findChain_eq_some_iff hsmcNew).mpr ⟨List.mem_append_right _ (List.mem_cons_self ..), rfl⟩ + have hfind_f_ne : f ≠ f' → findChain f msNew = none := by + intro hne + rw [findChain_eq_none_iff] + intro y hy hylic + rcases List.mem_append.mp hy with h1 | h2 + · have hy_eq := smc_unique_chain hsmc (hms_eq ▸ List.mem_append_left _ h1) hylic hc_in hlic + subst hy_eq + have hnd0 := hsmc.2; rw [hms_eq] at hnd0 + simp only [List.filterMap_append, List.filterMap_cons, hlic, List.nodup_append, + List.nodup_cons] at hnd0 + exact hnd0.2.2 f (List.mem_filterMap.mpr ⟨y, h1, hlic⟩) f (List.mem_cons_self ..) rfl + · rcases List.mem_cons.mp h2 with rfl | h2' + · simp [newC, MGChain.headLic] at hylic; exact hne hylic.symm + · have hy_eq := smc_unique_chain hsmc (hms_eq ▸ List.mem_append_right _ (List.mem_cons_of_mem _ h2')) hylic hc_in hlic + subst hy_eq + have hnd0 := hsmc.2; rw [hms_eq] at hnd0 + simp only [List.filterMap_append, List.filterMap_cons, hlic, List.nodup_append, + List.nodup_cons] at hnd0 + exact hnd0.2.1.1 (List.mem_filterMap.mpr ⟨y, h2', hlic⟩) + by_cases hgf : g = f + · subst hgf + have hpre' : (pre ++ [c.str]) ++ strsOf t ms = sHead :: strsOf L ms := by + rw [strsOf_cons_some hfc] at hpre + simpa [List.append_assoc] using hpre + by_cases hgf' : g = f' + · subst hgf' + simp only [and_self, ↓reduceIte, Option.map_eq_some_iff] at hgo + obtain ⟨⟨os1, vs1⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hrec' : relocateSlot.go g g δ pSrc (pre ++ [c.str]).length t (slotsOf t ms) = some (os1, vs1) := by + simpa [List.length_append] using hrec + obtain ⟨hsl, hev⟩ := ih (pre ++ [c.str]) os1 vs1 hpre' hrec' + refine ⟨?_, ?_⟩ + · rw [slotsOf_cons, hfind_f']; simp [newC, δ, hsl] + · rw [strsOf_cons_some hfind_f'] + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [sHead :: strsOf L ms] [MCFGAtom.var 0 pSrc] = c.str := by + simp [MCFG.evalComp, hgetSrc] + rw [hhead] + exact congrArg (c.str :: ·) hev + · simp only [hgf', and_false, ↓reduceIte, Option.map_eq_some_iff] at hgo + obtain ⟨⟨os1, vs1⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hrec' : relocateSlot.go g f' δ pSrc (pre ++ [c.str]).length t (slotsOf t ms) = some (os1, vs1) := by + simpa [List.length_append] using hrec + obtain ⟨hsl, hev⟩ := ih (pre ++ [c.str]) os1 vs1 hpre' hrec' + have hfn := hfind_f_ne hgf' + refine ⟨?_, ?_⟩ + · rw [slotsOf_cons, hfn]; simp [hsl] + · rw [strsOf_cons_none hfn]; exact hev + · simp only [hgf, false_and, ↓reduceIte] at hgo + by_cases hgf' : g = f' + · subst hgf' + simp only [↓reduceIte] at hgo + cases hfg : findChain g ms with + | some _ => simp [hfg] at hgo + | none => + simp only [hfg, Option.map_none, Option.map_eq_some_iff] at hgo + obtain ⟨⟨os1, vs1⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hpre' : pre ++ strsOf t ms = sHead :: strsOf L ms := by + rw [strsOf_cons_none hfg] at hpre; exact hpre + obtain ⟨hsl, hev⟩ := ih pre os1 vs1 hpre' hrec + refine ⟨?_, ?_⟩ + · rw [slotsOf_cons, hfind_f']; simp [newC, δ, hsl] + · rw [strsOf_cons_some hfind_f'] + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [sHead :: strsOf L ms] [MCFGAtom.var 0 pSrc] = c.str := by + simp [MCFG.evalComp, hgetSrc] + rw [hhead] + exact congrArg (c.str :: ·) hev + · simp only [hgf', ↓reduceIte] at hgo + have hsame := hfind_other hgf hgf' + cases hfg : findChain g ms with + | none => + simp only [hfg, Option.map_none, Option.map_eq_some_iff] at hgo + obtain ⟨⟨os1, vs1⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hpre' : pre ++ strsOf t ms = sHead :: strsOf L ms := by + rw [strsOf_cons_none hfg] at hpre; exact hpre + obtain ⟨hsl, hev⟩ := ih pre os1 vs1 hpre' hrec + refine ⟨?_, ?_⟩ + · rw [slotsOf_cons, hsame, hfg]; simp [hsl] + · rw [strsOf_cons_none (hsame.trans hfg)]; exact hev + | some cg => + simp only [hfg, Option.map_some, Option.map_eq_some_iff] at hgo + obtain ⟨⟨os1, vs1⟩, hrec, heq⟩ := hgo + simp at heq; obtain ⟨rfl, rfl⟩ := heq + have hpre' : (pre ++ [cg.str]) ++ strsOf t ms = sHead :: strsOf L ms := by + rw [strsOf_cons_some hfg] at hpre + simpa [List.append_assoc] using hpre + have hrec' : relocateSlot.go f f' δ pSrc (pre ++ [cg.str]).length t (slotsOf t ms) = some (os1, vs1) := by + simpa [List.length_append] using hrec + obtain ⟨hsl, hev⟩ := ih (pre ++ [cg.str]) os1 vs1 hpre' hrec' + refine ⟨?_, ?_⟩ + · rw [slotsOf_cons, hsame, hfg]; simp [hsl] + · rw [strsOf_cons_some (hsame.trans hfg)] + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [sHead :: strsOf L ms] [MCFGAtom.var 0 pre.length] = cg.str := by + have hgetcg : (sHead :: strsOf L ms)[pre.length]? = some cg.str := by + rw [← hpre, strsOf_cons_some hfg]; simp + simp [MCFG.evalComp, hgetcg] + rw [hhead] + exact congrArg (cg.str :: ·) hev + +/-- Soundness & evaluation helper for `Move2` (`relocateSlot`). -/ +theorem relocateSlot_eval_and_mem [DecidableEq Base] [DecidableEq Lic] + {f f' : Lic} {δ' : List (MGFeature Base Lic)} + (L : List Lic) (_hLnd : L.Nodup) + {ms : List (MGChain Base Lic T)} (hsmc : SMC ms) + (_hLms : ∀ c, c ∈ ms → ∀ g, c.headLic = some g → g ∈ L) + {s' : List (Option (List (MGFeature Base Lic)))} {vs : List (List (MCFGAtom T))} + (sHead : List T) + (h : relocateSlot f f' (MGFeature.licensee f' :: δ') L (slotsOf L ms) = some (s', vs)) : + ∃ tStr ms1 ms2, + ms = ms1 ++ ⟨tStr, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2 ∧ + SMC (ms1 ++ ⟨tStr, MGFeature.licensee f' :: δ'⟩ :: ms2) ∧ + slotsOf L (ms1 ++ ⟨tStr, MGFeature.licensee f' :: δ'⟩ :: ms2) = s' ∧ + MCFG.evalYield [sHead :: strsOf L ms] vs = + strsOf L (ms1 ++ ⟨tStr, MGFeature.licensee f' :: δ'⟩ :: ms2) := by + let δ := MGFeature.licensee f' :: δ' + unfold relocateSlot at h + cases hloc : locateSlot f 1 L (slotsOf L ms) with + | none => simp [hloc] at h + | some pr => + obtain ⟨pSrc, fs⟩ := pr + simp only [hloc] at h + by_cases hfs : fs = MGFeature.licensee f :: MGFeature.licensee f' :: δ' + · simp only [hfs, ↓reduceIte] at h + by_cases hf'L : f' ∈ L + · simp only [hf'L, ↓reduceIte] at h + obtain ⟨c, hfc, hcf, hgetSrc⟩ := locateSlot_eval L hsmc [sHead] hloc + simp only [List.singleton_append] at hgetSrc + have hcf' : c.feats = MGFeature.licensee f :: MGFeature.licensee f' :: δ' := hcf.trans hfs + obtain ⟨hc_in, hlic⟩ := (findChain_eq_some_iff hsmc).mp hfc + obtain ⟨ms1, ms2, hms_eq⟩ := List.append_of_mem hc_in + have hce : c = ⟨c.str, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ := by + cases c; simp at hcf'; subst hcf'; rfl + have hms_eq' : ms = ms1 ++ ⟨c.str, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2 := by + rw [← hce]; exact hms_eq + let newC : MGChain Base Lic T := ⟨c.str, MGFeature.licensee f' :: δ'⟩ + let msNew := ms1 ++ newC :: ms2 + -- First check SMC msNew: if f' ≠ f, then slot f' in slotsOf L ms must be none! + have hsmc_rem : SMC (ms1 ++ ms2) := MG.smc_remove (hms_eq ▸ hsmc) + have hf'_free : f' ≠ f → findChain f' ms = none := by + intro hne + -- From relocateSlot.go succeeding with f' ∈ L and f' ≠ f, the slot at f' in slotsOf L ms is none + have hgo_none : ∀ (c0 : Nat) (L0 : List Lic) (os' : List (Option (List (MGFeature Base Lic)))) + (vs0 : List (List (MCFGAtom T))), + f' ∈ L0 → relocateSlot.go f f' δ pSrc c0 L0 (slotsOf L0 ms) = some (os', vs0) → + findChain f' ms = none := by + intro c0 L0 + induction L0 generalizing c0 with + | nil => intro _ _ hm; simp at hm + | cons g t ih => + intro os' vs0 hm hgo + rw [slotsOf_cons] at hgo + simp only [relocateSlot.go] at hgo + rcases List.mem_cons.mp hm with rfl | ht + · simp only [hne, false_and, ↓reduceIte] at hgo + cases hff : findChain f' ms with + | none => rfl + | some _ => simp [hff] at hgo + · by_cases hgf : g = f + · subst hgf + by_cases hgf' : g = f' + · exact absurd hgf'.symm hne + · simp only [hgf', and_false, ↓reduceIte, Option.map_eq_some_iff] at hgo + obtain ⟨⟨_, _⟩, hrec, _⟩ := hgo + exact ih (c0 + 1) _ _ ht hrec + · by_cases hgf' : g = f' + · subst hgf' + simp only [hgf, false_and, ↓reduceIte] at hgo + cases hff : findChain g ms with + | none => rfl + | some _ => simp [hff] at hgo + · simp only [hgf, false_and, hgf', ↓reduceIte] at hgo + cases hfg : findChain g ms with + | none => + simp only [hfg, Option.map_none, Option.map_eq_some_iff] at hgo + obtain ⟨⟨_, _⟩, hrec, _⟩ := hgo + exact ih c0 _ _ ht hrec + | some _ => + simp only [hfg, Option.map_some, Option.map_eq_some_iff] at hgo + obtain ⟨⟨_, _⟩, hrec, _⟩ := hgo + exact ih (c0 + 1) _ _ ht hrec + exact hgo_none 1 L s' vs hf'L h + have hsmcNew : SMC msNew := by + refine ⟨?_, ?_⟩ + · intro x hx + rcases List.mem_append.mp hx with h1 | h2 + · exact hsmc_rem.1 x (List.mem_append_left _ h1) + · rcases List.mem_cons.mp h2 with rfl | h2' + · exact ⟨f', δ', rfl⟩ + · exact hsmc_rem.1 x (List.mem_append_right _ h2') + · have hnd := hsmc_rem.2 + simp only [msNew, List.filterMap_append, List.filterMap_cons] + change ((ms1.filterMap MGChain.headLic) ++ f' :: (ms2.filterMap MGChain.headLic)).Nodup + rw [List.filterMap_append, List.nodup_append] at hnd + rw [List.nodup_append, List.nodup_cons] + have hf'_not_rem : ∀ x, x ∈ ms1 ++ ms2 → x.headLic ≠ some f' := by + intro x hx hxlic + by_cases hff' : f' = f + · subst hff' + have hx_in : x ∈ ms := by + rw [hms_eq] + rcases List.mem_append.mp hx with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2) + have hxeq := smc_unique_chain hsmc hx_in hxlic hc_in hlic + subst hxeq + have hnd0 := hsmc.2 + rw [hms_eq] at hnd0 + simp only [List.filterMap_append, List.filterMap_cons, hlic, List.nodup_append, + List.nodup_cons] at hnd0 + rcases List.mem_append.mp hx with h1 | h2 + · exact hnd0.2.2 f' (List.mem_filterMap.mpr ⟨x, h1, hlic⟩) f' (List.mem_cons_self ..) rfl + · exact hnd0.2.1.1 (List.mem_filterMap.mpr ⟨x, h2, hlic⟩) + · have hnone := hf'_free hff' + have hx_in : x ∈ ms := by + rw [hms_eq] + rcases List.mem_append.mp hx with h1 | h2 + · exact List.mem_append_left _ h1 + · exact List.mem_append_right _ (List.mem_cons_of_mem _ h2) + exact (findChain_eq_none_iff.mp hnone) x hx_in hxlic + refine ⟨hnd.1, ⟨?_, hnd.2.1⟩, ?_⟩ + · intro hmem2 + obtain ⟨x, hx2, hxlic⟩ := List.mem_filterMap.mp hmem2 + exact hf'_not_rem x (List.mem_append_right _ hx2) hxlic + · intro a ha b hb + rcases List.mem_cons.mp hb with rfl | hb2 + · intro heq; subst heq + obtain ⟨x, hx1, hxlic⟩ := List.mem_filterMap.mp ha + exact hf'_not_rem x (List.mem_append_left _ hx1) hxlic + · exact hnd.2.2 a ha b hb2 + -- Now prove slotsOf and evalYield match by induction on L0 with running prefix `pre`! + obtain ⟨hsl, hev⟩ := relocateSlot_go_eval (f' := f') (δ' := δ') L hsmc + sHead pSrc c hfc hgetSrc hc_in hlic ms1 ms2 hms_eq hsmcNew L [sHead] s' vs rfl h + exact ⟨c.str, ms1, ms2, hms_eq', hsmcNew, hsl, hev⟩ + · simp [hf'L] at h + · simp [hfs] at h + +/-- Completeness helper for `Move2`: if `ms = ms1 ++ ⟨tStr, licensee f :: licensee f' :: δ'⟩ :: ms2` + and `SMC (ms1 ++ ⟨tStr, licensee f' :: δ'⟩ :: ms2)` and `f, f' ∈ L`, then `relocateSlot` succeeds. -/ +theorem relocateSlot_complete [DecidableEq Base] [DecidableEq Lic] + {f f' : Lic} {δ' : List (MGFeature Base Lic)} {tStr : List T} + (L : List Lic) (hfL : f ∈ L) (hf'L : f' ∈ L) + {ms1 ms2 : List (MGChain Base Lic T)} + (hsmc : SMC (ms1 ++ ⟨tStr, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2)) + (hsmcNew : SMC (ms1 ++ ⟨tStr, MGFeature.licensee f' :: δ'⟩ :: ms2)) : + ∃ s' vs, + relocateSlot (T := T) f f' (MGFeature.licensee f' :: δ') L + (slotsOf L (ms1 ++ ⟨tStr, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2)) = + some (s', vs) := by + let oldC : MGChain Base Lic T := ⟨tStr, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ + let newC : MGChain Base Lic T := ⟨tStr, MGFeature.licensee f' :: δ'⟩ + let ms := ms1 ++ oldC :: ms2 + let msNew := ms1 ++ newC :: ms2 + have hfc : findChain f ms = some oldC := + (findChain_eq_some_iff hsmc).mpr ⟨List.mem_append_right _ (List.mem_cons_self ..), rfl⟩ + -- locateSlot succeeds because f ∈ L and findChain f ms = some oldC + have hloc_ex : ∀ (L0 : List Lic) (c0 : Nat), f ∈ L0 → + ∃ p, locateSlot f c0 L0 (slotsOf L0 ms) = some (p, oldC.feats) := by + intro L0 + induction L0 with + | nil => intro _ hm; simp at hm + | cons g t ih => + intro c0 hm + simp only [slotsOf, List.map_cons, locateSlot] + by_cases hgf : g = f + · subst hgf; simp [hfc] + · simp only [hgf, ↓reduceIte] + have hft : f ∈ t := by + rcases List.mem_cons.mp hm with rfl | ht + · exact absurd rfl hgf + · exact ht + cases findChain g ms with + | none => exact ih c0 hft + | some _ => exact ih (c0 + 1) hft + obtain ⟨pSrc, hloc⟩ := hloc_ex L 1 hfL + -- If f' ≠ f, then findChain f' ms = none (otherwise SMC msNew would fail!) + have hf'_none : f' ≠ f → findChain f' ms = none := by + intro hne + rw [findChain_eq_none_iff] + intro x hx hxlic + rcases List.mem_append.mp hx with h1 | h2 + · have hnd := hsmcNew.2 + simp only [List.filterMap_append, List.filterMap_cons, List.nodup_append] at hnd + have hm1 : f' ∈ ms1.filterMap MGChain.headLic := List.mem_filterMap.mpr ⟨x, h1, hxlic⟩ + exact hnd.2.2 f' hm1 f' (List.mem_cons_self ..) rfl + · rcases List.mem_cons.mp h2 with rfl | h2' + · simp [oldC, MGChain.headLic] at hxlic; exact hne hxlic.symm + · have hnd := hsmcNew.2 + simp only [List.filterMap_append, List.filterMap_cons, MGChain.headLic, + List.nodup_append, List.nodup_cons] at hnd + have hm2 : f' ∈ ms2.filterMap MGChain.headLic := List.mem_filterMap.mpr ⟨x, h2', hxlic⟩ + exact hnd.2.1.1 hm2 + have hgo_ex : ∀ (L0 : List Lic) (c0 : Nat), + ∃ os' vs0, relocateSlot.go (T := T) f f' (MGFeature.licensee f' :: δ') pSrc c0 L0 (slotsOf L0 ms) = some (os', vs0) := by + intro L0 + induction L0 with + | nil => intro c0; exact ⟨[], [], rfl⟩ + | cons g t ih => + intro c0 + rw [slotsOf_cons] + simp only [relocateSlot.go] + by_cases hgf : g = f + · subst hgf + by_cases hgf' : g = f' + · subst hgf' + obtain ⟨os', vs0, hrec⟩ := ih (c0 + 1) + exact ⟨some (MGFeature.licensee g :: δ') :: os', [MCFGAtom.var 0 pSrc] :: vs0, by simp [hrec]⟩ + · obtain ⟨os', vs0, hrec⟩ := ih (c0 + 1) + exact ⟨none :: os', vs0, by simp [hgf', hrec]⟩ + · by_cases hgf' : g = f' + · subst hgf' + have hfn : findChain g ms = none := hf'_none hgf + obtain ⟨os', vs0, hrec⟩ := ih c0 + exact ⟨some (MGFeature.licensee g :: δ') :: os', [MCFGAtom.var 0 pSrc] :: vs0, by simp [hgf, hfn, hrec]⟩ + · cases hfg : findChain g ms with + | none => + obtain ⟨os', vs0, hrec⟩ := ih c0 + exact ⟨none :: os', vs0, by simp [hgf, hgf', hrec]⟩ + | some ch => + obtain ⟨os', vs0, hrec⟩ := ih (c0 + 1) + exact ⟨some ch.feats :: os', [MCFGAtom.var 0 c0] :: vs0, by simp [hgf, hgf', hrec]⟩ + obtain ⟨s', vs, hgo⟩ := hgo_ex L 1 + refine ⟨s', vs, ?_⟩ + change relocateSlot (T := T) f f' (MGFeature.licensee f' :: δ') L (slotsOf L ms) = some (s', vs) + unfold relocateSlot + simp only [hloc, oldC, ↓reduceIte, hf'L] + exact hgo + +/-! ### Part 5: Finite Enumeration of All Valid MG Profiles & MCFG Rules -/ + +/-- Cartesian product of finite lists of slot choices along `L`. -/ +def allSlotVectors [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + List Lic → List (List (Option (List (MGFeature Base Lic)))) + | [] => [[]] + | f :: t => + let tailVecs := allSlotVectors G t + let headChoices : List (Option (List (MGFeature Base Lic))) := + none :: (licFeats G f).map some + headChoices.flatMap fun o => tailVecs.map fun rest => o :: rest + +theorem mem_allSlotVectors_of_movers [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {ms : List (MGChain Base Lic T)} (hsmc : SMC ms) + (hsuf : ∀ c, c ∈ ms → ∃ entry, entry ∈ G.lexicon ∧ MG.isSuffix c.feats entry.2) : + ∀ L, slotsOf L ms ∈ allSlotVectors G L := by + intro L + induction L with + | nil => simp [slotsOf, allSlotVectors] + | cons f t ih => + simp only [slotsOf, List.map_cons, allSlotVectors, List.mem_flatMap, List.mem_map] + cases hfg : findChain f ms with + | none => + exact ⟨none, List.mem_cons_self .., slotsOf t ms, ih, rfl⟩ + | some c => + obtain ⟨hc_in, hlic⟩ := (findChain_eq_some_iff hsmc).mp hfg + obtain ⟨entry, hentry, hs⟩ := hsuf c hc_in + obtain ⟨f', δ, hcf⟩ := hsmc.1 c hc_in + have hfeq : f' = f := by simp [MGChain.headLic, hcf] at hlic; exact hlic + subst f' + have hmem_lf : c.feats ∈ licFeats G f := + mem_licFeats_iff.mpr ⟨mem_allFeats_of_suffix hentry hs, δ, hcf⟩ + refine ⟨some c.feats, List.mem_cons_of_mem _ (List.mem_map.mpr ⟨c.feats, hmem_lf, rfl⟩), + slotsOf t ms, ih, rfl⟩ + +/-- Finite list of all reachable MG profiles `(isLex, headFeats, slots)`. -/ +def allProfiles [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + List (Bool × List (MGFeature Base Lic) × List (Option (List (MGFeature Base Lic)))) := + [true, false].flatMap fun b => + (allFeats G).flatMap fun α => + (allSlotVectors G (allLics G)).map fun slots => (b, α, slots) + +theorem mem_allProfiles_of_derives [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {e : MGExpr Base Lic T} (h : MG.Derives G e) : + (e.isLex, e.head.feats, slotsOf (allLics G) e.movers) ∈ allProfiles G := by + obtain ⟨⟨e1, he1, hs1⟩, hm⟩ := h.feats_suffix + have hsmc := h.smc + simp only [allProfiles, List.mem_flatMap, List.mem_map] + refine ⟨e.isLex, by cases e.isLex <;> simp, e.head.feats, + mem_allFeats_of_suffix he1 hs1, + slotsOf (allLics G) e.movers, mem_allSlotVectors_of_movers hsmc hm (allLics G), rfl⟩ + +/-- Simulating rules for merging a lexical selector with an already completed argument. -/ +abbrev merge1Rules [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) + (profiles : List (Bool × List (MGFeature Base Lic) × + List (Option (List (MGFeature Base Lic))))) : + List (MCFGRule (MGMCFGNT Base Lic) T) := + profiles.flatMap fun (b1, α1, s1) => + if b1 = true ∧ s1 = ((allLics G).map fun _ => none) then + match α1 with + | MGFeature.sel x :: γ => + profiles.filterMap fun (b2, α2, s2) => + if α2 = [MGFeature.cat x] then + let tailVars := (List.range (s2.countP Option.isSome)).map fun k => + [MCFGAtom.var 1 (1 + k)] + some { + lhs := MGMCFGNT.prof false γ s2 + rhs := [MGMCFGNT.prof true (MGFeature.sel x :: γ) ((allLics G).map fun _ => none), + MGMCFGNT.prof b2 [MGFeature.cat x] s2] + yield := [MCFGAtom.var 0 0, MCFGAtom.var 1 0] :: tailVars + } + else none + | _ => [] + else [] + +/-- Simulating rules for merging a derived selector with an already completed argument. -/ +abbrev merge2Rules [DecidableEq Base] [DecidableEq Lic] + (profiles : List (Bool × List (MGFeature Base Lic) × + List (Option (List (MGFeature Base Lic))))) : + List (MCFGRule (MGMCFGNT Base Lic) T) := + profiles.flatMap fun (b1, α1, s1) => + if b1 = false then + match α1 with + | MGFeature.sel x :: γ => + profiles.filterMap fun (b2, α2, s2) => + if α2 = [MGFeature.cat x] then + match mergeSlots s1 s2 with + | some s12 => + some { + lhs := MGMCFGNT.prof false γ s12 + rhs := [MGMCFGNT.prof false (MGFeature.sel x :: γ) s1, + MGMCFGNT.prof b2 [MGFeature.cat x] s2] + yield := [MCFGAtom.var 1 0, MCFGAtom.var 0 0] :: mergeVars 1 1 s1 s2 + } + | none => none + else none + | _ => [] + else [] + +/-- Simulating rules for merging a selector whose argument must move later. -/ +abbrev merge3Rules [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) + (profiles : List (Bool × List (MGFeature Base Lic) × + List (Option (List (MGFeature Base Lic))))) : + List (MCFGRule (MGMCFGNT Base Lic) T) := + let L := allLics G + profiles.flatMap fun (b1, α1, s1) => + match α1 with + | MGFeature.sel x :: γ => + profiles.filterMap fun (b2, α2, s2) => + match α2 with + | MGFeature.cat x' :: MGFeature.licensee f :: δ' => + if x' = x then + match mergeSlots s1 s2 with + | some s12 => + match insertSlot f (MGFeature.licensee f :: δ') L s12 with + | some s3 => + some { + lhs := MGMCFGNT.prof false γ s3 + rhs := [MGMCFGNT.prof b1 (MGFeature.sel x :: γ) s1, + MGMCFGNT.prof b2 (MGFeature.cat x :: MGFeature.licensee f :: δ') s2] + yield := [MCFGAtom.var 0 0] :: merge3Vars f 1 1 L s1 s2 + } + | none => none + | none => none + else none + | _ => none + | _ => [] + +/-- Build the finite list of MCFG rules simulating `G`. -/ +def buildRules [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + List (MCFGRule (MGMCFGNT Base Lic) T) := + let L := allLics G + let emptySlots : List (Option (List (MGFeature Base Lic))) := L.map fun _ => none + let profs := allProfiles G + -- 0. Start rules (accepting lexical or derived `[cat G.start]` with empty movers) + let startRules : List (MCFGRule (MGMCFGNT Base Lic) T) := + [true, false].map fun b => + { lhs := MGMCFGNT.start + rhs := [MGMCFGNT.prof b [MGFeature.cat G.start] emptySlots] + yield := [[MCFGAtom.var 0 0]] } + -- 1. Lexicon rules + let lexRules : List (MCFGRule (MGMCFGNT Base Lic) T) := + G.lexicon.map fun (w, α) => + { lhs := MGMCFGNT.prof true α emptySlots + rhs := [] + yield := [w.map MCFGAtom.tm] } + -- 5. Move 1 rules + let move1Rules : List (MCFGRule (MGMCFGNT Base Lic) T) := + profs.filterMap fun (b, α, s) => + if b = false then + match α with + | MGFeature.licensor f :: γ => + match clearSlot (T := T) f 1 L s with + | some (p, s', vs) => + some { + lhs := MGMCFGNT.prof false γ s' + rhs := [MGMCFGNT.prof false (MGFeature.licensor f :: γ) s] + yield := [MCFGAtom.var 0 p, MCFGAtom.var 0 0] :: vs + } + | none => none + | _ => none + else none + -- 6. Move 2 rules + let move2Rules : List (MCFGRule (MGMCFGNT Base Lic) T) := + profs.flatMap fun (b, α, s) => + if b = false then + match α with + | MGFeature.licensor f :: γ => + L.flatMap fun f' => + (licFeats G f').filterMap fun δ => + match relocateSlot (T := T) f f' δ L s with + | some (s', vs) => + some { + lhs := MGMCFGNT.prof false γ s' + rhs := [MGMCFGNT.prof false (MGFeature.licensor f :: γ) s] + yield := [MCFGAtom.var 0 0] :: vs + } + | none => none + | _ => [] + else [] + startRules ++ lexRules ++ merge1Rules G profs ++ merge2Rules profs ++ merge3Rules G profs ++ + move1Rules ++ move2Rules + +/-! ### Part 6: Proof That Every Built Rule Is Linear & Non-Erasing (`WellFormed`) -/ + +theorem countP_map_none {α β : Type} (L : List α) : + (L.map fun _ => (none : Option β)).countP Option.isSome = 0 := by + induction L with + | nil => rfl + | cons _ _ ih => simp [ih] + +theorem ntDim_none {Base Lic : Type} (b : Bool) (α : List (MGFeature Base Lic)) (L : List Lic) : + ntDim (MGMCFGNT.prof b α (L.map fun _ => none)) = 1 := by + simp only [ntDim, countP_map_none] + +theorem evalComp_map_tm (args : List (List (List T))) (w : List T) : + MCFG.evalComp args (w.map MCFGAtom.tm) = w := by + induction w with + | nil => rfl + | cons a t ih => simp [MCFG.evalComp, ih] + +theorem varOccurrences_cons_comp {N : Type} (lhs : N) (rhs : List N) + (c0 : List (MCFGAtom T)) (cs : List (List (MCFGAtom T))) : + MCFGRule.varOccurrences { lhs := lhs, rhs := rhs, yield := c0 :: cs } = + (c0.filterMap fun | MCFGAtom.tm _ => none | MCFGAtom.var i j => some (i, j)) ++ + compsVars cs := rfl + +theorem range_vars1_props (base len : Nat) : + let vs : List (List (MCFGAtom T)) := (List.range len).map fun k => [MCFGAtom.var 1 (base + k)] + vs.length = len ∧ + (compsVars vs).Nodup ∧ + (∀ i j, (i, j) ∈ compsVars vs ↔ i = 1 ∧ base ≤ j ∧ j < base + len) := by + induction len generalizing base with + | zero => + refine ⟨rfl, List.nodup_nil, ?_⟩ + intro i j; simp [compsVars] + | succ len ih => + have hr : List.range (len + 1) = 0 :: (List.range len).map Nat.succ := + List.range_succ_eq_map (n := len) + obtain ⟨hlen, hnd, hmem⟩ := ih (base + 1) + have hmap : ((List.range (len + 1)).map fun k => [MCFGAtom.var (T := T) 1 (base + k)]) = + [MCFGAtom.var 1 base] :: ((List.range len).map fun k => [MCFGAtom.var 1 (base + 1 + k)]) := by + rw [hr, List.map_cons, List.map_map] + simp only [Nat.add_zero] + congr 1 + apply List.map_congr_left + intro k _ + have hidx : base + k.succ = base + 1 + k := by omega + simp [Function.comp, hidx] + simp only [hmap] + refine ⟨by simp [hlen], ?_, ?_⟩ + · rw [compsVars_cons_var, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hbad; have := (hmem 1 base).mp hbad; omega + · intro i j + rw [compsVars_cons_var, List.mem_cons, Prod.mk.injEq, hmem i j] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi⟩) <;> refine ⟨rfl, ?_, ?_⟩ <;> omega + · rintro ⟨rfl, hlo, hhi⟩ + by_cases hj : j = base + · left; exact ⟨rfl, hj⟩ + · right; refine ⟨rfl, ?_, ?_⟩ <;> omega + +private theorem merge1Rules_wellFormed [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {r : MCFGRule (MGMCFGNT Base Lic) T} + (hM1 : r ∈ merge1Rules G (allProfiles G)) : r.WellFormed ntDim := by + simp only [merge1Rules, List.mem_flatMap] at hM1 + obtain ⟨⟨b1, α1, s1⟩, _, h1⟩ := hM1 + dsimp only at h1 + split at h1 + · next hcond => + cases α1 with + | nil => simp at h1 + | cons hd γ => + cases hd with + | sel x => + simp only [List.mem_filterMap] at h1 + obtain ⟨⟨b2, α2, s2⟩, _, h2⟩ := h1 + dsimp only at h2 + split at h2 + · simp at h2; subst h2 + obtain ⟨hlen, hnd, hmem⟩ := range_vars1_props (T := T) 1 (s2.countP Option.isSome) + refine ⟨by simp [ntDim, hlen]; omega, ?_, ?_⟩ + · unfold MCFGRule.isLinear + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.nodup_cons] + refine ⟨?_, ?_, hnd⟩ + · intro hm; rcases List.mem_cons.mp hm with heq | hm' + · simp at heq + · have := (hmem 0 0).mp hm'; omega + · intro hm'; have := (hmem 1 0).mp hm'; omega + · intro i j + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.mem_cons, Prod.mk.injEq] + rw [hmem i j] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi⟩) + · exact ⟨_, rfl, by simp [ntDim_none]⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => + simp at hget; subst hget + rw [ntDim_none] at hj + left; exact ⟨rfl, by omega⟩ + | succ i' => + cases i' with + | zero => + simp at hget; subst hget + simp [ntDim] at hj + by_cases hj0 : j = 0 + · right; left; exact ⟨rfl, hj0⟩ + · right; right; refine ⟨rfl, ?_, ?_⟩ <;> omega + | succ _ => simp at hget + · simp at h2 + | _ => simp at h1 + · simp at h1 + +private theorem merge2Rules_wellFormed [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {r : MCFGRule (MGMCFGNT Base Lic) T} + (hM2 : r ∈ merge2Rules (allProfiles G)) : r.WellFormed ntDim := by + simp only [merge2Rules, List.mem_flatMap] at hM2 + obtain ⟨⟨b1, α1, s1⟩, _, h1⟩ := hM2 + dsimp only at h1 + split at h1 + · cases α1 with + | nil => simp at h1 + | cons hd γ => + cases hd with + | sel x => + simp only [List.mem_filterMap] at h1 + obtain ⟨⟨b2, α2, s2⟩, _, h2⟩ := h1 + dsimp only at h2 + split at h2 + · cases hm : mergeSlots s1 s2 with + | none => simp [hm] at h2 + | some s12 => + simp [hm] at h2; subst h2 + obtain ⟨hlen, hnd, hmem⟩ := mergeVars_props (T := T) hm 1 1 + refine ⟨by simp [ntDim, hlen]; omega, ?_, ?_⟩ + · unfold MCFGRule.isLinear + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.nodup_cons] + refine ⟨?_, ?_, hnd⟩ + · intro hm'; rcases List.mem_cons.mp hm' with heq | hmv + · simp at heq + · have := (hmem 1 0).mp hmv; omega + · intro hmv; have := (hmem 0 0).mp hmv; omega + · intro i j + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.mem_cons, Prod.mk.injEq] + rw [hmem i j] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi⟩ | ⟨rfl, hlo, hhi⟩) + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => + simp at hget; subst hget; simp [ntDim] at hj + by_cases hj0 : j = 0 + · right; left; exact ⟨rfl, hj0⟩ + · right; right; left; refine ⟨rfl, ?_, ?_⟩ <;> omega + | succ i' => + cases i' with + | zero => + simp at hget; subst hget; simp [ntDim] at hj + by_cases hj0 : j = 0 + · left; exact ⟨rfl, hj0⟩ + · right; right; right; refine ⟨rfl, ?_, ?_⟩ <;> omega + | succ _ => simp at hget + · simp at h2 + | _ => simp at h1 + · simp at h1 + +private theorem merge3Rules_wellFormed [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {r : MCFGRule (MGMCFGNT Base Lic) T} + (hM3 : r ∈ merge3Rules G (allProfiles G)) : r.WellFormed ntDim := by + simp only [merge3Rules, List.mem_flatMap] at hM3 + obtain ⟨⟨b1, α1, s1⟩, _, h1⟩ := hM3 + dsimp only at h1 + cases α1 with + | nil => simp at h1 + | cons hd γ => + cases hd with + | sel x => + simp only [List.mem_filterMap] at h1 + obtain ⟨⟨b2, α2, s2⟩, _, h2⟩ := h1 + dsimp only at h2 + cases α2 with + | nil => simp at h2 + | cons hd2 tl2 => + cases hd2 with + | cat x' => + cases tl2 with + | nil => simp at h2 + | cons hd3 δ' => + cases hd3 with + | licensee f => + dsimp only at h2 + split at h2 + · next hx => + subst hx + cases hm : mergeSlots s1 s2 with + | none => simp [hm] at h2 + | some s12 => + rw [hm] at h2 + cases hi : insertSlot f (MGFeature.licensee f :: δ') (allLics G) s12 with + | none => simp [hi] at h2 + | some s3 => + simp [hi] at h2; subst h2 + obtain ⟨hlen, hnd, hmem⟩ := merge3Vars_props (T := T) hm hi 1 1 (Nat.le_refl 1) + refine ⟨by simp [ntDim, hlen]; omega, ?_, ?_⟩ + · unfold MCFGRule.isLinear + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, + List.nil_append, List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hmv; have := (hmem 0 0).mp hmv; omega + · intro i j + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, + List.nil_append, List.mem_cons, Prod.mk.injEq] + rw [hmem i j] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi⟩ | ⟨rfl, hlo, hhi⟩) + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => + simp at hget; subst hget; simp [ntDim] at hj + by_cases hj0 : j = 0 + · left; exact ⟨rfl, hj0⟩ + · right; right; left; refine ⟨rfl, ?_, ?_⟩ <;> omega + | succ i' => + cases i' with + | zero => + simp at hget; subst hget; simp [ntDim] at hj + by_cases hj0 : j = 0 + · right; left; exact ⟨rfl, hj0⟩ + · right; right; right; refine ⟨rfl, ?_, ?_⟩ <;> omega + | succ _ => simp at hget + · simp at h2 + | _ => simp at h2 + | _ => simp at h2 + | _ => simp at h1 + +theorem buildRules_wf [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + ∀ r, r ∈ buildRules G → r.WellFormed ntDim := by + intro r hr + unfold buildRules at hr + simp only [List.mem_append] at hr + rcases hr with (((((hStart | hLex) | hM1) | hM2) | hM3) | hV1) | hV2 + · -- Start rules + simp only [List.mem_map] at hStart + obtain ⟨b, _, rfl⟩ := hStart + refine ⟨rfl, ?_, ?_⟩ + · simp [MCFGRule.isLinear, MCFGRule.varOccurrences] + · intro i j + simp only [MCFGRule.varOccurrences, List.flatMap_cons, List.flatMap_nil, + List.filterMap_cons, List.filterMap_nil, List.append_nil, List.mem_singleton, Prod.mk.injEq] + constructor + · rintro ⟨rfl, rfl⟩ + exact ⟨_, rfl, by simp [ntDim_none]⟩ + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => + simp at hget; subst hget + rw [ntDim_none] at hj + exact ⟨rfl, by omega⟩ + | succ _ => simp at hget + · -- Lex rules + simp only [List.mem_map] at hLex + obtain ⟨⟨w, α⟩, _, rfl⟩ := hLex + have hvars : MCFGRule.varOccurrences + ({ lhs := MGMCFGNT.prof true α ((allLics G).map fun _ => none), + rhs := [], yield := [w.map MCFGAtom.tm] } : MCFGRule (MGMCFGNT Base Lic) T) = [] := by + simp only [MCFGRule.varOccurrences, List.flatMap_cons, List.flatMap_nil, List.append_nil] + induction w with + | nil => rfl + | cons a t _ => simp + refine ⟨by simp [ntDim_none], ?_, ?_⟩ + · simp [MCFGRule.isLinear, hvars] + · intro i j + simp [hvars] + · -- Merge 1 rules + exact merge1Rules_wellFormed hM1 + · -- Merge 2 rules + exact merge2Rules_wellFormed hM2 + · -- Merge 3 rules + exact merge3Rules_wellFormed hM3 + · -- Move 1 rules + simp only [List.mem_filterMap] at hV1 + obtain ⟨⟨b, α, s⟩, _, h1⟩ := hV1 + dsimp only at h1 + split at h1 + · cases α with + | nil => simp at h1 + | cons hd γ => + cases hd with + | licensor f => + cases hcl : clearSlot (T := T) f 1 (allLics G) s with + | none => simp [hcl] at h1 + | some triple => + obtain ⟨p, s', vs⟩ := triple + simp [hcl] at h1; subst h1 + obtain ⟨hge, hlt, hlen, hnd, hmem⟩ := clearSlot_props (T := T) hcl + refine ⟨by simp [ntDim, hlen]; omega, ?_, ?_⟩ + · unfold MCFGRule.isLinear + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.nodup_cons] + refine ⟨?_, ?_, hnd⟩ + · intro hm; rcases List.mem_cons.mp hm with heq | hmv + · simp at heq; omega + · have := (hmem 0 p).mp hmv; omega + · intro hmv; have := (hmem 0 0).mp hmv; omega + · intro i j + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.mem_cons, Prod.mk.injEq] + rw [hmem i j] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi, _⟩) + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => + simp at hget; subst hget; simp [ntDim] at hj + by_cases hj0 : j = 0 + · right; left; exact ⟨rfl, hj0⟩ + · by_cases hjp : j = p + · left; exact ⟨rfl, hjp⟩ + · right; right; refine ⟨rfl, ?_, ?_, hjp⟩ <;> omega + | succ _ => simp at hget + | _ => simp at h1 + · simp at h1 + · -- Move 2 rules + simp only [List.mem_flatMap] at hV2 + obtain ⟨⟨b, α, s⟩, _, h1⟩ := hV2 + dsimp only at h1 + split at h1 + · cases α with + | nil => simp at h1 + | cons hd γ => + cases hd with + | licensor f => + simp only [List.mem_flatMap, List.mem_filterMap] at h1 + obtain ⟨f', _, δ, _, h2⟩ := h1 + cases hrel : relocateSlot (T := T) f f' δ (allLics G) s with + | none => simp [hrel] at h2 + | some pr => + obtain ⟨s', vs⟩ := pr + simp [hrel] at h2; subst h2 + obtain ⟨hlen, hnd, hmem⟩ := relocateSlot_props (T := T) (nodup_allLics G) hrel + refine ⟨by simp [ntDim, hlen]; omega, ?_, ?_⟩ + · unfold MCFGRule.isLinear + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.nodup_cons] + refine ⟨?_, hnd⟩ + intro hmv; have := (hmem 0 0).mp hmv; omega + · intro i j + rw [varOccurrences_cons_comp] + simp only [List.filterMap_cons, List.filterMap_nil, List.cons_append, List.nil_append, + List.mem_cons, Prod.mk.injEq] + rw [hmem i j] + constructor + · rintro (⟨rfl, rfl⟩ | ⟨rfl, hlo, hhi⟩) + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · exact ⟨_, rfl, by simp [ntDim]; omega⟩ + · rintro ⟨B, hget, hj⟩ + cases i with + | zero => + simp at hget; subst hget; simp [ntDim] at hj + by_cases hj0 : j = 0 + · left; exact ⟨rfl, hj0⟩ + · right; refine ⟨rfl, ?_, ?_⟩ <;> omega + | succ _ => simp at hget + | _ => simp at h1 + · simp at h1 + +/-- The Linear Non-Erasing MCFG (LCFRS) equivalent to Minimalist Grammar `G`. -/ +def mgToMCFG [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + MCFG (MGMCFGNT Base Lic) T where + start := MGMCFGNT.start + dim := ntDim + dim_pos := ntDim_pos + dim_start := rfl + rules := buildRules G + rules_wf := buildRules_wf G + +/-! ### Part 7: Soundness & Completeness (`MG.Lang ↔ MCFG.Lang`) -/ + +/-- Semantic interpretation of an `MGMCFGNT` tuple back in `MG.Derives G`. -/ +def ntInterp [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + MGMCFGNT Base Lic → List (List T) → Prop + | MGMCFGNT.start, tup => ∃ w, tup = [w] ∧ G.Lang w + | MGMCFGNT.prof b α slots, tup => + ∃ s ms, tup = s :: strsOf (allLics G) ms ∧ + slotsOf (allLics G) ms = slots ∧ + MG.Derives G ⟨b, ⟨s, α⟩, ms⟩ + +/-- Helper list-level predicate for mutual structural recursion on `MCFG.Yield` / `MCFG.YieldList`. -/ +inductive InterpList [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) : + List (MGMCFGNT Base Lic) → List (List (List T)) → Prop where + | nil : InterpList G [] [] + | cons {A : MGMCFGNT Base Lic} {As : List (MGMCFGNT Base Lic)} + {tup : List (List T)} {tups : List (List (List T))} : + ntInterp G A tup → InterpList G As tups → InterpList G (A :: As) (tup :: tups) + +theorem movers_in_allLics [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {e : MGExpr Base Lic T} (h : MG.Derives G e) : + ∀ c, c ∈ e.movers → ∀ f, c.headLic = some f → f ∈ allLics G := by + intro c hc f hlic + obtain ⟨entry, hentry, hsuf⟩ := h.feats_suffix.2 c hc + cases hcf : c.feats with + | nil => simp [MGChain.headLic, hcf] at hlic + | cons hd tl => + cases hd with + | licensee f' => + simp [MGChain.headLic, hcf] at hlic; subst hlic + rw [hcf] at hsuf + exact mem_allLics_of_suffix hentry hsuf + | _ => simp [MGChain.headLic, hcf] at hlic + +private theorem merge1Rules_sound [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {r : MCFGRule (MGMCFGNT Base Lic) T} + {args : List (List (List T))} (hM1 : r ∈ merge1Rules G (allProfiles G)) + (hargs : InterpList G r.rhs args) : ntInterp G r.lhs (MCFG.evalYield args r.yield) := by + simp only [merge1Rules, List.mem_flatMap] at hM1 + obtain ⟨⟨b1, α1, s1⟩, _, h1⟩ := hM1 + dsimp only at h1 + split at h1 + · cases α1 with + | nil => simp at h1 + | cons hd γ => + cases hd with + | sel x => + simp only [List.mem_filterMap] at h1 + obtain ⟨⟨b2, α2, s2⟩, _, h2⟩ := h1 + dsimp only at h2 + split at h2 + · simp at h2; subst h2 + cases hargs with + | cons hi1 hrest => + cases hrest with + | cons hi2 hnil => + cases hnil + obtain ⟨s, ms1, rfl, hslots1, hder1⟩ := hi1 + obtain ⟨t, ms2, rfl, hslots2, hder2⟩ := hi2 + have hms1 : ms1 = [] := + movers_nil_of_slotsOf_all_none hder1.smc (movers_in_allLics hder1) hslots1 + subst hms1 + refine ⟨s ++ t, ms2, ?_, hslots2, MG.Derives.merge1 hder1 hder2⟩ + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) ([] : List (MGChain Base Lic T)), t :: strsOf (allLics G) ms2] + [MCFGAtom.var 0 0, MCFGAtom.var 1 0] = s ++ t := by + simp [MCFG.evalComp] + rw [hhead] + congr 1 + rw [← hslots2, ← strsOf_length (allLics G) ms2] + exact evalYield_range_vars1 (s :: strsOf (allLics G) ([] : List (MGChain Base Lic T))) + [t] (strsOf (allLics G) ms2) + · simp at h2 + | _ => simp at h1 + · simp at h1 + +private theorem merge2Rules_sound [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {r : MCFGRule (MGMCFGNT Base Lic) T} + {args : List (List (List T))} (hM2 : r ∈ merge2Rules (allProfiles G)) + (hargs : InterpList G r.rhs args) : ntInterp G r.lhs (MCFG.evalYield args r.yield) := by + simp only [merge2Rules, List.mem_flatMap] at hM2 + obtain ⟨⟨b1, α1, s1⟩, _, h1⟩ := hM2 + dsimp only at h1 + split at h1 + · cases α1 with + | nil => simp at h1 + | cons hd γ => + cases hd with + | sel x => + simp only [List.mem_filterMap] at h1 + obtain ⟨⟨b2, α2, s2⟩, _, h2⟩ := h1 + dsimp only at h2 + split at h2 + · cases hm : mergeSlots s1 s2 with + | none => simp [hm] at h2 + | some s12 => + simp [hm] at h2; subst h2 + cases hargs with + | cons hi1 hrest => + cases hrest with + | cons hi2 hnil => + cases hnil + obtain ⟨s, ms1, rfl, hslots1, hder1⟩ := hi1 + obtain ⟨t, ms2, rfl, hslots2, hder2⟩ := hi2 + rw [← hslots1, ← hslots2] at hm + have hsmc12 : SMC (ms1 ++ ms2) := + smc_append_of_mergeSlots hder1.smc hder2.smc (movers_in_allLics hder1) hm + obtain ⟨hm', heval⟩ := + evalYield_mergeVars (allLics G) hder1.smc hder2.smc hsmc12 + have hs12_eq : slotsOf (allLics G) (ms1 ++ ms2) = s12 := by + rw [hm] at hm'; simp at hm'; exact hm'.symm + refine ⟨t ++ s, ms1 ++ ms2, ?_, hs12_eq, MG.Derives.merge2 hder1 hder2 hsmc12⟩ + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) ms1, t :: strsOf (allLics G) ms2] + [MCFGAtom.var 1 0, MCFGAtom.var 0 0] = t ++ s := by simp [MCFG.evalComp] + rw [hhead, ← hslots1, ← hslots2] + exact congrArg ((t ++ s) :: ·) (heval [s] [t]) + · simp at h2 + | _ => simp at h1 + · simp at h1 + +private theorem merge3Rules_sound [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {r : MCFGRule (MGMCFGNT Base Lic) T} + {args : List (List (List T))} (hM3 : r ∈ merge3Rules G (allProfiles G)) + (hargs : InterpList G r.rhs args) : ntInterp G r.lhs (MCFG.evalYield args r.yield) := by + simp only [merge3Rules, List.mem_flatMap] at hM3 + obtain ⟨⟨b1, α1, s1⟩, _, h1⟩ := hM3 + dsimp only at h1 + cases α1 with + | nil => simp at h1 + | cons hd γ => + cases hd with + | sel x => + simp only [List.mem_filterMap] at h1 + obtain ⟨⟨b2, α2, s2⟩, _, h2⟩ := h1 + dsimp only at h2 + cases α2 with + | nil => simp at h2 + | cons hd2 tl2 => + cases hd2 with + | cat x' => + cases tl2 with + | nil => simp at h2 + | cons hd3 δ' => + cases hd3 with + | licensee f => + dsimp only at h2 + split at h2 + · next hx => + subst hx + cases hm : mergeSlots s1 s2 with + | none => simp [hm] at h2 + | some s12 => + rw [hm] at h2 + cases hi : insertSlot f (MGFeature.licensee f :: δ') (allLics G) s12 with + | none => simp [hi] at h2 + | some s3 => + simp [hi] at h2; subst h2 + cases hargs with + | cons hi1 hrest => + cases hrest with + | cons hi2 hnil => + cases hnil + obtain ⟨s, ms1, rfl, hslots1, hder1⟩ := hi1 + obtain ⟨t, ms2, rfl, hslots2, hder2⟩ := hi2 + rw [← hslots1, ← hslots2] at hm + have hsmc12 : SMC (ms1 ++ ms2) := + smc_append_of_mergeSlots hder1.smc hder2.smc (movers_in_allLics hder1) hm + obtain ⟨hm', _⟩ := + evalYield_mergeVars (allLics G) hder1.smc hder2.smc hsmc12 + have hs12_eq : slotsOf (allLics G) (ms1 ++ ms2) = s12 := by + rw [hm] at hm'; simp at hm'; exact hm'.symm + rw [← hs12_eq] at hi + have hnotf := not_mem_headLic_of_insertSlot hsmc12 hi + have hsmc3 : SMC (ms1 ++ ⟨t, MGFeature.licensee f :: δ'⟩ :: ms2) := by + refine ⟨?_, ?_⟩ + · intro c hc + rcases List.mem_append.mp hc with h1' | h2' + · exact hder1.smc.1 c h1' + · rcases List.mem_cons.mp h2' with rfl | h2'' + · exact ⟨f, δ', rfl⟩ + · exact hder2.smc.1 c h2'' + · have hnd := hsmc12.2 + rw [List.filterMap_append, List.nodup_append] at hnd + simp only [List.filterMap_append, List.filterMap_cons] + change ((ms1.filterMap MGChain.headLic) ++ f :: (ms2.filterMap MGChain.headLic)).Nodup + rw [List.nodup_append, List.nodup_cons] + refine ⟨hnd.1, ⟨?_, hnd.2.1⟩, ?_⟩ + · intro hmem2 + obtain ⟨c, hc2, hlic⟩ := List.mem_filterMap.mp hmem2 + exact hnotf c (List.mem_append_right _ hc2) hlic + · intro a ha b hb + rcases List.mem_cons.mp hb with rfl | hb2 + · intro heq; subst heq + obtain ⟨c, hc1, hlic⟩ := List.mem_filterMap.mp ha + exact hnotf c (List.mem_append_left _ hc1) hlic + · exact hnd.2.2 a ha b hb2 + have hfL : f ∈ allLics G := by + obtain ⟨entry, hentry, hsuf⟩ := hder2.feats_suffix.1 + exact mem_allLics_of_suffix hentry (MG.isSuffix_tail hsuf) + obtain ⟨hi', heval⟩ := + evalYield_merge3Vars (allLics G) (nodup_allLics G) hfL hder1.smc hder2.smc hsmc3 + have hs3_eq : slotsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f :: δ'⟩ :: ms2) = s3 := by + rw [hi] at hi'; simp at hi'; exact hi'.symm + refine ⟨s, ms1 ++ ⟨t, MGFeature.licensee f :: δ'⟩ :: ms2, ?_, hs3_eq, + MG.Derives.merge3 hder1 hder2 hsmc3⟩ + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) ms1, t :: strsOf (allLics G) ms2] + [MCFGAtom.var 0 0] = s := by simp [MCFG.evalComp] + rw [hhead, ← hslots1, ← hslots2] + exact congrArg (s :: ·) (heval [s] [t] rfl) + · simp at h2 + | _ => simp at h2 + | _ => simp at h2 + | _ => simp at h1 + +mutual + theorem mgToMCFG_sound [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {A : MGMCFGNT Base Lic} {tup : List (List T)} : + MCFG.Yield (mgToMCFG G) A tup → ntInterp G A tup + | MCFG.Yield.rule hr hargs_raw => by + have hargs := mgToMCFG_sound_list hargs_raw + change _ ∈ buildRules G at hr + unfold buildRules at hr + simp only [List.mem_append] at hr + rcases hr with (((((hStart | hLex) | hM1) | hM2) | hM3) | hV1) | hV2 + · -- Start rules + simp only [List.mem_map] at hStart + obtain ⟨b, _, rfl⟩ := hStart + cases hargs with + | cons hi1 hnil => + cases hnil + obtain ⟨s, ms, rfl, hslots, hder⟩ := hi1 + have hms : ms = [] := + movers_nil_of_slotsOf_all_none hder.smc (movers_in_allLics hder) hslots + subst hms + exact ⟨s, by simp [MCFG.evalYield, MCFG.evalComp], b, hder⟩ + · -- Lex rules + simp only [List.mem_map] at hLex + obtain ⟨⟨w, α⟩, hlex, rfl⟩ := hLex + cases hargs + refine ⟨w, [], ?_, slotsOf_nil (allLics G), MG.Derives.lex hlex⟩ + simp [MCFG.evalYield, evalComp_map_tm, strsOf_nil] + · -- Merge 1 rules + exact merge1Rules_sound hM1 hargs + · -- Merge 2 rules + exact merge2Rules_sound hM2 hargs + · -- Merge 3 rules + exact merge3Rules_sound hM3 hargs + · -- Move 1 rules + simp only [List.mem_filterMap] at hV1 + obtain ⟨⟨b, α, s⟩, _, h1⟩ := hV1 + dsimp only at h1 + split at h1 + · cases α with + | nil => simp at h1 + | cons hd γ => + cases hd with + | licensor f => + cases hcl : clearSlot (T := T) f 1 (allLics G) s with + | none => simp [hcl] at h1 + | some triple => + obtain ⟨p, s', vs⟩ := triple + simp [hcl] at h1; subst h1 + cases hargs with + | cons hi1 hnil => + cases hnil + obtain ⟨sHead, ms, rfl, hslots, hder⟩ := hi1 + rw [← hslots] at hcl + obtain ⟨tStr, ms1, ms2, hms_eq, hslots', hget, heval⟩ := + clearSlot_eval_and_mem (allLics G) (nodup_allLics G) hder.smc [sHead] hcl + dsimp only at hms_eq hget heval + simp only [List.singleton_append] at hget heval + rw [hms_eq] at hder + refine ⟨tStr ++ sHead, ms1 ++ ms2, ?_, hslots', MG.Derives.move1 hder⟩ + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [sHead :: strsOf (allLics G) ms] + [MCFGAtom.var 0 p, MCFGAtom.var 0 0] = tStr ++ sHead := by + simp [MCFG.evalComp, hget] + rw [hhead] + exact congrArg ((tStr ++ sHead) :: ·) heval + | _ => simp at h1 + · simp at h1 + · -- Move 2 rules + simp only [List.mem_flatMap] at hV2 + obtain ⟨⟨b, α, s⟩, _, h1⟩ := hV2 + dsimp only at h1 + split at h1 + · cases α with + | nil => simp at h1 + | cons hd γ => + cases hd with + | licensor f => + simp only [List.mem_flatMap, List.mem_filterMap] at h1 + obtain ⟨f', _, δ, hδ, h2⟩ := h1 + cases hrel : relocateSlot (T := T) f f' δ (allLics G) s with + | none => simp [hrel] at h2 + | some pr => + obtain ⟨s', vs⟩ := pr + simp [hrel] at h2; subst h2 + obtain ⟨_, δ', rfl⟩ := mem_licFeats_iff.mp hδ + cases hargs with + | cons hi1 hnil => + cases hnil + obtain ⟨sHead, ms, rfl, hslots, hder⟩ := hi1 + rw [← hslots] at hrel + obtain ⟨tStr, ms1, ms2, hms_eq, hsmcNew, hslots', heval⟩ := + relocateSlot_eval_and_mem (allLics G) (nodup_allLics G) hder.smc + (movers_in_allLics hder) sHead hrel + dsimp only at hms_eq heval + rw [hms_eq] at hder + refine ⟨sHead, ms1 ++ ⟨tStr, MGFeature.licensee f' :: δ'⟩ :: ms2, + ?_, hslots', MG.Derives.move2 hder hsmcNew⟩ + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [sHead :: strsOf (allLics G) ms] + [MCFGAtom.var 0 0] = sHead := by simp [MCFG.evalComp] + rw [hhead] + exact congrArg (sHead :: ·) heval + | _ => simp at h1 + · simp at h1 + + theorem mgToMCFG_sound_list [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {As : List (MGMCFGNT Base Lic)} {args : List (List (List T))} : + MCFG.YieldList (mgToMCFG G) As args → InterpList G As args + | MCFG.YieldList.nil => InterpList.nil + | MCFG.YieldList.cons hy hrest => + InterpList.cons (mgToMCFG_sound hy) (mgToMCFG_sound_list hrest) +end + +private theorem split_at_unique_chain {c : MGChain Base Lic T} {f : Lic} + {left right left' right' : List (MGChain Base Lic T)} (head : c.headLic = some f) + (shortestMove : SMC (left ++ c :: right)) + (split : left ++ c :: right = left' ++ c :: right') : + left = left' ∧ right = right' := by + have not_in_left {a b : List (MGChain Base Lic T)} (smc : SMC (a ++ c :: b)) : c ∉ a := by + intro mem + have unique := smc.2 + simp only [List.filterMap_append, List.filterMap_cons, head, List.nodup_append, + List.nodup_cons] at unique + exact unique.2.2 f (List.mem_filterMap.mpr ⟨c, mem, head⟩) + f (List.mem_cons_self ..) rfl + have leftExcludes := not_in_left shortestMove + have rightExcludes := not_in_left (split ▸ shortestMove) + rcases List.append_eq_append_iff.mp split with ⟨middle, hprefix, hsuffix⟩ | + ⟨middle, hprefix, hsuffix⟩ + · cases middle with + | nil => simp at hprefix hsuffix; exact ⟨hprefix.symm, hsuffix⟩ + | cons first rest => + have first_eq : c = first := (List.cons.inj hsuffix).1 + subst first + apply (rightExcludes ?_).elim + rw [hprefix] + exact List.mem_append_right _ (List.mem_cons_self ..) + · cases middle with + | nil => simp at hprefix hsuffix; exact ⟨hprefix, hsuffix.symm⟩ + | cons first rest => + have first_eq : c = first := (List.cons.inj hsuffix).1 + subst first + apply (leftExcludes ?_).elim + rw [hprefix] + exact List.mem_append_right _ (List.mem_cons_self ..) + +private theorem mgToMCFG_move1_complete [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {s t : List T} + {f : Lic} {γ : List (MGFeature Base Lic)} {ms1 ms2 : List (MGChain Base Lic T)} + (h1 : G.Derives ⟨false, ⟨s, MGFeature.licensor f :: γ⟩, ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2⟩) + (ih1 : (mgToMCFG G).Yield + (MGMCFGNT.prof false (MGFeature.licensor f :: γ) + (slotsOf (allLics G) (ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2))) + (s :: strsOf (allLics G) (ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2))) : + (mgToMCFG G).Yield (MGMCFGNT.prof false γ (slotsOf (allLics G) (ms1 ++ ms2))) + ((t ++ s) :: strsOf (allLics G) (ms1 ++ ms2)) := by + have hp1 := mem_allProfiles_of_derives h1 + have hfL : f ∈ allLics G := + movers_in_allLics h1 ⟨t, [MGFeature.licensee f]⟩ + (List.mem_append_right _ (List.mem_cons_self ..)) f rfl + obtain ⟨p, s', vs, hcl⟩ := clearSlot_complete (T := T) (allLics G) hfL h1.smc 1 + obtain ⟨t', ms1', ms2', hms_eq, hslots', hget, heval⟩ := + clearSlot_eval_and_mem (allLics G) (nodup_allLics G) h1.smc [s] hcl + dsimp only at hms_eq hget heval + simp only [List.singleton_append] at hget heval + -- Uniqueness of the mover with headLic = some f forces t' = t and same slots/strs! + have ht_eq : t' = t := by + have hc1 : ⟨t, [MGFeature.licensee f]⟩ ∈ ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2 := + List.mem_append_right _ (List.mem_cons_self ..) + have hc2 : ⟨t', [MGFeature.licensee f]⟩ ∈ ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2 := by + rw [hms_eq]; exact List.mem_append_right _ (List.mem_cons_self ..) + have hceq := smc_unique_chain h1.smc hc2 rfl hc1 rfl + simpa using congrArg MGChain.str hceq + subst t' + obtain ⟨rfl, rfl⟩ := split_at_unique_chain rfl h1.smc hms_eq + have hr : ({ lhs := MGMCFGNT.prof false γ s', + rhs := [MGMCFGNT.prof false (MGFeature.licensor f :: γ) + (slotsOf (allLics G) (ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2))], + yield := [MCFGAtom.var 0 p, MCFGAtom.var 0 0] :: vs } : + MCFGRule (MGMCFGNT Base Lic) T) ∈ (mgToMCFG G).rules := by + change _ ∈ buildRules G + unfold buildRules + simp only [List.mem_append, List.mem_filterMap] + left; right + exact ⟨(false, MGFeature.licensor f :: γ, + slotsOf (allLics G) (ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2)), hp1, by simp [hcl]⟩ + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons ih1 MCFG.YieldList.nil) + have hev : MCFG.evalYield [s :: strsOf (allLics G) (ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2)] + ([MCFGAtom.var 0 p, MCFGAtom.var 0 0] :: vs) = + (t ++ s) :: strsOf (allLics G) (ms1 ++ ms2) := by + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) (ms1 ++ ⟨t, [MGFeature.licensee f]⟩ :: ms2)] + [MCFGAtom.var 0 p, MCFGAtom.var 0 0] = t ++ s := by simp [MCFG.evalComp, hget] + rw [hhead] + exact congrArg ((t ++ s) :: ·) heval + simpa [hslots', hev] using hy + +private theorem mgToMCFG_move2_complete [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {s t : List T} + {f f' : Lic} {γ δ' : List (MGFeature Base Lic)} {ms1 ms2 : List (MGChain Base Lic T)} + (h1 : G.Derives ⟨false, ⟨s, MGFeature.licensor f :: γ⟩, ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2⟩) + (hsmcNew : SMC (ms1 ++ ⟨t, MGFeature.licensee f' :: δ'⟩ :: ms2)) + (ih1 : (mgToMCFG G).Yield + (MGMCFGNT.prof false (MGFeature.licensor f :: γ) + (slotsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2))) + (s :: strsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2))) : + (mgToMCFG G).Yield (MGMCFGNT.prof false γ (slotsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f' :: δ'⟩ :: ms2))) + ((s) :: strsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f' :: δ'⟩ :: ms2)) := by + have hp1 := mem_allProfiles_of_derives h1 + have hfL : f ∈ allLics G := + movers_in_allLics h1 ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ + (List.mem_append_right _ (List.mem_cons_self ..)) f rfl + obtain ⟨entry, hentry, hsuf⟩ := + h1.feats_suffix.2 ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ + (List.mem_append_right _ (List.mem_cons_self ..)) + have hf'L : f' ∈ allLics G := mem_allLics_of_suffix hentry (MG.isSuffix_tail hsuf) + have hlf : MGFeature.licensee f' :: δ' ∈ licFeats G f' := + mem_licFeats_iff.mpr ⟨mem_allFeats_of_suffix hentry (MG.isSuffix_tail hsuf), δ', rfl⟩ + obtain ⟨s', vs, hrel⟩ := relocateSlot_complete (T := T) (allLics G) hfL hf'L h1.smc hsmcNew + obtain ⟨t', ms1', ms2', hms_eq, _, hslots', heval⟩ := + relocateSlot_eval_and_mem (allLics G) (nodup_allLics G) h1.smc (movers_in_allLics h1) s hrel + dsimp only at hms_eq heval + have ht_eq : t' = t := by + have hc1 : ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ ∈ + ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2 := + List.mem_append_right _ (List.mem_cons_self ..) + have hc2 : ⟨t', MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ ∈ + ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2 := by + rw [hms_eq]; exact List.mem_append_right _ (List.mem_cons_self ..) + have hceq := smc_unique_chain h1.smc hc2 rfl hc1 rfl + simpa using congrArg MGChain.str hceq + subst t' + obtain ⟨rfl, rfl⟩ := split_at_unique_chain rfl h1.smc hms_eq + have hr : ({ lhs := MGMCFGNT.prof false γ s', + rhs := [MGMCFGNT.prof false (MGFeature.licensor f :: γ) + (slotsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2))], + yield := [MCFGAtom.var 0 0] :: vs } : + MCFGRule (MGMCFGNT Base Lic) T) ∈ (mgToMCFG G).rules := by + change _ ∈ buildRules G + unfold buildRules + simp only [List.mem_append, List.mem_flatMap, List.mem_filterMap] + right + refine ⟨(false, MGFeature.licensor f :: γ, + slotsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2)), hp1, ?_⟩ + simp only [↓reduceIte, List.mem_flatMap, List.mem_filterMap] + exact ⟨f', hf'L, MGFeature.licensee f' :: δ', hlf, by simp [hrel]⟩ + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons ih1 MCFG.YieldList.nil) + have hev : MCFG.evalYield [s :: strsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2)] + ([MCFGAtom.var 0 0] :: vs) = + s :: strsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f' :: δ'⟩ :: ms2) := by + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) (ms1 ++ ⟨t, MGFeature.licensee f :: MGFeature.licensee f' :: δ'⟩ :: ms2)] + [MCFGAtom.var 0 0] = s := by simp [MCFG.evalComp] + rw [hhead] + exact congrArg (s :: ·) heval + simpa [hslots', hev] using hy + +/-- Completeness of `mgToMCFG`: every derivable MG expression yields its canonical tuple in `mgToMCFG G`. -/ +theorem mgToMCFG_complete [DecidableEq Base] [DecidableEq Lic] + {G : MG Base Lic T} {e : MGExpr Base Lic T} (h : MG.Derives G e) : + MCFG.Yield (mgToMCFG G) + (MGMCFGNT.prof e.isLex e.head.feats (slotsOf (allLics G) e.movers)) + (e.head.str :: strsOf (allLics G) e.movers) := by + induction h with + | @lex w α hlex => + have hr : ({ lhs := MGMCFGNT.prof true α ((allLics G).map fun _ => none), + rhs := [], yield := [w.map MCFGAtom.tm] } : MCFGRule (MGMCFGNT Base Lic) T) ∈ + (mgToMCFG G).rules := by + change _ ∈ buildRules G + unfold buildRules + simp only [List.mem_append, List.mem_map] + left; left; left; left; left; right + exact ⟨(w, α), hlex, rfl⟩ + have hy := MCFG.Yield.rule hr MCFG.YieldList.nil + simpa [slotsOf_nil, strsOf_nil, MCFG.evalYield, evalComp_map_tm] using hy + | @merge1 s t x γ b ms h1 h2 ih1 ih2 => + have hp1 := mem_allProfiles_of_derives h1 + have hp2 := mem_allProfiles_of_derives h2 + simp only [slotsOf_nil] at hp1 ih1 + let tailVars := (List.range ((slotsOf (allLics G) ms).countP Option.isSome)).map fun k => + [MCFGAtom.var (T := T) 1 (1 + k)] + have hr : ({ lhs := MGMCFGNT.prof false γ (slotsOf (allLics G) ms), + rhs := [MGMCFGNT.prof true (MGFeature.sel x :: γ) ((allLics G).map fun _ => none), + MGMCFGNT.prof b [MGFeature.cat x] (slotsOf (allLics G) ms)], + yield := [MCFGAtom.var 0 0, MCFGAtom.var 1 0] :: tailVars } : + MCFGRule (MGMCFGNT Base Lic) T) ∈ (mgToMCFG G).rules := by + change _ ∈ buildRules G + unfold buildRules + simp only [List.mem_append, List.mem_flatMap, List.mem_filterMap] + left; left; left; left; right + refine ⟨(true, MGFeature.sel x :: γ, (allLics G).map fun _ => none), hp1, ?_⟩ + simp only [and_self, ↓reduceIte, List.mem_filterMap] + exact ⟨(b, [MGFeature.cat x], slotsOf (allLics G) ms), hp2, by simp [tailVars]⟩ + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons ih1 (MCFG.YieldList.cons ih2 MCFG.YieldList.nil)) + have hev : MCFG.evalYield [s :: strsOf (allLics G) ([] : List (MGChain Base Lic T)), t :: strsOf (allLics G) ms] + ([MCFGAtom.var 0 0, MCFGAtom.var 1 0] :: tailVars) = + (s ++ t) :: strsOf (allLics G) ms := by + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) ([] : List (MGChain Base Lic T)), t :: strsOf (allLics G) ms] + [MCFGAtom.var 0 0, MCFGAtom.var 1 0] = s ++ t := by simp [MCFG.evalComp] + rw [hhead]; congr 1 + dsimp only [tailVars] + rw [← strsOf_length (allLics G) ms] + exact evalYield_range_vars1 (s :: strsOf (allLics G) ([] : List (MGChain Base Lic T))) + [t] (strsOf (allLics G) ms) + simpa [hev] using hy + | @merge2 s t x γ b ms1 ms2 h1 h2 hsmc12 ih1 ih2 => + have hp1 := mem_allProfiles_of_derives h1 + have hp2 := mem_allProfiles_of_derives h2 + obtain ⟨hm, heval⟩ := evalYield_mergeVars (allLics G) h1.smc h2.smc hsmc12 + have hr : ({ lhs := MGMCFGNT.prof false γ (slotsOf (allLics G) (ms1 ++ ms2)), + rhs := [MGMCFGNT.prof false (MGFeature.sel x :: γ) (slotsOf (allLics G) ms1), + MGMCFGNT.prof b [MGFeature.cat x] (slotsOf (allLics G) ms2)], + yield := [MCFGAtom.var 1 0, MCFGAtom.var 0 0] :: + mergeVars 1 1 (slotsOf (allLics G) ms1) (slotsOf (allLics G) ms2) } : + MCFGRule (MGMCFGNT Base Lic) T) ∈ (mgToMCFG G).rules := by + change _ ∈ buildRules G + unfold buildRules + simp only [List.mem_append, List.mem_flatMap, List.mem_filterMap] + left; left; left; right + refine ⟨(false, MGFeature.sel x :: γ, slotsOf (allLics G) ms1), hp1, ?_⟩ + simp only [↓reduceIte, List.mem_filterMap] + exact ⟨(b, [MGFeature.cat x], slotsOf (allLics G) ms2), hp2, by simp [hm]⟩ + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons ih1 (MCFG.YieldList.cons ih2 MCFG.YieldList.nil)) + have hev : MCFG.evalYield [s :: strsOf (allLics G) ms1, t :: strsOf (allLics G) ms2] + ([MCFGAtom.var 1 0, MCFGAtom.var 0 0] :: + mergeVars 1 1 (slotsOf (allLics G) ms1) (slotsOf (allLics G) ms2)) = + (t ++ s) :: strsOf (allLics G) (ms1 ++ ms2) := by + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) ms1, t :: strsOf (allLics G) ms2] + [MCFGAtom.var 1 0, MCFGAtom.var 0 0] = t ++ s := by simp [MCFG.evalComp] + rw [hhead] + exact congrArg ((t ++ s) :: ·) (heval [s] [t]) + simpa [hev] using hy + | @merge3 s t x f γ δ' b1 b2 ms1 ms2 h1 h2 hsmc3 ih1 ih2 => + have hp1 := mem_allProfiles_of_derives h1 + have hp2 := mem_allProfiles_of_derives h2 + have hsmc12 : SMC (ms1 ++ ms2) := MG.smc_remove hsmc3 + have hfL : f ∈ allLics G := by + obtain ⟨entry, hentry, hsuf⟩ := h2.feats_suffix.1 + exact mem_allLics_of_suffix hentry (MG.isSuffix_tail hsuf) + obtain ⟨hm, _⟩ := evalYield_mergeVars (allLics G) h1.smc h2.smc hsmc12 + obtain ⟨hi, heval⟩ := + evalYield_merge3Vars (allLics G) (nodup_allLics G) hfL h1.smc h2.smc hsmc3 + let ms3 := ms1 ++ ⟨t, MGFeature.licensee f :: δ'⟩ :: ms2 + have hr : ({ lhs := MGMCFGNT.prof false γ (slotsOf (allLics G) ms3), + rhs := [MGMCFGNT.prof b1 (MGFeature.sel x :: γ) (slotsOf (allLics G) ms1), + MGMCFGNT.prof b2 (MGFeature.cat x :: MGFeature.licensee f :: δ') (slotsOf (allLics G) ms2)], + yield := [MCFGAtom.var 0 0] :: + merge3Vars f 1 1 (allLics G) (slotsOf (allLics G) ms1) (slotsOf (allLics G) ms2) } : + MCFGRule (MGMCFGNT Base Lic) T) ∈ (mgToMCFG G).rules := by + change _ ∈ buildRules G + unfold buildRules + simp only [List.mem_append, List.mem_flatMap, List.mem_filterMap] + left; left; right + refine ⟨(b1, MGFeature.sel x :: γ, slotsOf (allLics G) ms1), hp1, ?_⟩ + simp only [List.mem_filterMap] + exact ⟨(b2, MGFeature.cat x :: MGFeature.licensee f :: δ', slotsOf (allLics G) ms2), hp2, + by simp [hm, hi, ms3]⟩ + have hy := MCFG.Yield.rule hr (MCFG.YieldList.cons ih1 (MCFG.YieldList.cons ih2 MCFG.YieldList.nil)) + have hev : MCFG.evalYield [s :: strsOf (allLics G) ms1, t :: strsOf (allLics G) ms2] + ([MCFGAtom.var 0 0] :: + merge3Vars f 1 1 (allLics G) (slotsOf (allLics G) ms1) (slotsOf (allLics G) ms2)) = + s :: strsOf (allLics G) ms3 := by + simp only [MCFG.evalYield, List.map_cons] + have hhead : MCFG.evalComp [s :: strsOf (allLics G) ms1, t :: strsOf (allLics G) ms2] + [MCFGAtom.var 0 0] = s := by simp [MCFG.evalComp] + rw [hhead] + exact congrArg (s :: ·) (heval [s] [t] rfl) + simpa [hev] using hy + | @move1 s t f γ ms1 ms2 h1 ih1 => + exact mgToMCFG_move1_complete h1 ih1 + | @move2 s t f f' γ δ' ms1 ms2 h1 hsmcNew ih1 => + exact mgToMCFG_move2_complete h1 hsmcNew ih1 + +/-- **Michaelis Theorem (1998, 2001) — Direction 1 (`MG → MCFG`)**: + Every Minimalist Grammar has a weakly equivalent Linear Non-Erasing MCFG (LCFRS). -/ +theorem mgToMCFG_lang [DecidableEq Base] [DecidableEq Lic] + (G : MG Base Lic T) (w : List T) : + (mgToMCFG G).Lang w ↔ G.Lang w := by + constructor + · intro h + obtain ⟨w', hw, hlang⟩ := mgToMCFG_sound h + simp at hw; subst hw; exact hlang + · rintro ⟨b, hder⟩ + have hy := mgToMCFG_complete hder + simp only [slotsOf_nil, strsOf_nil] at hy + have hr : ({ lhs := MGMCFGNT.start, + rhs := [MGMCFGNT.prof b [MGFeature.cat G.start] ((allLics G).map fun _ => none)], + yield := [[MCFGAtom.var 0 0]] } : MCFGRule (MGMCFGNT Base Lic) T) ∈ + (mgToMCFG G).rules := by + change _ ∈ buildRules G + unfold buildRules + simp only [List.mem_append, List.mem_map] + left; left; left; left; left; left + exact ⟨b, by cases b <;> simp, rfl⟩ + have hres := MCFG.Yield.rule hr (MCFG.YieldList.cons hy MCFG.YieldList.nil) + change MCFG.Yield (mgToMCFG G) MGMCFGNT.start [w] + simpa [MCFG.evalYield, MCFG.evalComp] using hres + +end MGtoMCFG +end FormalLinguistics diff --git a/LeanPool/FormalLinguistics/MathlibBridge.lean b/LeanPool/FormalLinguistics/MathlibBridge.lean new file mode 100644 index 0000000000..9019756c6c --- /dev/null +++ b/LeanPool/FormalLinguistics/MathlibBridge.lean @@ -0,0 +1,154 @@ +/- +Copyright (c) 2026 Lean Pool contributors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Lean Pool contributors +-/ + +module + +public import LeanPool.FormalLinguistics.LambekPentus +public import Mathlib.Computability.ContextFreeGrammar + +/-! +# Context-free languages in Mathlib + +The list of productions used by the grammar transformations has the same language semantics as +Mathlib's finite set of productions. The equivalences for basic categorial grammars and Lambek +grammars can therefore be used with `Language.IsContextFree`. +-/ + +@[expose] public section + +namespace FormalLinguistics + +/-- Identify the transformation grammar symbols with Mathlib’s grammar symbols. -/ +def symbolEquiv {N T : Type} : Symbol N T ≃ _root_.Symbol T N where + toFun + | .nt n => .nonterminal n + | .tm t => .terminal t + invFun + | .nonterminal n => .nt n + | .terminal t => .tm t + left_inv := by intro x; cases x <;> rfl + right_inv := by intro x; cases x <;> rfl + +/-- Read a Mathlib grammar as a list of productions for the grammar transformations. -/ +noncomputable def CFG.ofMathlib {T : Type} (G : ContextFreeGrammar T) : CFG G.NT T where + start := G.initial + rules := G.rules.toList.map fun rule => (rule.input, rule.output.map symbolEquiv.symm) + +/-- Interpret a list-based grammar as a Mathlib grammar, ignoring repeated productions. -/ +noncomputable abbrev CFG.toMathlib {N T : Type} (G : CFG N T) : ContextFreeGrammar T := + ⟨N, G.start, by + classical + exact (G.rules.map fun rule => ⟨rule.1, rule.2.map symbolEquiv⟩).toFinset⟩ + +private theorem map_encode_decode {N T : Type} (symbols : List (Symbol N T)) : + (symbols.map symbolEquiv).map symbolEquiv.symm = symbols := by + simp [List.map_map, Function.comp_def] + +private theorem map_decode_encode {N T : Type} (symbols : List (_root_.Symbol T N)) : + (symbols.map symbolEquiv.symm).map symbolEquiv = symbols := by + simp [List.map_map, Function.comp_def] + +private theorem CFG.produces_map_iff {N T : Type} (G : CFG N T) {u v : List (Symbol N T)} : + G.toMathlib.Produces (u.map symbolEquiv) (v.map symbolEquiv) ↔ G.Step u v := by + classical + constructor + · rintro ⟨r, hr, rewrites⟩ + change r ∈ (G.rules.map fun rule => (⟨rule.1, rule.2.map symbolEquiv⟩ : + ContextFreeRule T N)).toFinset at hr + obtain ⟨⟨A, rhs⟩, hRule, rfl⟩ := List.mem_map.mp (List.mem_toFinset.mp hr) + obtain ⟨left, suffix, hp, hq⟩ := rewrites.exists_parts + change u.map symbolEquiv = left ++ [_root_.Symbol.nonterminal A] ++ suffix at hp + change v.map symbolEquiv = left ++ rhs.map symbolEquiv ++ suffix at hq + have hpu := congrArg (List.map symbolEquiv.symm) hp + have hqv := congrArg (List.map symbolEquiv.symm) hq + simp only [map_encode_decode, List.map_append, List.map_cons, List.map_nil] at hpu hqv + rw [hpu, hqv] + exact .mk _ _ _ _ hRule + · rintro ⟨left, suffix, rhs, A, hr⟩ + refine ⟨⟨A, rhs.map symbolEquiv⟩, ?_, ?_⟩ + · change _ ∈ (G.rules.map fun rule => (⟨rule.1, rule.2.map symbolEquiv⟩ : + ContextFreeRule T N)).toFinset + exact List.mem_toFinset.mpr (List.mem_map.mpr ⟨(A, rhs), hr, rfl⟩) + · simpa [List.map_append, symbolEquiv] using + ContextFreeRule.rewrites_of_exists_parts + (⟨A, rhs.map symbolEquiv⟩ : ContextFreeRule T N) + (left.map symbolEquiv) (suffix.map symbolEquiv) + +private theorem CFG.derives_of_mathlib {N T : Type} (G : CFG N T) + {u v : List (_root_.Symbol T N)} (h : G.toMathlib.Derives u v) : + G.Derives (u.map symbolEquiv.symm) (v.map symbolEquiv.symm) := by + induction h with + | refl => exact .refl _ + | @tail w x _ step ih => + apply CFG.Derives.tail ih + apply (G.produces_map_iff).mp + rw [map_decode_encode, map_decode_encode] + exact step + +/-- Applying Mathlib's derivation relation to a converted grammar preserves its language. -/ +theorem CFG.mem_toMathlib_language {N T : Type} (G : CFG N T) (w : List T) : + w ∈ G.toMathlib.language ↔ G.Lang w := by + change G.toMathlib.Derives [_root_.Symbol.nonterminal G.start] (w.map _root_.Symbol.terminal) ↔ + G.Derives [.nt G.start] (w.map Symbol.tm) + constructor + · intro h + have mapped := G.derives_of_mathlib h + rw [List.map_map] at mapped + exact mapped + · intro h + have transport {u v : List (Symbol N T)} (h : G.Derives u v) : + G.toMathlib.Derives (u.map symbolEquiv) (v.map symbolEquiv) := by + induction h with + | refl => exact Relation.ReflTransGen.refl + | tail _ step ih => exact .tail ih (G.produces_map_iff.mpr step) + have mapped := transport h + rw [List.map_map] at mapped + exact mapped + +/-- A Mathlib grammar round-trips through the list presentation. -/ +theorem CFG.toMathlib_ofMathlib {T : Type} (G : ContextFreeGrammar T) : + (CFG.ofMathlib G).toMathlib = G := by + classical + cases G with + | mk N start rules => + suffices ((rules.toList.map fun rule => (rule.input, rule.output.map symbolEquiv.symm)).map + fun rule => (⟨rule.1, rule.2.map symbolEquiv⟩ : ContextFreeRule T N)).toFinset = rules + from congrArg (ContextFreeGrammar.mk N start) this + rw [List.map_map] + change (List.map (fun rule : ContextFreeRule T N => + (⟨rule.input, (rule.output.map symbolEquiv.symm).map symbolEquiv⟩ : + ContextFreeRule T N)) rules.toList).toFinset = rules + simp + +/-- The language recognized by the list presentation of a Mathlib grammar. -/ +theorem CFG.ofMathlib_lang {T : Type} (G : ContextFreeGrammar T) (w : List T) : + (CFG.ofMathlib G).Lang w ↔ w ∈ G.language := by + rw [← CFG.mem_toMathlib_language, CFG.toMathlib_ofMathlib] + +private theorem contextFree_iff {T : Type} (L : Language T) : + (∃ (N : Type) (_ : DecidableEq N) (G : CFG N T), ∀ w, G.Lang w ↔ w ∈ L) ↔ + L.IsContextFree := by + classical + constructor + · rintro ⟨N, _, G, hG⟩ + exact ⟨G.toMathlib, Set.ext fun w => (G.mem_toMathlib_language w).trans (hG w)⟩ + · rintro ⟨G, rfl⟩ + exact ⟨G.NT, Classical.typeDecidableEq G.NT, CFG.ofMathlib G, CFG.ofMathlib_lang G⟩ + +/-- Basic categorial grammars recognize precisely the epsilon-free context-free languages. -/ +theorem bar_hillel_gaifman_shamir_isContextFree {T : Type} (L : Language T) : + (∃ (P : Type) (G : ABG P T), ∀ w, G.Lang w ↔ w ∈ L) ↔ + L.IsContextFree ∧ [] ∉ L := by + classical + exact (bar_hillel_gaifman_shamir (· ∈ L)).trans ((contextFree_iff L).and Iff.rfl) + +/-- Product Lambek grammars recognize precisely the epsilon-free context-free languages. -/ +theorem chomsky_pentus_isContextFree {T : Type} (L : Language T) : + IsLambekLang (· ∈ L) ↔ L.IsContextFree ∧ [] ∉ L := by + classical + exact (chomsky_pentus (· ∈ L)).trans ((contextFree_iff L).and Iff.rfl) + +end FormalLinguistics diff --git a/LeanPool/projects/formal-grammar-equivalences.yaml b/LeanPool/projects/formal-grammar-equivalences.yaml new file mode 100644 index 0000000000..fedd71f281 --- /dev/null +++ b/LeanPool/projects/formal-grammar-equivalences.yaml @@ -0,0 +1,45 @@ +slug: formal-grammar-equivalences +title: Categorial, Lambek, and minimalist grammar equivalences +summary: Proves weak language equivalences for basic categorial grammars, + product Lambek grammars, and chain-based minimalist grammars. The development + includes context-free normal forms, Lambek cut elimination and interpolation, + and language-preserving translations between minimalist and multiple + context-free grammars. +branch: formal language theory +entry_module: LeanPool.FormalLinguistics +authors: +- bocchitherock888-ux +source: + url: https://github.com/bocchitherock888-ux/lean-grammar-equivalences/releases/tag/v2.0 + github_repo: bocchitherock888-ux/lean-grammar-equivalences + commit: 967b3f2cfa05b52ca253b37d3e58b49abd6d150d +license: MIT +status: verified +provenance: AI +main_declarations: +- FormalLinguistics.bar_hillel_gaifman_shamir +- FormalLinguistics.chomsky_pentus +- FormalLinguistics.michaelis_harkema_equivalence_SK +main_results: +- declaration: FormalLinguistics.bar_hillel_gaifman_shamir + informal: Over a terminal type with decidable equality, the languages of + basic categorial grammars are exactly the context-free languages that + exclude the empty word. + source_ref: Bar-Hillel, Gaifman and Shamir (1960), On categorial and phrase-structure grammars. +- declaration: FormalLinguistics.chomsky_pentus + informal: Over a terminal type with decidable equality, the languages of + product Lambek grammars with a distinguished primitive type are exactly the + context-free languages that exclude the empty word. + source_ref: Pentus (1993), Lambek grammars are context free, via Kanazawa (2018), Sections 3–4, arXiv:1709.07695. +- declaration: FormalLinguistics.michaelis_harkema_equivalence_SK + informal: The languages of the formalized Stabler–Keenan minimalist grammars + are exactly those generated by linear non-erasing multiple context-free grammars. + source_ref: Michaelis, DOI 10.1007/3-540-48199-0_14, and Harkema, DOI 10.1007/3-540-48199-0_12. +tags: +- formal-languages +- categorial-grammars +- lambek-calculus +- minimalist-grammars +msc: +- 68Q42 +- 03B47 From e69454de7e41202b5deeb4fbb5022e18841eb4ce Mon Sep 17 00:00:00 2001 From: Vasily Ilin Date: Sat, 28 Nov 2026 11:33:19 +0000 Subject: [PATCH 2/3] Correct grammar theorem attributions and narrow the translation imports --- LeanPool/FormalLinguistics/CNF.lean | 34 -------- LeanPool/FormalLinguistics/Fixpoint.lean | 36 ++++++++- LeanPool/FormalLinguistics/LambekPentus.lean | 12 +-- LeanPool/FormalLinguistics/MGMCFGEquiv.lean | 6 +- LeanPool/FormalLinguistics/MGOriginal.lean | 77 ++++++------------- LeanPool/FormalLinguistics/MGtoMCFG.lean | 16 ++-- LeanPool/FormalLinguistics/MathlibBridge.lean | 7 +- .../projects/formal-grammar-equivalences.yaml | 7 +- 8 files changed, 87 insertions(+), 108 deletions(-) diff --git a/LeanPool/FormalLinguistics/CNF.lean b/LeanPool/FormalLinguistics/CNF.lean index db9be6b2fc..2952a38073 100644 --- a/LeanPool/FormalLinguistics/CNF.lean +++ b/LeanPool/FormalLinguistics/CNF.lean @@ -19,40 +19,6 @@ public import LeanPool.FormalLinguistics.Fixpoint namespace FormalLinguistics -/-- Simple self-contained deduplication on lists (independent of Lean/Mathlib version). -/ -def dedupList [DecidableEq α] : List α → List α - | [] => [] - | a :: t => - let r := dedupList t - if a ∈ r then r else a :: r - -theorem mem_dedupList [DecidableEq α] {x : α} {l : List α} : - x ∈ dedupList l ↔ x ∈ l := by - induction l with - | nil => simp [dedupList] - | cons a t ih => - simp only [dedupList] - split - · next h => - rw [ih] - constructor - · intro hx; exact List.mem_cons_of_mem a hx - · intro hx - rcases List.mem_cons.mp hx with rfl | ht - · exact ih.mp h - · exact ht - · next h => - simp [ih] - -theorem nodup_dedupList [DecidableEq α] (l : List α) : (dedupList l).Nodup := by - induction l with - | nil => exact List.nodup_nil - | cons a t ih => - simp only [dedupList] - split - · exact ih - · next h => exact List.nodup_cons.mpr ⟨h, ih⟩ - /-! ### Stage 1: Binarized CFG (all RHS have length ≤ 2, terminals isolated) -/ /-- An original nonterminal, a lifted terminal, or a symbol naming a rule suffix. -/ diff --git a/LeanPool/FormalLinguistics/Fixpoint.lean b/LeanPool/FormalLinguistics/Fixpoint.lean index dca6e412a7..02ed0f4e6b 100644 --- a/LeanPool/FormalLinguistics/Fixpoint.lean +++ b/LeanPool/FormalLinguistics/Fixpoint.lean @@ -9,7 +9,7 @@ module public import Init /-! - Lightweight finite-universe monotone fixpoint helper (pure Lean 4, no Mathlib needed). + Deduplication and monotone fixed-point iteration on finite lists. The iteration is a computable function. Its soundness proof (`fixpoint_sound`) is choice-free; its convergence proof (`fixpoint_closed`) depends on `Classical.choice`. -/ @@ -18,6 +18,40 @@ public import Init namespace FormalLinguistics +/-- Deduplicate a finite universe by keeping the last occurrence of each element. -/ +def dedupList [DecidableEq α] : List α → List α + | [] => [] + | a :: t => + let r := dedupList t + if a ∈ r then r else a :: r + +theorem mem_dedupList [DecidableEq α] {x : α} {l : List α} : + x ∈ dedupList l ↔ x ∈ l := by + induction l with + | nil => simp [dedupList] + | cons a t ih => + simp only [dedupList] + split + · next h => + rw [ih] + constructor + · intro hx; exact List.mem_cons_of_mem a hx + · intro hx + rcases List.mem_cons.mp hx with rfl | ht + · exact ih.mp h + · exact ht + · next h => + simp [ih] + +theorem nodup_dedupList [DecidableEq α] (l : List α) : (dedupList l).Nodup := by + induction l with + | nil => exact List.nodup_nil + | cons a t ih => + simp only [dedupList] + split + · exact ih + · next h => exact List.nodup_cons.mpr ⟨h, ih⟩ + /-- If `l1` has no duplicates and every element of `l1` lies in `l2`, then `l1.length ≤ l2.length`. -/ theorem nodup_length_le [DecidableEq α] {l1 l2 : List α} (hnd : l1.Nodup) (hsub : ∀ x, x ∈ l1 → x ∈ l2) : l1.length ≤ l2.length := by diff --git a/LeanPool/FormalLinguistics/LambekPentus.lean b/LeanPool/FormalLinguistics/LambekPentus.lean index 35e664cd3f..2f29cf9c31 100644 --- a/LeanPool/FormalLinguistics/LambekPentus.lean +++ b/LeanPool/FormalLinguistics/LambekPentus.lean @@ -12,8 +12,8 @@ public import LeanPool.FormalLinguistics.LambekFreeGroup public import LeanPool.FormalLinguistics.LambekThin /-! - Pentus's theorem (1993): every Lambek grammar generates a context-free language, and - the resulting characterisation of Lambek languages (Chomsky's conjecture). + The primitive-goal case of Pentus’s 1993 theorem and the resulting characterization of the + languages generated by product Lambek grammars with a distinguished primitive type. The proof follows Pentus's argument as presented by Kanazawa (2018, Section 4): thin sequents, interpolation, the free-group interpretation and Pentus's lemma about @@ -511,8 +511,8 @@ theorem le_sum_of_mem {α : Type} (f : α → Nat) {l : List α} {x : α} (h : x end LPentus -/-- **Pentus's theorem.** Every Lambek grammar has a context-free grammar generating the - same language. -/ +/-- The primitive-goal case of Pentus (1993), Theorem 2. Each product Lambek grammar with a +distinguished primitive type has a context-free grammar generating the same language. -/ theorem lambek_to_cfg {P T : Type} (G : LambekGrammar P T) : ∃ G' : CFG (LType P) T, ∀ w, G'.Lang w ↔ G.Lang w := by classical @@ -543,8 +543,8 @@ theorem lambek_to_cfg {P T : Type} (G : LambekGrammar P T) : def IsLambekLang {T : Type} (L : List T → Prop) : Prop := ∃ (P : Type) (G : LambekGrammar P T), ∀ w, G.Lang w ↔ L w -/-- **Chomsky–Pentus theorem.** A language is generated by a Lambek grammar if and only if - it is an ε-free context-free language. -/ +/-- A language is generated by a product Lambek grammar with a primitive goal if and only if +it is an ε-free context-free language. -/ theorem chomsky_pentus {T : Type} [DecidableEq T] (L : List T → Prop) : IsLambekLang L ↔ ((∃ (N : Type) (_ : DecidableEq N) (G : CFG N T), ∀ w, G.Lang w ↔ L w) ∧ ¬ L []) := by diff --git a/LeanPool/FormalLinguistics/MGMCFGEquiv.lean b/LeanPool/FormalLinguistics/MGMCFGEquiv.lean index 4d78ae669a..24a340853a 100644 --- a/LeanPool/FormalLinguistics/MGMCFGEquiv.lean +++ b/LeanPool/FormalLinguistics/MGMCFGEquiv.lean @@ -14,7 +14,7 @@ public import LeanPool.FormalLinguistics.MCFGtoMG Main machine-checked result: The class of languages generated by finite chain-based Minimalist Grammars - (Stabler 1997; Stabler & Keenan 2003) coincides exactly with the class of + in the invariant-carrying presentation coincides exactly with the class of languages generated by finite Linear Non-Erasing Multiple Context-Free Grammars / Linear Context-Free Rewriting Systems (Seki et al. 1991; Vijay-Shanker, Weir & Joshi 1987): @@ -75,8 +75,8 @@ def IsMCFGLang {T : Type} (L : List T → Prop) : Prop := ∃ (N : Type) (G : MCFG N T), ∀ w, G.Lang w ↔ L w /-- **Michaelis–Harkema Equivalence Theorem** (`L(MG) = L(MCFG)` over any alphabet `T`): - Every Minimalist Grammar language is an MCFG/LCFRS language (Michaelis 1998, 2001), - and every MCFG/LCFRS language is a Minimalist Grammar language (Harkema 2001; Michaelis 2001). -/ +The translations adapt Michaelis’s LACL 1998 forward inclusion and the LACL 2001 +converse constructions of Michaelis and Harkema to the chain-based presentation. -/ theorem michaelis_harkema_equivalence {T : Type} (L : List T → Prop) : IsMGLang L ↔ IsMCFGLang L := by constructor diff --git a/LeanPool/FormalLinguistics/MGOriginal.lean b/LeanPool/FormalLinguistics/MGOriginal.lean index 64ea7b8730..6fe464cf24 100644 --- a/LeanPool/FormalLinguistics/MGOriginal.lean +++ b/LeanPool/FormalLinguistics/MGOriginal.lean @@ -9,55 +9,27 @@ module public import LeanPool.FormalLinguistics.MGMCFGEquiv /-! - Minimalist Grammars exactly as stated by Stabler & Keenan (2003), and their - equivalence with the invariant-carrying presentation used in `MG.lean`. - - `MG.Derives` (in `MG.lean`) differs from the textbook definition in two ways: - - 1. The Shortest Move Constraint is imposed as an invariant on every derived - expression (`merge2`, `merge3`, `move2` all carry an `SMC` premise), - whereas Stabler & Keenan impose it only as a side condition on `move`: - "none of the other chains has `-f` as its first feature". - 2. `merge3` and `move2` require the remaining feature string of the mover to - begin with a licensee, whereas Stabler & Keenan only require it to be - non-empty. - - This file defines `MG.DerivesSK`, which follows Stabler & Keenan literally. - The rules were checked against Stabler & Keenan (2003), p. 347, whose - `merge1`–`merge3`, `move1`–`move2` and (SMC) are the constructors below, and - against Harkema (2000), "A recognizer for minimalist grammars" (IWPT), - §3.2.2, whose six inference rules correspond to them as follows: - - Harkema Merge-1 ↦ `merge1` - Harkema Merge-2 (δ ≠ ε) ↦ `merge3` with a lexical selector - Harkema Merge-3 ↦ `merge2` - Harkema Merge-4 (δ ≠ ε) ↦ `merge3` with a derived selector - Harkema Move-1 ↦ `move1` - Harkema Move-2 (δ ≠ ε) ↦ `move2` - - with Harkema's side condition on Move ("if `γⱼ` is one of the other chains, - then the first feature of `γⱼ` is not `-f`") rendered as - `∀ c ∈ ms1 ++ ms2, c.headLic ≠ some f`. - - Three minor differences from Stabler & Keenan remain. They index all four - kinds of feature by a single set `base`, whereas `MG` keeps category names - (`Base`) and licensing features (`Lic`) in separate types, as in Stabler - (1997); their grammars are the special case `Base = Lic`. Their lexical items - may have an empty feature string, which `MG.lex_nonempty` excludes, and their - merge/move rules require the remaining feature string `γ` of the head chain - to be non-empty (`γ ∈ F⁺`), whereas `DerivesSK` permits `γ = []`; in both - cases, an empty head-chain feature string matches the premise of no rule and - is not a complete expression, so the generated language is unaffected. - - We prove: - - • `MG.derives_iff_SK_and_smc`: - `Derives G e ↔ DerivesSK G e ∧ SMC e.movers` - i.e. `Derives` derives exactly the Stabler–Keenan expressions whose - movers satisfy the SMC invariant. - • `MG.langSK_iff_lang`: both presentations generate the same string language. - • `michaelis_harkema_equivalence_SK`: the main `L(MG) = L(MCFG)` theorem, - restated for the literal Stabler–Keenan definition. +# Stabler–Keenan rules and the invariant-carrying presentation + +`DerivesSK` is a chain-based presentation of the merge and move rules in Stabler +and Keenan, *Structural similarity within and among languages* (2003), §2. +It keeps category names and licensing features in separate types and uses +the nonempty feature lists specified by `MG.lex_nonempty` for lexical items. + +`merge` may introduce movers with any nonempty remaining feature sequence. +`move` applies when no other chain starts with the requested licensee. The +head's feature sequence may be empty after removing the selected feature. +The invariant-carrying `MG.Derives` additionally requires movers to start +with a licensee and imposes the shortest-move constraint on all derived +expressions. The two presentations yield the same complete strings. + +Harkema’s *A Recognizer for Minimalist Grammars* (2000), §3.2.2, splits +`merge3` into lexical- and derived-selector cases. His other merge and move +cases correspond to `merge1`, `merge2`, `move1`, and `move2` here. + +The language-equivalence result following the rule comparison concerns the +chain-based grammar in this file. See Stabler and Keenan (2003), §2.3, +for weak generative capacity. -/ @[expose] public section @@ -68,8 +40,7 @@ namespace MG variable {Base Lic T : Type} -/-- Derivable expressions of a Minimalist Grammar, following Stabler & Keenan (2003) - literally: `merge` has no SMC condition and admits any non-empty remaining +/-- Derivable expressions of a Minimalist Grammar, based on Stabler and Keenan (2003): `merge` has no SMC condition and admits any non-empty remaining feature string `δ` on the selected phrase; `move` applies only when no *other* mover has `-f` as its first feature (the Shortest Move Constraint). -/ inductive DerivesSK (G : MG Base Lic T) : MGExpr Base Lic T → Prop where @@ -200,7 +171,7 @@ theorem smc_insert {ms1 ms2 : List (MGChain Base Lic T)} {c : MGChain Base Lic T /-! ### The two presentations coincide -/ /-- Every expression derivable in the invariant-carrying presentation is derivable - under the literal Stabler–Keenan rules. -/ + under the `DerivesSK` rules. -/ theorem Derives.toSK {G : MG Base Lic T} {e : MGExpr Base Lic T} (h : Derives G e) : DerivesSK G e := by induction h with @@ -256,7 +227,7 @@ theorem langSK_iff_lang (G : MG Base Lic T) (w : List T) : end MG -/-! ### Main theorem for the literal Stabler–Keenan definition -/ +/-! ### Main theorem for the Stabler–Keenan presentation -/ /-- Language class of finite Minimalist Grammars under the literal Stabler–Keenan (2003) definition. -/ diff --git a/LeanPool/FormalLinguistics/MGtoMCFG.lean b/LeanPool/FormalLinguistics/MGtoMCFG.lean index 061cf6f9d4..89b2f5a705 100644 --- a/LeanPool/FormalLinguistics/MGtoMCFG.lean +++ b/LeanPool/FormalLinguistics/MGtoMCFG.lean @@ -8,12 +8,16 @@ module public import LeanPool.FormalLinguistics.MCFG public import LeanPool.FormalLinguistics.MG -public import LeanPool.FormalLinguistics.CNF +public import LeanPool.FormalLinguistics.Fixpoint /-! - Direction 1 of Michaelis (1998, 2001) & Harkema (2001): - Every Minimalist Grammar (Stabler & Keenan 2003) has a weakly equivalent - Linear Non-Erasing Multiple Context-Free Grammar (MCFG / LCFRS). +# Translating minimalist grammars to linear context-free rewriting systems + +Michaelis, *Derivational Minimalism Is Mildly Context–Sensitive* (LACL 1998, +doi:10.1007/3-540-45738-0_11), proves the forward language inclusion. +The construction here adapts it to the chain-based presentation used in this +development. The connection to Stabler and Keenan (2003), §2.3, is formalized in +`MGOriginal.lean`. Key idea (after Michaelis 1998, Sect. 4, who fixes an enumeration of the licensees and indexes the components of each nonterminal by it): @@ -3188,8 +3192,8 @@ theorem mgToMCFG_complete [DecidableEq Base] [DecidableEq Lic] | @move2 s t f f' γ δ' ms1 ms2 h1 hsmcNew ih1 => exact mgToMCFG_move2_complete h1 hsmcNew ih1 -/-- **Michaelis Theorem (1998, 2001) — Direction 1 (`MG → MCFG`)**: - Every Minimalist Grammar has a weakly equivalent Linear Non-Erasing MCFG (LCFRS). -/ +/-- Michaelis’s forward construction (LACL 1998), adapted to the chain-based presentation. +The constructed linear non-erasing MCFG generates the same strings as the input grammar. -/ theorem mgToMCFG_lang [DecidableEq Base] [DecidableEq Lic] (G : MG Base Lic T) (w : List T) : (mgToMCFG G).Lang w ↔ G.Lang w := by diff --git a/LeanPool/FormalLinguistics/MathlibBridge.lean b/LeanPool/FormalLinguistics/MathlibBridge.lean index 9019756c6c..527d3bf997 100644 --- a/LeanPool/FormalLinguistics/MathlibBridge.lean +++ b/LeanPool/FormalLinguistics/MathlibBridge.lean @@ -13,8 +13,8 @@ public import Mathlib.Computability.ContextFreeGrammar # Context-free languages in Mathlib The list of productions used by the grammar transformations has the same language semantics as -Mathlib's finite set of productions. The equivalences for basic categorial grammars and Lambek -grammars can therefore be used with `Language.IsContextFree`. +Mathlib's finite set of productions. The equivalences for basic categorial grammars and +product Lambek grammars with a primitive goal can be used with `Language.IsContextFree`. -/ @[expose] public section @@ -145,7 +145,8 @@ theorem bar_hillel_gaifman_shamir_isContextFree {T : Type} (L : Language T) : classical exact (bar_hillel_gaifman_shamir (· ∈ L)).trans ((contextFree_iff L).and Iff.rfl) -/-- Product Lambek grammars recognize precisely the epsilon-free context-free languages. -/ +/-- Product Lambek grammars with a primitive goal recognize precisely the epsilon-free +context-free languages. -/ theorem chomsky_pentus_isContextFree {T : Type} (L : Language T) : IsLambekLang (· ∈ L) ↔ L.IsContextFree ∧ [] ∉ L := by classical diff --git a/LeanPool/projects/formal-grammar-equivalences.yaml b/LeanPool/projects/formal-grammar-equivalences.yaml index fedd71f281..2248d37b86 100644 --- a/LeanPool/projects/formal-grammar-equivalences.yaml +++ b/LeanPool/projects/formal-grammar-equivalences.yaml @@ -30,11 +30,14 @@ main_results: informal: Over a terminal type with decidable equality, the languages of product Lambek grammars with a distinguished primitive type are exactly the context-free languages that exclude the empty word. - source_ref: Pentus (1993), Lambek grammars are context free, via Kanazawa (2018), Sections 3–4, arXiv:1709.07695. + source_ref: Pentus (1993), Theorem 2 specialized to a primitive goal, + via Kanazawa (2018), Sections 3–4, arXiv:1709.07695. - declaration: FormalLinguistics.michaelis_harkema_equivalence_SK informal: The languages of the formalized Stabler–Keenan minimalist grammars are exactly those generated by linear non-erasing multiple context-free grammars. - source_ref: Michaelis, DOI 10.1007/3-540-48199-0_14, and Harkema, DOI 10.1007/3-540-48199-0_12. + source_ref: Stabler and Keenan (2003), Section 2.3, for the chain-based + presentation. Forward direction Michaelis (LACL 1998), DOI 10.1007/3-540-45738-0_11. + Converse Michaelis, DOI 10.1007/3-540-48199-0_14, and Harkema, DOI 10.1007/3-540-48199-0_12. tags: - formal-languages - categorial-grammars From 4435287d1d97417e83e6ae1b54c3949c08f8a9cd Mon Sep 17 00:00:00 2001 From: Vasily Ilin Date: Sat, 28 Nov 2026 12:45:29 +0000 Subject: [PATCH 3/3] Clarify grammar sources and share normal-form computations --- LeanPool/FormalLinguistics/CNF.lean | 30 +++++++++++-------- LeanPool/FormalLinguistics/LambekPentus.lean | 9 +++++- LeanPool/FormalLinguistics/MG.lean | 7 +++-- LeanPool/FormalLinguistics/MGOriginal.lean | 29 +++++++++--------- .../projects/formal-grammar-equivalences.yaml | 17 +++++++---- 5 files changed, 57 insertions(+), 35 deletions(-) diff --git a/LeanPool/FormalLinguistics/CNF.lean b/LeanPool/FormalLinguistics/CNF.lean index 2952a38073..a37532c115 100644 --- a/LeanPool/FormalLinguistics/CNF.lean +++ b/LeanPool/FormalLinguistics/CNF.lean @@ -420,7 +420,8 @@ def nullPred (G : BinCFG N T) (s : List N) (A : N) : Bool := /-- Compute the nullability fixed point by bounded iteration over the finite symbol list. -/ def nullableList (G : BinCFG N T) : List N := - iterN (stepFilter (allNTs G) (nullPred G)) (allNTs G).length [] + let nonterminals := allNTs G + iterN (stepFilter nonterminals (nullPred G)) nonterminals.length [] theorem nullPred_mono (G : BinCFG N T) : ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, nullPred G s1 x = true → nullPred G s2 x = true := by @@ -497,16 +498,17 @@ theorem nullableList_complete {G : BinCFG N T} {A : N} (h : BinCFG.Yield G A []) exact ⟨(X, Y, Z), hb, ⟨rfl, hY⟩, hZ⟩ /-- Remove empty productions, adding unary rules when a binary child can disappear. -/ -def toNoEps (G : BinCFG N T) : NoEpsCFG N T where - start := G.start - termRules := G.termRules - unitRules := - G.unitRules ++ - (G.binRules.filterMap fun (A, B, C) => - if B ∈ nullableList G then some (A, C) else none) ++ - (G.binRules.filterMap fun (A, B, C) => - if C ∈ nullableList G then some (A, B) else none) - binRules := G.binRules +def toNoEps (G : BinCFG N T) : NoEpsCFG N T := + let nullable := nullableList G + { start := G.start + termRules := G.termRules + unitRules := + G.unitRules ++ + (G.binRules.filterMap fun (A, B, C) => + if B ∈ nullable then some (A, C) else none) ++ + (G.binRules.filterMap fun (A, B, C) => + if C ∈ nullable then some (A, B) else none) + binRules := G.binRules } theorem toNoEps_sound {G : BinCFG N T} {A : N} {w : List T} (h : NoEpsCFG.Yield (toNoEps G) A w) : BinCFG.Yield G A w ∧ w ≠ [] := by @@ -616,7 +618,8 @@ def allNTs (G : NoEpsCFG N T) : List N := /-- Enumerate ordered pairs of nonterminals that can participate in a unary path. -/ def allPairs (G : NoEpsCFG N T) : List (N × N) := - dedupList ((allNTs G).flatMap fun A => (allNTs G).map fun B => (A, B)) + let nonterminals := allNTs G + dedupList (nonterminals.flatMap fun A => nonterminals.map fun B => (A, B)) /-- Test whether a pair is reflexive, a direct unary rule, or reachable by extending a known path. -/ @@ -627,7 +630,8 @@ def unitPred (G : NoEpsCFG N T) (s : List (N × N)) (p : N × N) : Bool := /-- Compute all unary paths by bounded finite fixed-point iteration. -/ def unitReach (G : NoEpsCFG N T) : List (N × N) := - iterN (stepFilter (allPairs G) (unitPred G)) (allPairs G).length [] + let pairs := allPairs G + iterN (stepFilter pairs (unitPred G)) pairs.length [] theorem unitPred_mono (G : NoEpsCFG N T) : ∀ s1 s2, (∀ x, x ∈ s1 → x ∈ s2) → ∀ x, unitPred G s1 x = true → unitPred G s2 x = true := by diff --git a/LeanPool/FormalLinguistics/LambekPentus.lean b/LeanPool/FormalLinguistics/LambekPentus.lean index 2f29cf9c31..ea57d7b263 100644 --- a/LeanPool/FormalLinguistics/LambekPentus.lean +++ b/LeanPool/FormalLinguistics/LambekPentus.lean @@ -20,6 +20,11 @@ public import LeanPool.FormalLinguistics.LambekThin free groups give a "binary reduction" of every derivable sequent whose types have bounded size; the context-free grammar has the types of bounded size as nonterminals and the derivable sequents with at most two antecedent types as rules. + + For the converse, the formalization first obtains a basic categorial grammar + via the Greibach construction for Bar-Hillel, Gaifman and Shamir's theorem. + It then embeds that grammar in the Lambek calculus, the direction established + by Cohen (1967). -/ @[expose] public section @@ -544,7 +549,9 @@ def IsLambekLang {T : Type} (L : List T → Prop) : Prop := ∃ (P : Type) (G : LambekGrammar P T), ∀ w, G.Lang w ↔ L w /-- A language is generated by a product Lambek grammar with a primitive goal if and only if -it is an ε-free context-free language. -/ +it is an ε-free context-free language. The Lambek-to-CFG direction uses the primitive-goal +case of Pentus (1993), Theorem 2. The CFG-to-Lambek direction uses the Greibach-derived +basic categorial lexicon and its embedding into the Lambek calculus, as in Cohen (1967). -/ theorem chomsky_pentus {T : Type} [DecidableEq T] (L : List T → Prop) : IsLambekLang L ↔ ((∃ (N : Type) (_ : DecidableEq N) (G : CFG N T), ∀ w, G.Lang w ↔ L w) ∧ ¬ L []) := by diff --git a/LeanPool/FormalLinguistics/MG.lean b/LeanPool/FormalLinguistics/MG.lean index 0f6511c985..95724637a4 100644 --- a/LeanPool/FormalLinguistics/MG.lean +++ b/LeanPool/FormalLinguistics/MG.lean @@ -17,8 +17,10 @@ public import Init • Structure-building operations: `lex`, `merge1`, `merge2`, `merge3`, `move1`, `move2`. The SMC is built into the rules as an invariant of every derived expression. - Stabler & Keenan impose it on `move` only; `MGOriginal.lean` states their rules - literally and proves that both presentations generate the same languages. + Stabler and Keenan (2003, §2, Definition 1) impose it on `move` only. + The formalized variant uses nonempty lexical feature lists and a distinguished + basic category as its goal. `MGOriginal.lean` presents the rules without + the extra invariant on `merge` and proves language equivalence for this variant. -/ @[expose] public section @@ -74,6 +76,7 @@ structure MG (Base Lic T : Type) where start : Base /-- Finite list of lexical strings paired with nonempty feature sequences. -/ lexicon : List (List T × List (MGFeature Base Lic)) + /-- The formalized variant requires each lexical entry to have at least one feature. -/ lex_nonempty : ∀ entry, entry ∈ lexicon → entry.2 ≠ [] namespace MG diff --git a/LeanPool/FormalLinguistics/MGOriginal.lean b/LeanPool/FormalLinguistics/MGOriginal.lean index 6fe464cf24..e516a89549 100644 --- a/LeanPool/FormalLinguistics/MGOriginal.lean +++ b/LeanPool/FormalLinguistics/MGOriginal.lean @@ -12,9 +12,11 @@ public import LeanPool.FormalLinguistics.MGMCFGEquiv # Stabler–Keenan rules and the invariant-carrying presentation `DerivesSK` is a chain-based presentation of the merge and move rules in Stabler -and Keenan, *Structural similarity within and among languages* (2003), §2. -It keeps category names and licensing features in separate types and uses -the nonempty feature lists specified by `MG.lex_nonempty` for lexical items. +and Keenan, *Structural similarity within and among languages* (2003), §2, Definition 1. +This variant uses separate types for basic categories and movement features. +It requires nonempty lexical feature lists and a distinguished basic category +as its goal. Definition 1 allows empty lexical feature lists and an arbitrary +distinguished feature. `merge` may introduce movers with any nonempty remaining feature sequence. `move` applies when no other chain starts with the requested licensee. The @@ -40,9 +42,9 @@ namespace MG variable {Base Lic T : Type} -/-- Derivable expressions of a Minimalist Grammar, based on Stabler and Keenan (2003): `merge` has no SMC condition and admits any non-empty remaining - feature string `δ` on the selected phrase; `move` applies only when no *other* - mover has `-f` as its first feature (the Shortest Move Constraint). -/ +/-- Derivability for the formalized variant of Stabler and Keenan (2003, §2, Definition 1). + The third merge rule admits any nonempty remainder on the selected phrase. Movement + requires that no other mover start with the requested licensee feature. -/ inductive DerivesSK (G : MG Base Lic T) : MGExpr Base Lic T → Prop where /-- Lexical insertion. -/ | lex {w : List T} {α : List (MGFeature Base Lic)} : @@ -92,8 +94,8 @@ inductive DerivesSK (G : MG Base Lic T) : MGExpr Base Lic T → Prop where (∀ c, c ∈ ms1 ++ ms2 → c.headLic ≠ some f) → DerivesSK G ⟨false, ⟨s, γ⟩, ms1 ++ ⟨t, δ⟩ :: ms2⟩ -/-- The string language of a Minimalist Grammar under the literal - Stabler–Keenan definition. -/ +/-- Strings derived using the Stabler–Keenan rules in this variant, with the + distinguished basic category as the sole remaining feature and no pending movers. -/ def LangSK (G : MG Base Lic T) (w : List T) : Prop := ∃ b, DerivesSK G ⟨b, ⟨w, [MGFeature.cat G.start]⟩, []⟩ @@ -229,8 +231,8 @@ end MG /-! ### Main theorem for the Stabler–Keenan presentation -/ -/-- Language class of finite Minimalist Grammars under the literal - Stabler–Keenan (2003) definition. -/ +/-- Languages of finite Stabler–Keenan grammars with nonempty lexical feature + lists and a distinguished basic category as the goal. -/ def IsMGLangSK {T : Type} (L : List T → Prop) : Prop := ∃ (Base Lic : Type) (G : MG Base Lic T), ∀ w, G.LangSK w ↔ L w @@ -242,10 +244,9 @@ theorem isMGLangSK_iff_isMGLang {T : Type} (L : List T → Prop) : · rintro ⟨Base, Lic, G, hG⟩ exact ⟨Base, Lic, G, fun w => by rw [MG.langSK_iff_lang, hG]⟩ -/-- **Michaelis–Harkema Equivalence Theorem for Stabler–Keenan Minimalist Grammars**: - a language is generated by a finite Minimalist Grammar, in the literal sense of - Stabler & Keenan (2003), iff it is generated by a finite linear non-erasing - MCFG (LCFRS). -/ +/-- A language is generated by a finite linear non-erasing MCFG if and only if it + is generated by a finite Stabler–Keenan grammar in the formalized variant + with nonempty lexical feature lists and a distinguished basic goal category. -/ theorem michaelis_harkema_equivalence_SK {T : Type} (L : List T → Prop) : IsMGLangSK L ↔ IsMCFGLang L := by rw [isMGLangSK_iff_isMGLang, michaelis_harkema_equivalence] diff --git a/LeanPool/projects/formal-grammar-equivalences.yaml b/LeanPool/projects/formal-grammar-equivalences.yaml index 2248d37b86..7708dc391c 100644 --- a/LeanPool/projects/formal-grammar-equivalences.yaml +++ b/LeanPool/projects/formal-grammar-equivalences.yaml @@ -30,13 +30,20 @@ main_results: informal: Over a terminal type with decidable equality, the languages of product Lambek grammars with a distinguished primitive type are exactly the context-free languages that exclude the empty word. - source_ref: Pentus (1993), Theorem 2 specialized to a primitive goal, + source_ref: > + Lambek to CFG is Pentus (1993), Theorem 2 specialized to a primitive goal, via Kanazawa (2018), Sections 3–4, arXiv:1709.07695. + The converse uses the Greibach-derived basic categorial lexicon of the + Bar-Hillel–Gaifman–Shamir equivalence and its embedding into Lambek + grammars, the direction credited to Cohen (1967) in Pentus's introduction. - declaration: FormalLinguistics.michaelis_harkema_equivalence_SK - informal: The languages of the formalized Stabler–Keenan minimalist grammars - are exactly those generated by linear non-erasing multiple context-free grammars. - source_ref: Stabler and Keenan (2003), Section 2.3, for the chain-based - presentation. Forward direction Michaelis (LACL 1998), DOI 10.1007/3-540-45738-0_11. + informal: The languages of Stabler–Keenan minimalist grammars with nonempty + lexical feature lists and a distinguished basic goal category are exactly + those generated by linear non-erasing multiple context-free grammars. + source_ref: > + Stabler and Keenan (2003), Section 2, Definition 1 for the chain rules, + and Section 2.3 for weak generative capacity. + Forward direction Michaelis (LACL 1998), DOI 10.1007/3-540-45738-0_11. Converse Michaelis, DOI 10.1007/3-540-48199-0_14, and Harkema, DOI 10.1007/3-540-48199-0_12. tags: - formal-languages