Theory Path_Indexing

theory Path_Indexing
  imports
    Linear_Unification
    Update_Map_Entries
begin

section ‹Path indexing›

datatype (plugins del: size) ('f,'v) trie =
  Leaf ‹('f,'v) term set›
| SymbolNode (children: ‹('f symbol, (nat, ('f, 'v) trie) fmap) fmap›)
  where
    ‹children (Leaf ts) = fmempty›

abbreviation empty_trie :: ‹('f, 'v) trie›
  where ‹empty_trie ≡ SymbolNode fmempty›

function (domintros) trie_depth :: ‹('f,'v) trie ⇒ nat› where
  ‹trie_depth (Leaf ts) = 1›
| ‹trie_depth (SymbolNode m) = Suc (Max (trie_depth ` ⋃ (fmran' ` (fmran' m))))›
  by pat_completeness auto
termination
proof (intro allI)
  fix x :: ‹('f ,'v) trie›
  show ‹trie_depth_dom x›
  proof (induction x)
    case (Leaf ts)
    then show ?case using trie_depth.domintros(1) by blast
  next
    case (SymbolNode m)
    then show ?case using trie_depth.domintros(2) by blast
  qed
qed

instantiation trie :: (type, type) size
begin
definition size_trie where
  size_trie_overloaded_def: ‹size_trie = Path_Indexing.trie_depth›
instance ..
end

lemma subtrie_size_lt [simp]: ‹m2 ∈ fmran' m1 ⟹ tr ∈ fmran' m2 ⟹ size tr < size (SymbolNode m1)›
proof -
  assume ‹m2 ∈ fmran' m1› and ‹tr ∈ fmran' m2›
  then have t_elem: ‹tr ∈ ⋃ (fmran' ` fmran' m1)› by auto
  then show ?thesis unfolding size_trie_overloaded_def using t_elem
    by (simp add: le_imp_less_Suc fmran'_alt_def)
qed

lemma subtrie_size_lt_alt [simp]: ‹m1 $$ s = Some m2 ⟹ i ∈ fmdom' m2 ⟹ size (m2 $$! i) < size (SymbolNode m1)›
  by (metis fmdom'_notI fmran'I option.collapse subtrie_size_lt)

text ‹The collection of all terms in the leaves of the trie.›

fun to_set :: ‹('f,'v) trie ⇒ ('f,'v) term set› where
  ‹to_set (Leaf ts) = ts›
| ‹to_set (SymbolNode m) = ⋃ (to_set ` ⋃ (fmran' ` (fmran' m)))›

lemma entry_to_set: ‹m1 $$ s = Some m2 ⟹
                     m2 $$ i = Some tr ⟹
                     t ∈ to_set tr ⟹
                     t ∈ to_set (SymbolNode m1)›
  by (metis (no_types, opaque_lifting) UN_I fmran'I to_set.simps(2))

lemma to_set_exists_entry: ‹t ∈ to_set (SymbolNode m) ⟹
                            (∃s i m2 tr. m $$ s = Some m2 ∧ m2 $$ i = Some tr ∧ t ∈ to_set tr)› by fastforce

subsection ‹Preliminaries: paths and subtries›

type_synonym 'f tpath = ‹('f symbol × nat) list›

inductive subtrie_at_path :: ‹('f,'v) trie ⇒ 'f tpath ⇒ ('f,'v) trie ⇒ bool› where
  subtrie_at_path_empty: ‹subtrie_at_path tr [] tr›
| subtrie_at_path_step: ‹m1 $$ s = Some m2 ⟹ m2 $$ i = Some tr1 ⟹ subtrie_at_path tr1 ps tr2 ⟹ subtrie_at_path (SymbolNode m1) ((s, i) # ps) tr2›

lemma subtrie_inj:
  assumes ‹subtrie_at_path tr1 p tr2›
      and ‹subtrie_at_path tr1 p tr3›
    shows ‹tr2 = tr3›
  using assms by (induct rule: subtrie_at_path.induct) (auto elim: subtrie_at_path.cases)

lemma fmran_empty' [simp]: ‹fmran' {$$} = {}›
  by (simp add: fmran'_alt_def)

lemma subtrie_at_nil [simp]: ‹¬ subtrie_at_path (SymbolNode m) [] (Leaf ts)›
  using subtrie_at_path_empty subtrie_inj by blast

lemma subtrie_cons: ‹subtrie_at_path (SymbolNode m) ((s, i) # p) (Leaf ts) ⟹ ∃a m2. m $$ s = Some a ∧ a $$ i = Some m2 ∧ subtrie_at_path m2 p (Leaf ts)›
  using subtrie_at_path.cases by fastforce

lemma subtrie_to_set:
  assumes ‹subtrie_at_path tr p (Leaf (insert t ts))›
    shows ‹t ∈ to_set tr›
  using assms
proof (induction tr arbitrary: p)
  case (Leaf ts)
  then show ?case
    using subtrie_at_path.cases by auto 
next
  case (SymbolNode m)
  then show ?case 
  proof (cases p)
    case Nil
    then show ?thesis
      using SymbolNode.prems subtrie_at_path_empty subtrie_inj by blast 
  next
    case (Cons a ps)    
    obtain s i where ‹a = (s, i)›
      by (metis prod.exhaust)
    then obtain m2 tr2 where h1: ‹m $$ s = Some m2›
                         and h2: ‹m2 $$ i = Some tr2›
                         and h3: ‹subtrie_at_path tr2 ps (Leaf (insert t ts))›
      using SymbolNode Cons subtrie_cons by blast
    then have ‹t ∈ to_set tr2›
      by (meson SymbolNode.IH fmran'I)
    then show ?thesis
      using h1 h2  by (metis (no_types, lifting) UN_I fmran'I to_set.simps(2))
  qed
qed

lemma elim_sub:
  assumes ‹subtrie_at_path (SymbolNode m) ((s, i) # p) (Leaf (insert t ts))›
      and ‹m $$ s = Some m2›
      and ‹m2 $$ i = Some tr› 
    shows ‹subtrie_at_path tr p (Leaf (insert t ts))› 
  using assms subtrie_at_path.cases by fastforce

lemma subtrie_entry_to_set: ‹subtrie_at_path (SymbolNode m1) ((s, i) # p) (Leaf (insert t ts)) ⟹
    m1 $$ s = Some m2 ⟹ m2 $$ i = Some tr ⟹ t ∈ to_set tr›
  by (meson elim_sub subtrie_to_set)

inductive_cases subtrie_at_path_cases: ‹subtrie_at_path tr1 p tr2›
declare subtrie_at_path_cases [elim!]

lemma subtrie_string_1:
  assumes ‹subtrie_at_path (SymbolNode {s $$:= {i $$:= Leaf ts1}}) [(s, i)] (Leaf ts2)›
    shows ‹ts1 = ts2›
  using assms subtrie_at_path.cases subtrie_cons
  by force

lemma subtrie_string_2:
  assumes ‹subtrie_at_path (SymbolNode {s $$:= m}) ((s2, i) # p) (Leaf ts)›
    shows ‹s2 = s›
  using assms
  by (metis fmempty_lookup fmupd_lookup option.distinct(1) subtrie_cons)

lemma subtrie_string_3: 
  assumes ‹subtrie_at_path (SymbolNode {s $$:= m}) ((s2, i) # p) (Leaf ts)›
    shows ‹i ∈ fmdom' m›
  using assms
  by (metis fmdom'I fmupd_lookup option.sel subtrie_cons subtrie_string_2)

lemma subtrie_string_4:
  assumes ‹subtrie_at_path (SymbolNode {s $$:= {i $$:= Leaf ts1}}) ps (Leaf ts2)›
    shows ‹ps = [(s, i)]›
proof (cases ps)
  case Nil
  then show ?thesis
    using assms by blast
next
  case (Cons p ps2)
  then obtain s1 j where h1: ‹p = (s1, j)› by (cases p, blast)
  then show ?thesis
  proof -
    have ‹ps2 = []›
      using assms Cons h1    
      by (metis fmempty_lookup fmran'I fmran_empty' singletonD subtrie_cons subtrie_at_path_cases trie.distinct(1) update_entry_ran)
    moreover have t1: ‹s1 = s› 
      by (metis assms h1 local.Cons subtrie_string_2) 
    moreover have ‹j = i› 
      by (metis fmempty_lookup fmupd_lookup assms h1 local.Cons option.distinct(1) option.sel subtrie_cons)
    ultimately show ?thesis
      using h1 local.Cons by force
  qed
qed

lemma subtrie_at_path_fmdrop_subset [simp]:
  ‹subtrie_at_path (SymbolNode (fmdrop k m)) (p # ps) tr ⟹ subtrie_at_path (SymbolNode m) (p # ps) tr›
proof -
  assume h: ‹subtrie_at_path (SymbolNode (fmdrop k m)) (p # ps) tr›
  show ?thesis
  proof (cases ‹m $$ k›)
    case None
    then show ?thesis
      using h by (metis fmdom'_notI fmdrop_idle')
  next
    case (Some v)
    then obtain s m2 i tr1 where ‹p = (s, i)
                                ∧ fmdrop k m $$ s = Some m2
                                ∧ m2 $$ i = Some tr1
                                ∧ subtrie_at_path tr1 ps tr›
      using h subtrie_at_path.simps [of ‹SymbolNode (fmdrop k m)› ‹p # ps› tr]
      by (metis list.distinct(1) list.inject trie.inject(2))
    then show ?thesis
      using fmlookup_drop [of k m s]
      by (metis option.distinct(1) subtrie_at_path_step)
  qed
qed

inductive path_of_term :: ‹('f,'v) term ⇒'f tpath ⇒ bool› where
  path_of_term_var: ‹path_of_term (Var x) [(Star, 0)]›
| path_of_term_const: ‹path_of_term (Fun f []) [(F f 0, 0)]›
| path_of_term_func: ‹f_args ≠ [] ⟹ i < length f_args ⟹ path_of_term (f_args ! i) p ⟹ path_of_term (Fun f f_args) ((F f (length f_args), i) # p)›

lemma path_of_term_nil [simp]: ‹¬ path_of_term t []›
  using path_of_term.cases by blast

lemma last_path_term:
  assumes ‹path_of_term t p›
    shows ‹last p = (Star, 0) ∨ (∃f. last p = (F f 0, 0))›
  using assms by (induct rule: path_of_term.induct) (auto intro: path_of_term.cases)

lemma path_var: ‹path_of_term (Var x) p ⟷ p = [(Star, 0)]›
  using path_of_term.simps path_of_term_var by fast

lemma path_const: ‹path_of_term (Fun f []) p ⟷ p = [(F f 0, 0)]›
  using path_of_term.simps [of ‹Fun f []›] path_of_term_const by auto

lemma path_func: 
  assumes ‹path_of_term (Fun f (a # f_args)) ps›
  shows ‹∃i ps1. ps = (F f (length (a # f_args)), i) # ps1 ∧
    i < length (a # f_args) ∧ path_of_term ((a # f_args) ! i) ps1›
  using assms path_of_term.simps [of ‹Fun f (a # f_args)› ps] by blast

lemma path_of_term_element:
  ‹n ≠ 0 ⟹ path_of_term t (ps1 @ (F f n, i) # ps2) ⟹ i < n ∧ ps2 ≠ []›
proof (induction ps1 arbitrary: t f n i)
  case Nil
  then show ?case using path_of_term.simps [of t] by force
next
  case (Cons p ps1')
  then obtain t2 :: ‹('a, 'b) term› where ‹path_of_term t2 (ps1' @ (F f n, i) # ps2)›
    using path_of_term.simps [of t ‹(p # ps1') @ (F f n, i) # ps2›] by auto
  then show ?case
    using Cons.IH Cons.prems(1) by presburger
qed

inductive subterm_at_path :: ‹('f,'v) term ⇒'f tpath ⇒ ('f,'v) term ⇒ bool› where
  subterm_at_path_empty: ‹subterm_at_path t [] t›
| subterm_at_path_step:  ‹i < length f_args ⟹ f_args ≠ [] ⟹ subterm_at_path (f_args ! i) ps t ⟹ subterm_at_path (Fun f f_args) ((F f (length f_args), i) # ps) t›

lemma subterm_inj: 
  assumes ‹subterm_at_path tr p t1›
      and ‹subterm_at_path tr p t2›
    shows ‹t1 = t2› 
  using assms by (induction rule: subterm_at_path.induct) (auto elim: subterm_at_path.cases)

lemma subterm_at_path_path_of_term:
  assumes ‹subterm_at_path t p t2› 
      and ‹path_of_term t2 p2›
    shows ‹path_of_term t (p @ p2)› 
  using assms by (induction rule: subterm_at_path.induct) (auto intro: path_of_term_func)

lemma path_of_subterm: 
  assumes ‹subterm_at_path t p t2›
      and ‹path_of_term t (p @ p2)›
    shows ‹path_of_term t2 p2› 
  using assms by (induction rule: subterm_at_path.induct) (auto intro: path_of_term.cases)

lemma var_is_subterm_at_last: 
  assumes ‹path_of_term t (p @ [(Star, 0)])›
  obtains x where ‹subterm_at_path t p (Var x)›
  using assms
proof (induct t arbitrary: p)
  case (Var x)
  then have h0: ‹p = []›
    by (simp add: path_var)
  then have ‹subterm_at_path (Var x) [] (Var x)›
    by (simp add: subterm_at_path_empty) 
  then show ?case
    using Var.prems(1) h0 by blast
next
  case (Fun f f_args)
  then show ?case
  proof (cases f_args)
    case Nil
    then have ‹¬path_of_term (Fun f []) (p @ [(Star, 0)])›
      by (simp add: path_const)
    then show ?thesis
      using Fun.prems local.Nil by blast
  next
    case c1: (Cons t ts)
    then show ?thesis
    proof (cases p)
      case Nil
      then have ‹path_of_term (Fun f (t # ts)) [(Star, 0)]›
        using Fun c1 by force
      then show ?thesis
        using path_func by fastforce
    next
      case c2: (Cons c cl)
      then have h1 : ‹path_of_term (Fun f (t # ts)) (c # cl @ [(Star, 0)])›
        using Fun.prems c1 by auto
      then show ?thesis using c1 c2 subterm_at_path_step path_func Fun.hyps  
        by (smt (verit) Fun.prems(1) list.distinct(1) list.sel(1) list.sel(3) nth_mem path_of_term.simps term.sel(4))
    qed
  qed
qed

lemma end_path_const:
  assumes ‹path_of_term t (p @ (F f 0, i) # q)›
    shows ‹i = 0 ∧ q = []›
  using assms
proof (induct p arbitrary: t )
  case Nil
  then show ?case 
    using Pair_inject path_of_term.cases by force
next
  case (Cons _ _)
  then show ?case 
    by (smt (verit, del_insts) Nil_is_append_conv append_Cons list.distinct(1) list.inject path_of_term.simps)
qed

lemma end_path_var:
  assumes ‹path_of_term t (p @ (Star, i) # q)›
    shows ‹i = 0 ∧ q = []›
  using assms proof (induct p arbitrary: t )
  case Nil
  then show ?case 
    using Pair_inject path_of_term.cases by force
next
  case (Cons _ _)
  then show ?case 
    by (smt (verit, del_insts) Nil_is_append_conv append_Cons list.distinct(1) list.inject path_of_term.simps)
qed

lemma fun_is_subterm_at_last:
  assumes ‹path_of_term t (p1 @ (F f n, i) # p2)›
    shows ‹∃f_args. subterm_at_path t p1 (Fun f f_args) ∧ n = length f_args› 
  using assms
proof (induction p1 arbitrary: t)
  case Nil
  then show ?case 
    by (smt (verit) Pair_inject list.size(3) nth_Cons_0 path_of_term.cases self_append_conv2 subterm_at_path_empty symbol.distinct(1) symbol.inject) 
next
  case (Cons _ _)
  then show ?case 
    by (smt (verit, ccfv_SIG) Nil_is_append_conv append_Cons list.distinct(1) list.inject path_of_term.simps subterm_at_path_step)
qed

lemma sub_path_not_path:
  assumes ‹subterm_at_path t1 p t2›
    shows ‹¬ path_of_term t3 p›
  using assms
proof (induction p arbitrary: t3 t1)
  case Nil
  then show ?case  by simp
next
  case (Cons a ps)
  then show ?case
  proof (cases a)
    case (Pair s i)
    then show ?thesis  
      by (smt (verit, ccfv_SIG) Cons Pair_inject gr_implies_not0 list.distinct(1) list.sel(1,3) path_of_term.simps subterm_at_path.simps symbol.simps(1) symbol.simps(3))  
  qed
qed

lemma exists_path: ‹∃p. path_of_term t p›
proof (induction t)
  case (Var x)
  then show ?case
    using path_of_term_var by force 
next
  case (Fun f f_args)
  then show ?case
    by (metis length_greater_0_conv nth_mem path_of_term_const path_of_term_func) 
qed

lemma subsubterm_at_path: 
  assumes ‹subterm_at_path t p (Fun f f_args)› 
      and ‹i < (length f_args)›
    shows ‹subterm_at_path t (p @ [(F f (length f_args), i)]) (f_args ! i)›
  using assms
proof (induction p arbitrary: t)
  case Nil
  then show ?case
    by (metis append.left_neutral less_zeroE list.size(3) subterm_at_path_empty subterm_at_path_step subterm_inj) 
next
  case (Cons _ _)
  then show ?case 
    by (smt (verit, ccfv_threshold) append_Cons list.distinct(1) list.sel(3) subterm_at_path.simps)
qed

declare subtrie_at_path_cases [rule del]

lemma exists_leaf:
  assumes ‹t ∈ to_set tr›
    shows ‹∃ts p. subtrie_at_path tr p (Leaf (insert t ts))›
  using assms
proof (induct tr)
  case (Leaf ts)
  then show ?case
    by (metis insert_absorb subtrie_at_path_empty to_set.simps(1)) 
next
  case (SymbolNode m) then show ?case 
    by (fastforce  intro: subtrie_at_path_step  )
qed

subsection ‹Invariants›

text ‹The structure of the trie (number and nature of children for each SymbolNode) is consistent with the symbols›

inductive well_structured :: ‹('f, 'v) trie ⇒ bool›
  and well_structured_map_entry :: ‹'f symbol ⇒ (nat, ('f, 'v) trie) fmap ⇒ bool›
  where
    ws_node: ‹(∀s. s ∈ fmdom' m ⟶ well_structured_map_entry s (m $$! s)) ⟹ well_structured (SymbolNode m)›
  | wsme_var: ‹fmdom' m = {0} ⟹ m $$ 0 = Some (Leaf ts) ⟹ well_structured_map_entry Star m›
  | wsme_const: ‹fmdom' m = {0} ⟹ m $$ 0 = Some (Leaf ts) ⟹ well_structured_map_entry (F f 0) m›
  | wsme_func: ‹n ≠ 0 ⟹ fmdom' m = {..<n} ⟹ (∀t. t ∈ fmran' m ⟶ well_structured t) ⟹ well_structured_map_entry (F f n) m›

lemma ws_dom_var: 
  assumes ‹well_structured (SymbolNode m)›
      and ‹m $$ Star = Some m2›
  obtains ts where ‹fmdom' m2 = {0} ∧ m2 $$ 0 = Some (Leaf ts)›
  by (metis assms(1,2) fmdom'I option.sel symbol.distinct(1) trie.sel(3) well_structured.simps well_structured_map_entry.simps)

lemma ws_dom_const: 
  assumes ‹well_structured (SymbolNode m)›
      and ‹m $$ F f 0 = Some m2›
  obtains ts where ‹fmdom' m2 = {0} ∧ m2 $$ 0 = Some (Leaf ts)›
  by (metis assms(1,2) fmdom'I option.sel symbol.inject trie.inject(2) well_structured.simps well_structured_map_entry.simps)

lemma ws_dom_fun: 
  assumes ‹well_structured (SymbolNode m)›
      and ‹m $$ F f n = Some a›
      and ‹i < n›
    shows ‹i ∈ fmdom' a›
proof -
  from assms(1) have h: ‹∀s. s ∈ fmdom' m ⟶ well_structured_map_entry s (m $$! s)›
    using well_structured.cases by auto
  from assms(2) have ‹F f n ∈ fmdom' m›
    by (simp add: fmdom'I)
  then have ‹well_structured_map_entry (F f n) a›
    using assms(2) h by (metis option.sel)
  thus ?thesis
    using assms(3) well_structured_map_entry.cases by fastforce 
qed

lemma ws_dom_fun2: 
  assumes ‹well_structured (SymbolNode m)›
      and ‹m $$ F f (Suc n) = Some a›
      and ‹i ∈ fmdom' a›
    shows ‹i < Suc n›
proof -
  from assms(1) have h: ‹∀s. s ∈ fmdom' m ⟶ well_structured_map_entry s (m $$! s)›
    using well_structured.cases by auto
  from assms(2) have ‹F f (Suc n) ∈ fmdom' m›
    by (simp add: fmdom'I)
  then have ‹well_structured_map_entry (F f (Suc n)) a›
    using assms(2) h by (metis option.sel)
  thus ?thesis
    using assms(3) well_structured_map_entry.cases by auto
qed

lemma ws_subtree:
  assumes ‹well_structured (SymbolNode m)›
      and ‹m $$ F f n = Some m2›
      and ‹m2 $$ i = Some tr›
      and ‹n > 0›
    shows ‹well_structured tr›
proof -
  from assms(1,2) have ‹well_structured_map_entry (F f n) (m $$! (F f n))›
    by (metis well_structured.cases trie.inject(2) fmdom'I)
  then show ?thesis
    by (metis assms(2,3,4) option.sel fmran'I symbol.inject fmlookup_dom'_iff well_structured_map_entry.cases symbol.simps(3) not_less0)
qed

lemma key_map_entry:
  assumes ‹well_structured (SymbolNode m)› 
      and ‹m $$ F f n = Some m2›
      and ‹n ≠ 0›
      and ‹i ∈ fmdom' m2›
    shows ‹i < n›
proof-
  have ‹F f n ∈ fmdom' m›
    by (simp add: assms(2) fmdom'I) 
  then have ‹well_structured_map_entry (F f n) (m $$! (F f n))›
    using assms(1) well_structured.cases by auto
  then have ‹fmdom' m2 = {..<n} ∧ (∀t. t ∈ fmran' m2 ⟶ well_structured t)›
    by (simp add: assms(2) assms(3) well_structured_map_entry.simps)
  then show ?thesis
    using assms(4) by blast
qed

lemma key_map_entry_simp:
  assumes ‹well_structured (SymbolNode m)› 
      and ‹m $$ F f n = Some m2›
      and ‹n ≠ 0›
    shows ‹i ∈ fmdom' m2 ⟷ i < n›
  using assms key_map_entry ws_dom_fun by meson

lemma ws_fmdom': 
  assumes ‹well_structured (SymbolNode m)›
     and ‹m $$ F f (length f_args) = Some m2›
     and ‹f_args ≠ []›
   shows ‹fmdom' m2 = {..<length f_args}›
  using assms
  by (metis fmdom'I length_0_conv option.sel symbol.distinct(1) symbol.inject trie.inject(2) well_structured.cases well_structured_map_entry.cases)

lemma well_structured_drop [simp]:
  ‹well_structured (SymbolNode m) ⟹ well_structured (SymbolNode (fmdrop s m))›
  by (metis Diff_iff fmdom'_drop fmdom'_notI fmlookup_drop trie.sel(3) well_structured.cases ws_node)

lemma well_structured_split:
  ‹well_structured (SymbolNode m) ⟹
   well_structured (SymbolNode {s $$:= m2}) ⟹
   well_structured (SymbolNode (m(s $$:= m2)))›
  by (metis fmdom'_fmupd fmupd_lookup insert_iff trie.sel(3) well_structured.cases ws_node)

text ‹A term is stored in a leaf only if that leaf is located on a path of the term›

definition sound_storage :: ‹('f, 'v) trie ⇒ bool› where
  ‹sound_storage tr = (∀t p s. subtrie_at_path tr p (Leaf (insert t s)) ⟶ path_of_term t p)›

text ‹A term stored in the trie must appear in all the leaves located on paths of that term›

definition complete_storage :: ‹('f, 'v) trie ⇒ bool› where
  ‹complete_storage tr = (∀t∈to_set tr. ∀p. path_of_term t p ⟶ (∃s. subtrie_at_path tr p (Leaf (insert t s))))›

text ‹The trie contains no empty subtries›

inductive minimal_storage :: ‹ ('f,'v) trie ⇒ bool› where
  minimal_storage_leaf: ‹ts ≠ {} ⟹ minimal_storage (Leaf ts)›
| minimal_storage_node: ‹(∀m2 ∈ fmran' m. ∀tr ∈ fmran' m2. minimal_storage tr ∧ tr ≠ empty_trie) ⟹ minimal_storage (SymbolNode m)› 

text ‹The empty trie satisfies all four invariants›

lemma well_structured_empty_trie [simp]: ‹well_structured empty_trie›
  by (simp add: ws_node)

lemma sound_empty_trie [simp]: ‹sound_storage empty_trie›
  using sound_storage_def subtrie_at_path.cases by fastforce

lemma complete_empty_trie [simp]: ‹complete_storage empty_trie›
  by (simp add: complete_storage_def)

lemma minimal_empty_trie [simp]: ‹minimal_storage empty_trie›
  by (simp add: minimal_storage_node)

lemma subtrie_at_nil_iff_eq: ‹subtrie_at_path tr [] str ⟹ str = tr›
  using subtrie_at_path.cases by auto

text ‹complete storage and sound storage must be expressed as inductive invariants.
       For this we must take into account the position of a node within the trie›

definition complete_storage_from_position :: ‹('f, 'v) trie ⇒ 'f tpath ⇒ bool› where
  ‹complete_storage_from_position tr p = (∀t . t ∈ to_set tr ⟶ (∀p2. path_of_term t (p @ p2) ⟶ (∃s. subtrie_at_path tr p2 (Leaf (insert t s)))))›

lemma complete_storage_alt_def: ‹complete_storage t = complete_storage_from_position t []›
  unfolding complete_storage_def complete_storage_from_position_def by auto

lemma complete_storage_from_position_subtrie:
  assumes ‹complete_storage_from_position (SymbolNode m1) p›
      and ‹m1 $$ s = Some m2›
      and ‹m2 $$ i = Some tr›
    shows ‹complete_storage_from_position tr (p @ [(s, i)])›
proof -
  have ‹⋀ t p2. t ∈ to_set tr ⟹ path_of_term t (p @ [(s, i)] @ p2) ⟹ ∃s. subtrie_at_path tr p2 (Leaf (insert t s))›
  proof -
    fix t p2
    assume elem: ‹t ∈ to_set tr› and path: ‹path_of_term t (p @ [(s, i)] @ p2)›
    have elem': ‹t ∈ to_set (SymbolNode m1)›
      by (metis (no_types, opaque_lifting) UN_iff fmlookup_ran'_iff to_set.simps(2) assms(2,3) elem)
    have path': ‹path_of_term t (p @ [(s, i)] @ p2)› using path by blast
    have ‹∃ts. subtrie_at_path (SymbolNode m1) ((s, i) # p2) (Leaf (insert t ts))› using assms(1) elem' path' unfolding complete_storage_from_position_def by force
    then show ‹∃ts. subtrie_at_path tr p2 (Leaf (insert t ts))› using assms(2,3) subtrie_at_path.cases by fastforce
  qed
  then show ?thesis unfolding complete_storage_from_position_def by auto
qed

definition sound_storage_from_position :: ‹('f, 'v) trie ⇒ 'f tpath ⇒ bool› where
  ‹sound_storage_from_position tr p = (∀t p2 s. subtrie_at_path tr p2 (Leaf (insert t s)) ⟶ path_of_term t (p @ p2))›

lemma sound_storage_alt_def: ‹sound_storage t = sound_storage_from_position t []›
  unfolding sound_storage_def sound_storage_from_position_def by auto

lemma sound_storage_from_position_subtrie:
  assumes ‹sound_storage_from_position (SymbolNode m1) p›
      and ‹m1 $$ s = Some m2›
      and ‹m2 $$ i = Some tr›
    shows ‹sound_storage_from_position tr (p @ [(s, i)])›
  using assms(1,2,3) subtrie_at_path_step unfolding sound_storage_from_position_def 
  by (metis append.assoc append_Cons append_Nil)

lemma non_empty_to_set_subtrie: ‹to_set tr ≠ {} ⟹ ∃p t s. subtrie_at_path tr p (Leaf (insert t s))›
  by (meson all_not_in_conv exists_leaf)

lemma no_subtrie_in_empty_trie : ‹¬ subtrie_at_path empty_trie p (Leaf S)›
  using subtrie_at_path.cases by fastforce

lemma sibling_nodes_subset:
  assumes ‹well_structured (SymbolNode m)›
      and ‹complete_storage_from_position (SymbolNode m) p›
      and ‹sound_storage_from_position (SymbolNode m) p›
      and ‹m $$ F f n = Some m2›
      and ‹m2 $$ i = Some tr_i›
      and ‹m2 $$ j = Some tr_j›
    shows ‹to_set tr_i ⊆ to_set tr_j›
proof
  fix t
  assume h0: ‹t ∈ to_set tr_i›
  then have h0': ‹t ∈ to_set (SymbolNode m)›
    using assms(4,5) entry_to_set by blast
  show ‹t ∈ to_set tr_j›
  proof (cases n)
    case 0
    then have ‹i = 0 ∧ j = 0›
      by (metis assms(1,4,5,6) fmdom'I singletonD ws_dom_const)
    then show ?thesis
      using assms(5,6) h0 by auto
  next
    case (Suc n')
    then have h1: ‹i < Suc n' ∧ j < Suc n'›
      by (metis assms(1,4,5,6) fmdom'I key_map_entry nat.simps(3))
    have ‹sound_storage_from_position tr_i (p @ [(F f n, i)])›
      using assms(3,4,5) sound_storage_from_position_subtrie by blast
    then obtain p2 ts where ‹subtrie_at_path tr_i p2 (Leaf (insert t ts))› and ‹path_of_term t ((p @ [(F f n, i)]) @ p2)›
      by (metis sound_storage_from_position_def h0 exists_leaf)
    then obtain f_args where h2: ‹subterm_at_path t p (Fun f f_args) ∧ Suc n' = length f_args›
      by (metis fun_is_subterm_at_last Suc append.assoc append_Cons)
    obtain p3 where ‹path_of_term (f_args ! j) p3› using h1
      using exists_path by blast
    then have ‹path_of_term (Fun f f_args) ((F f n, j) # p3)›
      by (metis Suc h2 bot_nat_0.extremum_strict h1 list.size(3) path_of_term_func)
    then have ‹path_of_term t ((p @ [(F f n, j)]) @ p3)›
      using h2 subterm_at_path_path_of_term by auto
    then obtain ts2 where ‹subtrie_at_path (SymbolNode m) ((F f n, j) # p3) (Leaf (insert t ts2))›
      using h0' assms(2) unfolding complete_storage_from_position_def by auto
    then show ?thesis
      using assms(4,6) subtrie_entry_to_set by blast
  qed
qed

lemma sibling_nodes_to_set:
  assumes ‹well_structured (SymbolNode m)›
      and ‹complete_storage_from_position (SymbolNode m) p›
      and ‹sound_storage_from_position (SymbolNode m) p›
      and ‹m $$ F f n = Some m2›
      and ‹m2 $$ i = Some tr_i›
      and ‹m2 $$ j = Some tr_j›
    shows ‹to_set tr_i = to_set tr_j›
  using sibling_nodes_subset assms by fastforce

subsection ‹Term insertion›

fun insert_leaf :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) trie› where
  ‹insert_leaf (Leaf s) t = Leaf (insert t s)›
| ‹insert_leaf (SymbolNode m) t = undefined›

function (sequential) insert_aux :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) term ⇒ ('f, 'v) trie› where
  ‹insert_aux (Leaf s) t t0 = undefined›
| ‹insert_aux (SymbolNode m) (Var x) t0 = 
   SymbolNode (update_entry m Star (λm2. update_entry m2 0 (λtr. insert_leaf tr t0) (Leaf {})) fmempty)›
| ‹insert_aux (SymbolNode m) (Fun f []) t0 =
   SymbolNode (update_entry m (F f 0)(λm2. update_entry m2 0 (λtr. insert_leaf tr t0) (Leaf {})) fmempty)›
| ‹insert_aux (SymbolNode m) (Fun f f_args) t0 =
   SymbolNode (update_entry m (F f (length f_args))
     (λm2. update_entries m2 [0..<length f_args] (λi tr. if i < (length f_args) then insert_aux tr (f_args ! i) t0 else undefined) empty_trie) {$$})›
  by pat_completeness auto
termination
proof (relation ‹measure (λ(p, q, r). depth q)›)
  show ‹wf (measure (λ(p, q, r). depth q))› by simp
next
  show ‹⋀m f v va t0 x xa xb. xa < length (v # va) ⟹ ((xb, (v # va) ! xa, t0), SymbolNode m, Fun f (v # va), t0) ∈ measure (λ(p, q, r). depth q)›
    by (simp; metis List.finite_set Max_ge finite_imageI image_eqI image_insert le_imp_less_Suc length_Cons list.simps(15) nth_mem)
qed

declare List.upt.upt_Suc [simp del]

lemma fmran_updt_entries_empty:
  assumes ‹distinct ls› 
    shows ‹fmran'(update_entries {$$} ls f v) = (λy. f y v) ` set ls›
  using assms by (simp add: rew_ran_upd_entries_none)

lemma in_fmran_updt_entries:
  assumes ‹distinct ls›
      and ‹fmdom' m = set ls›
      and ‹t ∈ fmran' (update_entries m ls f v)›
    shows ‹∃i∈set ls. t = f i (m $$! i)›
  using assms
proof-
  have ‹∀k∈set ls. m $$ k ≠ None›
    by (metis assms(2) fmdom'_notI)
  then show ?thesis using  upd_entries_some update_entries_dom
    by (smt (verit, ccfv_threshold) Un_iff assms(1) assms(2) assms(3) fmdom'I fmdom'_alt_def fmdomE fmran'E option.sel)
qed

lemma in_fmran_updt_entries_left: 
  assumes ‹distinct ls›
      and ‹fmdom' m = set ls›
      and ‹i ∈ set ls› 
    shows ‹f i (m $$! i) ∈ fmran' (update_entries m ls f v)›
  using assms  by (metis fmdom'_notI fmran'I option.exhaust_sel upd_entries_some)

lemma rew_upd_entries_none:
  assumes ‹distinct ls›
      and ‹k ∈ set ls›
      and ‹m $$ k = None›
    shows ‹(update_entries m ls f v) $$ k = Some(f k v)›
  using assms
proof (induction m ls f v arbitrary: k rule: update_entries.induct)
  case (1 m)
  then show ?case 
    by simp
next
  case (2 m k' ks f v)
  then show ?case 
  proof (cases ‹k = k'›)
    case True
    then show ?thesis proof (cases ‹m $$ k'›)
      case None
      then show ?thesis 
        by (simp, metis (mono_tags, lifting) "2.prems"(1) True distinct.simps(2) fmupd_idem fmupd_lookup option.simps(5) updt_entries_some update_entries.simps(2) update_entry.simps)
    next
      case (Some a)
      then show ?thesis
        using "2.prems"(3) True by auto  
    qed
  next
    case False
    then show ?thesis
      using 2 by auto
  qed
qed

lemma fmran_updt_entries:
  assumes ‹distinct ls›
      and ‹fmdom' m = set ls›
    shows ‹fmran' (update_entries m ls f v) = (λi. f i (m $$! i)) ` set ls›
proof -
  have h0: ‹fmran' (update_entries m ls f v) ⊆ (λi. f i (m $$! i)) ` set ls›
  proof
    fix t
    assume ‹t ∈ fmran' (update_entries m ls f v)›
    then obtain i where ‹i ∈ set ls› and ‹t = f i (m $$! i)›
      using in_fmran_updt_entries
      by (metis assms(1) assms(2))
    thus ‹t ∈ (λi. f i (m $$! i)) ` set ls›
      by simp
  qed
  have ‹(λi. f i (m $$! i)) ` set ls ⊆ fmran' (update_entries m ls f v)›
  proof
    fix t
    assume ‹t ∈ (λi. f i (m $$! i)) ` set ls›
    then obtain i where ‹i ∈ set ls› and ‹t = f i (m $$! i)›
      by auto
    hence ‹t ∈ fmran' (update_entries m ls f v)›
      by (simp add: assms(1) assms(2) in_fmran_updt_entries_left)
    thus ‹t ∈ fmran' (update_entries m ls f v)›
      by simp
  qed
  thus ?thesis
    using h0 by force
qed

lemma rew_fmran_updt_entries_empty: ‹fmran' (update_entries {$$} [0..<Suc (length f_args)] f v) = (λy. f y v) ` set [0..<Suc (length f_args)]›
  by (metis distinct_upt fmran_updt_entries_empty)

lemma insert_none_image: ‹k < Suc (length f_args) ⟹
  update_entries {$$} ([0..<Suc (length f_args)])
       (λi tr. if i < Suc (length f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie $$ k =
 Some (insert_aux empty_trie ((a # f_args) ! k) t0)›
  by (simp add: rew_upd_entries_none)

lemma insert_none_image': ‹k < Suc (length f_args) ⟹
  update_entries {$$} ([0..<Suc (length f_args)])
       (λi tr.  insert_aux tr ((a # f_args) ! i) t0 ) empty_trie $$ k =
 Some (insert_aux empty_trie((a # f_args) ! k) t0)›
  by (simp add: rew_upd_entries_none)

lemma rew_insert_none: ‹ fmran' (update_entries {$$} ([0..<Suc (length f_args)])
      (λi tr. if i < Suc (length f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie)= (λi. (insert_aux empty_trie ((a # f_args) ! i) t0)) ` set [0..<Suc (length f_args)]›
  by (simp add: rew_fmran_updt_entries_empty)

lemma fmdom'_fmap_of_list: ‹ fmdom' (fmap_of_list xs) = set (map fst xs)›
  by (metis dom_map_of_conv_image_fst fmap_of_list.rep_eq fmdom'.rep_eq image_set)

lemma insert_some_image:
  assumes ‹k < Suc (length f_args)›
      and ‹fmdom' m = set [0..<Suc (length f_args)]› 
    shows ‹update_entries m [0..<Suc (length f_args)] (λi tr. if i < Suc (length f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie $$ k = Some (insert_aux (m $$! k) ((a # f_args) ! k) t0)›
proof -
  have h0: ‹k ∈ set [0..<Suc (length f_args)]›
    using assms(1) atLeast_upt by blast then 
  obtain tr where
    f4: ‹k ∈ fmdom' m ⟹ m $$ k = Some tr›
      by (meson fmlookup_dom'_iff)
  have ‹k ∈ fmdom' m›
    using h0 assms(2) by blast
  then have ‹m $$ k = Some tr›
    using f4 by blast
  then show ?thesis
    using h0 assms(1) by (simp add: upd_entries_some)
qed

inductive_cases well_structured_cases: ‹well_structured tr›
declare well_structured_cases [elim!]

inductive_cases well_structured_map_entry_cases: ‹well_structured_map_entry s m›
declare well_structured_map_entry_cases [elim!]

lemma ws_insert_var: 
  assumes ‹well_structured (SymbolNode m)›
    shows ‹well_structured (insert_aux (SymbolNode m) (Var x) t)›
  using assms
proof (cases ‹m $$ Star›)
  case None
  then show ?thesis
    using assms by (clarsimp simp add: update_entry_ran ws_node wsme_var)
next
  case h1: (Some m0)
  then show ?thesis  
  proof (cases ‹m0 $$ 0›)
    case None
    then show ?thesis using assms
      by (meson fmdom'I fmdom'_notI h1 ws_dom_var)
  next
    case (Some tr)
    then show ?thesis 
    proof (cases tr)
      case (Leaf ts)   
      then have ‹symbol.Star ∈ fmdom' m›
        by (simp add: fmdom'I h1)
      then  have h3: ‹fmdom' (m0 (0 $$:= insert_leaf tr t)) = {0}›
        using h1 assms by auto
      then have ‹∀tr2. tr2 ∈ fmran' (m0 (0 $$:= insert_leaf tr t)) ⟶ (∃ts. tr2 = Leaf ts)›
        by (metis Leaf fmdom'I fmlookup_ran'_iff fmupd_lookup insert_leaf.simps(1) option.sel singleton_iff)
      then have ‹well_structured_map_entry symbol.Star (m0 (0 $$:= insert_leaf tr t))›
        by (metis h3 wsme_var Leaf fmupd_lookup insert_leaf.simps(1))
      then have ‹well_structured (SymbolNode (m(symbol.Star $$:= m0(0 $$:= insert_leaf tr t))))›
        using assms
        by (metis fmdom'_fmupd fmupd_lookup insert_iff option.sel trie.inject(2) well_structured.cases ws_node)
      then show ?thesis 
        by (simp add: h1 Some)
    next
      case (SymbolNode m2)
      then show ?thesis using assms
        by (metis Some h1 option.sel trie.distinct(1) ws_dom_var)
    qed
  qed
qed

lemma ws_insert_const: 
  assumes ‹well_structured (SymbolNode m)›
    shows ‹well_structured (insert_aux (SymbolNode m) (Fun f []) t0)›
  using assms
proof (cases ‹m $$ F f 0›)
  case None  
  from assms have h0: ‹∀s. s ∈ fmdom' m ⟶  well_structured_map_entry s (m $$! s)›
    by force
  then  have h3: ‹well_structured_map_entry (F f 0) {0 $$:= Leaf {t0}}›
    by (simp add: update_entry_ran wsme_const)
  then have h4 : ‹F f 0 ∈ fmdom' m ⟶ well_structured_map_entry (F f 0) {0 $$:= Leaf {t0}}›
    by simp
  then have ‹well_structured (SymbolNode (m(F f 0 $$:= {0 $$:= Leaf {t0}})))›
    by (simp add: h0 h3 ws_node)
  then show ?thesis by (simp add: None) 
next
  case (Some m2)
  then show ?thesis 
  proof (cases ‹m2 $$ 0›)
    case None
    then show ?thesis
      by (metis assms Some option.discI ws_dom_const)
  next
    case s: (Some n)
    then have ‹F f 0  ∈ fmdom' m›
      by (simp add: fmdom'I Some)
    then show ?thesis  
    proof (cases n)
      case (Leaf ts)
      then have h1: ‹fmdom' (m2 (0 $$:= Leaf (insert t0 ts))) = {0}›
        by (metis assms Some fmdom'I fmdom'_fmupd insert_absorb ws_dom_const)
      then have h0: ‹well_structured_map_entry (F f 0) (m2 (0 $$:= Leaf (insert t0 ts)))›
        by (metis fmupd_lookup wsme_const)
      then have h3: ‹∀s. s ∈ fmdom' m ⟶  well_structured_map_entry s (m $$! s)›
        using assms by fastforce
      then show ?thesis by (simp add: Some Leaf s h0 ws_node)
    next
      case (SymbolNode m3)
      then show ?thesis
        by (metis assms Some s option.sel trie.distinct(1) ws_dom_const)
    qed
  qed
qed

lemma insert_preserves_structure:
  assumes ‹well_structured tr›
    shows ‹well_structured (insert_aux tr t t0)›
  using assms
proof (induct tr t t0 rule: insert_aux.induct)
  case (1 s t t0)
  then show ?case by auto
next
  case (2 m x t0)
  then show ?case by (meson ws_insert_var)
next
  case (3 m f t0)
  then show ?case by (meson ws_insert_const)
next
  case (4 m f a f_args t0)
  then have dom_well_structured: ‹∀s. s ∈ fmdom' m ⟶ well_structured_map_entry s (m $$! s)›
    using "4.prems" by blast
  show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    let ?m' = ‹update_entries {$$} [0..<length (a # f_args)]
                 (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) 
                 empty_trie›
    have dom_m': ‹fmdom' ?m' = {..<length (a # f_args)}›
      by (simp add: atLeast_upt update_entries_dom)
    have well_structured_fmran: ‹⋀t. t ∈ fmran' ?m' ⟹ well_structured t›
    proof -
      fix t 
      assume ‹t ∈ fmran' ?m'›
      then obtain i where in_dom': ‹i ∈ fmdom' ?m'› and ‹?m' $$ i = Some t›
        by (meson fmdom'I fmlookup_ran'_iff)
      then have k: ‹insert_aux empty_trie ((a # f_args) ! i) t0 = t›
        using dom_m' by (simp add: rew_upd_entries_none)
      then have ‹i < length (a # f_args)›
        using dom_m' in_dom' by blast
      then show  ‹well_structured t›
        by (metis "4.hyps" fmdom'_notI fmempty_lookup k ws_node)
    qed
    then have ‹well_structured_map_entry (F f (length (a # f_args))) ?m'›
      by (metis (no_types, lifting) dom_m' length_greater_0_conv list.distinct(1) list.size(3) wsme_func)
    then show ?thesis using None dom_well_structured
      by (simp add: ws_node)
  next
    case (Some m2)
    let ?m'' = ‹update_entries m2 [0..<length (a # f_args)]
                 (λi tr. if i < Suc (length f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) 
                 empty_trie›
    have dom_m2: ‹fmdom' m2 = {..<length (a # f_args)}›
      by (metis "4.prems" Some length_Cons list.distinct(1) ws_fmdom')
    have all_well_structured: ‹∀i ∈ fmdom' m2. well_structured (m2 $$! i)›
      by (metis "4.prems" Some fmdom'_notI length_greater_0_conv list.distinct(1) option.collapse ws_subtree)
    obtain i where in_dom': ‹i ∈ fmdom' m2›
      using dom_m2 by blast
    then have ‹i < length (a # f_args)›
      by (metis in_dom' dom_m2 lessThan_iff)
    then have insert_well_structured: ‹well_structured (insert_aux (m2 $$! i) ((a # f_args) ! i) t0)›
      using "4.hyps" all_well_structured in_dom' by blast
    have dom_m'': ‹fmdom' ?m'' = {..<length (a # f_args)}›
      by (simp add: atLeast_upt dom_m2 update_entries_dom)
    have ran_m'': ‹fmran' ?m'' = (λi. insert_aux (m2 $$! i) ((a # f_args) ! i) t0) ` set [0..<length (a # f_args)]›
      using fmran_updt_entries[of ‹[0..<length (a # f_args)]› m2] atLeast_upt dom_m2 by auto
    have well_structured_fmran'': ‹⋀t. t ∈ fmran' ?m'' ⟹ well_structured t›
      using "4.hyps" all_well_structured dom_m2 ran_m'' by auto
    then show ?thesis using Some dom_m'' "4.prems" dom_well_structured
      by  (simp add: ws_node  dom_m'' wsme_func)
  qed
qed

lemma minimal_storage_drop [simp]:
  assumes ‹minimal_storage (SymbolNode m)›
  shows ‹minimal_storage (SymbolNode (fmdrop s m))›
proof -
  have ‹⋀m2 tr. m2∈fmran' (fmdrop s m) ⟹ tr∈fmran' m2 ⟹ minimal_storage tr ∧ tr ≠ empty_trie›
  proof -
    fix m2 tr
    assume ‹m2 ∈ fmran' (fmdrop s m)› and h: ‹tr ∈ fmran' m2›
    then have ‹m2 ∈ fmran' m›
      by (metis fmlookup_drop fmlookup_ran'_iff option.simps(3))
    then show ‹minimal_storage tr ∧ tr ≠ empty_trie›
      using assms h minimal_storage.cases by auto
  qed
  then show ?thesis
    by (simp add: minimal_storage_node)
qed

lemma minimal_storage_udt: 
  assumes ‹minimal_storage (SymbolNode m)›
      and ‹minimal_storage (SymbolNode {s $$:= m2})›
    shows ‹minimal_storage (SymbolNode (m(s $$:= m2)))›
  by (smt (verit, del_insts) assms(1) assms(2) fmlookup_ran'_iff fmupd_lookup minimal_storage.cases minimal_storage_node trie.sel(3) trie.simps(4))

lemma insert_preserves_minimal: 
  assumes ‹well_structured tr›
      and ‹minimal_storage tr› 
    shows ‹minimal_storage (insert_aux tr t t0)›
  using assms
proof  (induction tr t t0  rule: insert_aux.induct)
  case (1 s t t0)
  then show ?case by blast 
next
  case (2 m x t0)
  then show ?case
  proof (cases ‹m $$ Star›)
    case None
    have ‹minimal_storage (SymbolNode ({symbol.Star $$:= {0 $$:= Leaf {t0}}}))›
      by (metis fmran'_alt_def fmran_singleton fsingleton_iff insert_not_empty minimal_storage.simps trie.simps(4))
    then show ?thesis
      using "2.prems"(2) minimal_storage_udt None 
      by auto
  next
    case (Some m2)
    then obtain ts where h: ‹m2 $$ 0 = Some (Leaf ts)›
      by (meson "2.prems"(1) ws_dom_var)
    have ‹minimal_storage (SymbolNode {Star $$:= m2(0 $$:= insert_leaf (Leaf ts) t0)})›
      by (smt (verit, ccfv_threshold) "2.prems"(1) Some dom_res_singleton fmempty_lookup fmfilter_true fmlookup_dom'_iff fmran_empty' fmupd_idem insert_leaf.simps(1) insert_not_empty minimal_storage.simps singletonD trie.distinct(1) update_entry_ran ws_dom_var)
    then show ?thesis
      using "2.prems"(2) Some h minimal_storage_udt by auto
  qed
next
  case (3 m f t0)
  then show ?case
  proof (cases ‹m $$ F f 0›)
    case None
    have ‹minimal_storage (SymbolNode ({F f 0 $$:= {0 $$:= Leaf {t0}}}))›
      by (metis fmempty_lookup fmran_empty' insert_not_empty minimal_storage.simps singletonD trie.simps(4) update_entry_ran)
    then show ?thesis
      using "3.prems"(2) minimal_storage_udt  None 
      by auto
  next
    case (Some m2)
    then obtain ts where h: ‹m2 $$ 0 = Some (Leaf ts)›
      by (meson "3.prems"(1) ws_dom_const)
    have ‹minimal_storage (SymbolNode {F f 0 $$:= m2(0 $$:= insert_leaf (Leaf ts) t0)})›
      by (smt (verit, best) "3.prems"(1) Some fmdom'I fmdom'_empty fmlookup_ran'_iff fmupd_lookup insert_absorb insert_leaf.simps(1) insert_not_empty minimal_storage.simps option.sel singletonD trie.distinct(1) ws_dom_const)
    then show ?thesis
      using "3.prems"(2) Some h minimal_storage_udt by auto
  qed
next
  case (4 m f a f_args t0)
  then show ?case 
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    let ?m' = ‹update_entries {$$} [0..<length (a # f_args)]
          (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
    have hi: ‹⋀i. i < length (a # f_args) ⟹ minimal_storage (insert_aux empty_trie ((a # f_args) ! i) t0)›
      by (simp add: 4)
    have ‹⋀m2 tr. m2 ∈ fmran' {F f (length (a # f_args)) $$:= ?m'} ⟹ tr ∈ fmran' m2 ⟹ minimal_storage tr ∧ tr ≠ empty_trie›
    proof -
      fix m2 tr2
      assume h1: ‹m2 ∈ fmran' {F f (length (a # f_args)) $$:= ?m'}›
      then have h2: ‹m2 = ?m'› by (simp add: update_entry_ran)
      assume h3: ‹tr2 ∈ fmran' m2›
      then obtain i where h4: ‹m2 $$ i = Some tr2› by auto
      then have h5: ‹i < length (a # f_args)› using h2 h3
        by (metis (no_types, lifting) add_0 diff_zero fmdom'I fmdom'_empty in_set_conv_nth length_upt nth_upt sup_bot.right_neutral update_entries_dom)
      then have h6: ‹tr2 = insert_aux (SymbolNode {$$})  ((a # f_args) ! i) t0› using rew_insert_none 
        by (smt (verit, ccfv_SIG) distinct_upt fmdom'I fmdom'_empty fmempty_lookup fmran'_alt_def fmran_singleton fsingleton_iff h1 h4 option.sel rew_upd_entries_none sup_bot.right_neutral update_entries_dom)
      then have h7: ‹minimal_storage tr2› using hi h1 h3 h4 h5 by blast
      then have ‹tr2 ≠ empty_trie› 
        using fmap_distinct(1) h6 insert_aux.elims trie.distinct(1) trie.sel(3) by force
      then show ‹minimal_storage tr2 ∧ tr2 ≠ empty_trie› 
        using h7 by auto 
    qed
    then have ‹minimal_storage (SymbolNode {F f (length (a # f_args)) $$:= ?m'})›
      using minimal_storage_node by blast
    then show ?thesis using "4.prems"(2)minimal_storage_udt None by auto  
  next
    case (Some m2)
    have dom_m2: ‹fmdom' m2= {0..<length (a # f_args)}›
      by (metis "4.prems"(1) Some atLeast_upt length_Cons list.distinct(1) set_upt ws_fmdom')
    have h0: ‹⋀ i. i< length (a # f_args) ⟹ minimal_storage (insert_aux (m2 $$! i) ((a # f_args) ! i) t0)›
    proof-
      fix i 
      assume h1: ‹i < length (a # f_args)›
      then have in_dom: ‹i ∈ fmdom' m2›
        by (simp add: dom_m2)
      then have h2: ‹well_structured (m2 $$! i)›
        using "4.prems"(1) Some
        by (metis bot_nat_0.extremum_strict fmdom'_notI h1 length_greater_0_conv list.size(3) option.collapse ws_subtree)
      have ‹minimal_storage (m2 $$! i)›
        using "4.prems"(2) Some
        by (metis fmlookup_dom'_iff fmlookup_ran'_iff in_dom minimal_storage.simps option.sel trie.distinct(1) trie.sel(3))
      then show ‹minimal_storage (insert_aux (m2 $$! i) ((a # f_args) ! i) t0)›
        using 4 h1 h2 by presburger 
    qed
    have h3: ‹minimal_storage empty_trie› by auto
    have h4: ‹minimal_storage (SymbolNode (fmdrop (F f (length (a # f_args))) m))›
      by (simp add: "4.prems"(2))
    let ?m' = ‹update_entries m2 [0..< length (a # f_args)] (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
    have ir: ‹⋀i tr2 . ?m'$$ i = Some tr2 ⟹ minimal_storage tr2 ∧ tr2 ≠ empty_trie›
    proof-
      fix i tr2
      assume h5: ‹?m'$$ i = Some tr2›
      then have h6: ‹i < length (a # f_args)›
        by (metis (lifting) length_Cons ws_dom_fun2 "4.prems"(1) Some Un_iff dom_m2 fmdom'I set_upt update_entries_dom)
      then have h7: ‹tr2 = insert_aux (m2 $$! i) ((a # f_args) ! i) t0›
        using dom_m2 h5 insert_some_image by fastforce
      then have h8: ‹minimal_storage tr2›
        using h0 h6 by blast
      have ‹well_structured (m2 $$! i)›
        by (metis "4.prems"(1) Some bot_nat_0.extremum_strict fmdom'_notI h6 length_greater_0_conv list.size(3) option.collapse
            ws_dom_fun ws_subtree)
      then have ‹tr2 ≠ empty_trie›
        using h7 by (smt (verit, ccfv_SIG) fmap_distinct(1) insert_aux.elims trie.distinct(1) trie.sel(3) update_entry.elims well_structured.cases)
      then show ‹minimal_storage tr2 ∧ tr2 ≠ empty_trie›
        using h8 by blast
    qed
    then have ‹minimal_storage (SymbolNode {F f (length (a # f_args)) $$:= ?m'})›
      by (smt (verit, del_insts) fmempty.rep_eq fmran'E fmran_empty' minimal_storage_node singletonD update_entry_ran)
    then  show ?thesis
      using "4.prems"(2) minimal_storage_udt Some
      by (auto simp add: Some)
  qed
qed

lemma only_empty_trie_is_empty:
  assumes ‹to_set tr = {}›
      and ‹minimal_storage tr›
      and ‹well_structured tr›
    shows ‹tr = empty_trie›
  using assms
proof (induction tr)
  case (Leaf ts)
  then show ?case by auto
next
  case (SymbolNode m)
  have h0: ‹⋀m2 tr2. m2 ∈ fmran' m ⟹ tr2 ∈ fmran' m2 ⟹ to_set tr2 = {}›
    using SymbolNode.prems(1) by auto
  moreover have h1: ‹⋀m2 tr2. m2 ∈ fmran' m ⟹ tr2 ∈ fmran' m2 ⟹ minimal_storage tr2 ∧ tr2 ≠ empty_trie›
    using SymbolNode.prems(2) minimal_storage.simps [of ‹SymbolNode m›] by fast
  ultimately have h2: ‹⋀m2 tr2. m2 ∈ fmran' m ⟹ tr2 ∈ fmran' m2 ⟹ ¬ well_structured tr2›
    using SymbolNode.IH by metis
  have ‹⋀s. m $$ s = None›
  proof -
    fix s
    show ‹m $$ s = None›
    proof (rule ccontr)
      assume ‹m $$ s ≠ None›
      then obtain m2 where h3: ‹m $$ s = Some m2› by blast
      then have ‹well_structured_map_entry s m2›
        by (metis SymbolNode.prems(3) option.sel well_structured.cases trie.sel(3) fmdom'I)
      then show False
      proof (cases s)
        case (wsme_var ts)
        then show ?thesis
          by (metis h0 h1 h3 fmran'I to_set.simps(1) trie.distinct(1) minimal_storage.simps)
      next
        case (wsme_const ts f)
        then show ?thesis
          by (metis h0 h1 h3 fmran'I to_set.simps(1) trie.distinct(1) minimal_storage.simps)
      next
        case (wsme_func arity f)
        then show ?thesis
          by (metis h2 h3 fmlookup_ran'_iff bot_nat_0.not_eq_extremum fmdom'_notI not_Some_eq lessThan_iff)
      qed
    qed
  qed
  then show ?case
    by (simp add: fmap_ext)
qed

lemma fmran'_singleton: ‹fmran' {k $$:= v} = {v}›
  by (simp add: fmran'_alt_def fmran_singleton)

lemma insert_var_adds_element:
  assumes ‹well_structured tr›
    shows ‹t ∈ to_set (insert_aux tr (Var x) t)›
  using assms
proof (cases tr)
  case (ws_node m)
  then show ?thesis  
  proof (cases ‹m $$ Star›)
    case None
    then show ?thesis using ws_node None 
      by (simp add: update_entry_ran)
  next
    case (Some m2)
    then obtain ts where ‹m2 $$ 0 = Some (Leaf ts)›
      by (metis assms local.ws_node(1) ws_dom_var)
    then show ?thesis
      by (smt (verit, ccfv_SIG) fmdom'I fmdom'_notI fmupd_lookup insertCI insert_aux.simps(2) insert_leaf.simps(1) local.ws_node(1) option.case_eq_if option.sel Some to_set.simps(1) entry_to_set update_entry.simps)
  qed
qed

lemma insert_var_keeps_elements:
  assumes ‹well_structured (SymbolNode m)›
      and ‹t ∈ to_set (SymbolNode m)›
    shows ‹t ∈ to_set (insert_aux (SymbolNode m) (Var x) t0)›
proof (cases ‹m $$ Star›)
  case None
  then show ?thesis 
    using assms None by (simp add: update_entry_ran) 
next
  case (Some m2)
  then obtain ts where ‹m2 $$ 0 = Some (Leaf ts)›
    by (meson assms(1) ws_dom_var)
  then show ?thesis using Some assms
    by (simp, metis fmlookup_ran'_iff fmupd_lookup insert_iff option.sel to_set.simps(1))
qed

lemma insert_var_subset:
  assumes ‹well_structured (SymbolNode m)›
  shows ‹to_set (insert_aux (SymbolNode m) (Var x) t) ⊆ insert t (to_set (SymbolNode m))›
proof (cases ‹m $$ Star›)
  case None
  then show ?thesis
    by (clarsimp, metis fmempty_lookup fmran_empty' insertE singletonD to_set.simps(1) update_entry_ran)
next
  case (Some m2)
  then obtain ts where ‹m2 $$ 0 = Some (Leaf ts)›
    by (meson assms(1) ws_dom_var)
  then show ?thesis using Some assms
    by (simp, smt (verit, del_insts) UN_iff fmlookup_ran'_iff fmupd_lookup insert_iff option.sel subsetI to_set.simps(1))
qed

lemma insert_const_adds_element:
  assumes ‹well_structured tr›
   shows ‹t ∈ to_set (insert_aux tr (Fun f []) t)›
proof (cases tr)
  case (Leaf ts)
  then show ?thesis
    using assms by fastforce 
next
  case (SymbolNode m)
  then show ?thesis 
  proof (cases ‹m $$ F f 0›)
    case None
    then show ?thesis 
      by (simp add: update_entry_ran SymbolNode)
  next
    case (Some m2)
    then obtain ts where ‹m2 $$ 0 = Some (Leaf ts)›
      by (metis SymbolNode assms ws_dom_const)
    then show ?thesis using SymbolNode Some 
      by (simp, metis fmran'I fmupd_lookup insert_iff to_set.simps(1))
  qed
qed

lemma insert_const_keeps_elements:
  assumes ‹well_structured (SymbolNode m)›
      and ‹t ∈ to_set (SymbolNode m)›
    shows ‹t ∈ to_set (insert_aux (SymbolNode m) (Fun f []) t0)›
  using assms
proof (cases ‹m $$ F f 0›)
  case None
  then show ?thesis using assms None by (simp add: update_entry_ran) 
next
  case s1: (Some m)
  then obtain ts where ‹m $$ 0 = Some (Leaf ts)›
    by (metis assms(1) ws_dom_const)
  then show ?thesis using s1 assms
    by (simp, metis fmlookup_ran'_iff fmupd_lookup insert_iff option.sel to_set.simps(1))
qed

lemma insert_const_subset:
  assumes ‹well_structured (SymbolNode tr)›
    shows ‹to_set (insert_aux (SymbolNode tr) (Fun f []) t) ⊆ insert t (to_set (SymbolNode tr))›
proof (cases ‹tr $$ F f 0›)
  case None
  then show ?thesis
    by (clarsimp, metis fmempty_lookup fmran_empty' insertE singletonD to_set.simps(1) update_entry_ran)
next
  case (Some m)
  then show ?thesis
  proof (cases ‹m $$ 0›)
    case None
    then show ?thesis using Some assms None
      by (clarsimp, metis fmdom'I fmdom'_notI option.sel singletonI symbol.inject well_structured_map_entry.simps)
  next
    case s2: (Some tr2)
    then show ?thesis
    proof (cases tr2)
      case (Leaf ts)
      then show ?thesis using s2 Some assms
        by (clarsimp, metis (no_types, lifting) fmlookup_ran'_iff fmupd_lookup insert_iff option.sel to_set.simps(1))
    next
      case (SymbolNode m2)
      then show ?thesis using s2 Some assms
        by (metis option.sel trie.distinct(1) ws_dom_const)
    qed
  qed
qed

lemma insert_aux_adds_element: 
  assumes ‹well_structured tr›
    shows ‹t0 ∈ to_set (insert_aux tr t t0)›
  using assms
proof (induction t arbitrary: tr)
  case (Var x)
  then show ?case by (meson insert_var_adds_element)
next
  case (Fun f f_args)
  then show ?case
  proof (cases f_args)
    case Nil
    then show ?thesis
      by (simp add: Fun.prems insert_const_adds_element)  
  next
    case (Cons a f_args')
    then show ?thesis
    proof (cases tr)
      case (Leaf ts)
      then show ?thesis 
        using Fun.prems by force
    next
      case (SymbolNode m)
      then show ?thesis
      proof (cases ‹m $$ F f (Suc (length f_args'))›)
        case None
        let ?m' = ‹ update_entries {$$} [0..<Suc (length f_args')] (λi tr. if i < Suc (length f_args') then insert_aux tr ((a # f_args') ! i) t0 else undefined) empty_trie›
        have ‹t0 ∈ to_set (insert_aux empty_trie ((a # f_args') ! 0) t0)›
          using Fun.IH by (simp add: Cons ws_node)
        then have ‹∃x∈fmran'?m' . t0 ∈ to_set x› 
          by (simp only: rew_fmran_updt_entries_empty; force)
        then show ?thesis by (simp add: local.Cons None update_entry_ran SymbolNode)
      next
        case (Some m2)
        let ?m'' = ‹update_entries m2 [0..<Suc (length f_args')]
        (λi tr. if i < Suc (length f_args') then insert_aux tr ((a # f_args') ! i) t0 else undefined) empty_trie›
        have h0: ‹distinct [0..<Suc (length f_args')]›
          using distinct_upt by blast
        then have h1: ‹fmdom' m2 = set [0..<Suc (length f_args')]›
          by (metis SymbolNode Fun.prems Some atLeast_upt length_Cons list.distinct(1) ws_fmdom')
        have h2: ‹t0 ∈ to_set (insert_aux (m2 $$! 0) ((a # f_args') ! 0) t0)›
          using Fun.IH by (metis SymbolNode Fun.prems Some fmdom'I fmdom'_notI fmran'I length_Cons list.set_intros(1) local.Cons nat.distinct(1) nth_Cons_0 option.collapse option.sel symbol.distinct(1) symbol.inject trie.sel(3) well_structured.cases well_structured_map_entry.cases ws_dom_fun zero_less_Suc) 
        have ‹fmran' ?m'' = (λi. insert_aux (m2 $$! i) ((a # f_args') ! i) t0) ` set  [0..<Suc (length f_args')]›
          using fmran_updt_entries [of ‹[0..<Suc (length f_args')]› m2 ] h0 h1 
          by auto
        then have ‹insert_aux (m2 $$! 0) ((a # f_args') ! 0) t0 ∈ fmran' ?m''›
          by (simp add: upt_conv_Cons)
        then show ?thesis
          by (simp add: Some SymbolNode Cons, metis (no_types, lifting) h2 fmran'I fmupd_lookup nth_Cons_0)
      qed
    qed
  qed
qed 

lemma insert_aux_keeps_elements: 
  assumes ‹well_structured tr›
      and ‹t ∈ to_set tr›
    shows ‹t ∈ to_set (insert_aux tr t1 t2)›
    using assms
proof (induction tr t1 t2 rule: insert_aux.induct)
  case (1 s t t0)
  then show ?case by blast
next
  case (2 m x t0)
  then show ?case
    by (meson insert_var_keeps_elements)
next
  case (3 m f t0)
  then show ?case 
    by (meson insert_const_keeps_elements)
next
  case (4 m f a f_args t0)
  then show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    then have ‹t ∈ to_set (SymbolNode m)›
      using "4.prems"(2) by blast
    then show ?thesis using None by (simp add: update_entry_ran)
  next
    case (Some m2)
    then obtain m3 where h1: ‹m3 ∈ fmran' m› and h2: ‹∃xb∈fmran' m3. t ∈ to_set xb›
      using "4.prems"(2) by auto
    then show ?thesis
    proof (cases ‹m2 = m3›)
      case True
      then have h3: ‹fmdom' m2 = {0..< length (a # f_args)}›
        by (metis "4.prems"(1) Some atLeast_upt list.distinct(1) set_upt ws_fmdom')
      then  obtain i where h4: ‹t∈to_set (m2 $$! i)› and h5: ‹i ∈ fmdom' m2›
        by (metis True fmdom'I fmran'E option.sel h2)
      then have ws: ‹well_structured (m2 $$! i)›
        by (metis "4.prems"(1) Some fmdom'_notI length_greater_0_conv list.distinct(1) option.collapse ws_subtree)
      then have ‹i < length (a # f_args)›
        by (metis h5 h3 atLeastLessThan_iff)
      then have gh: ‹t ∈ to_set (insert_aux (m2 $$! i) ((a # f_args) ! i) t0)›
        using "4.IH" h4 ws by presburger
      have di: ‹distinct [0..<length (a # f_args)]›
        using distinct_upt by blast
      then have fm: ‹fmdom' m2 = set [0..<length (a # f_args)]›
        using atLeastLessThan_upt h3 by presburger
      let ?m'' = ‹update_entries m2 [0..<Suc (length f_args)]
        (λi tr. if i < Suc (length f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
      have ‹fmran' ?m'' = (λi. (insert_aux (m2 $$! i) ((a # f_args) ! i) t0)) ` set  [0..<length (a # f_args)]›
        using  fmran_updt_entries [of ‹[0..<Suc (length f_args)]› m2 ] di fm
        by auto
      then have h6: ‹∃m3∈fmran' ?m''. t ∈ to_set m3›
        using fm gh h5 by blast
      then have ‹?m''∈ fmran' (m(F f (length (a # f_args)) $$:= ?m''))›
        by (meson fmlookup_ran'_iff fmupd_lookup)
      then show ?thesis 
        using h6 Some 
        by auto
    next
      case False
      then show ?thesis using 4 h1 h2 Some
        by (simp, metis (no_types, lifting) fmlookup_ran'_iff fmupd_lookup option.inject)
    qed
  qed
qed

lemma insert_aux_subset:
  assumes ‹well_structured tr›
    shows ‹to_set (insert_aux tr t t0 ) ⊆ insert t0 (to_set tr)›
proof
  fix x
  assume ‹x ∈ to_set (insert_aux tr t t0)›
  then show ‹x ∈ insert t0 (to_set tr)›
    using assms
  proof (induction tr t t0 rule: insert_aux.induct)
    case (1 s t t0)
    then show ?case
      by blast 
  next
    case (2 m x t0)
    then show ?case
      by (meson subsetD insert_var_subset)
  next
    case (3 m f t0)
    then show ?case
      by (meson in_mono insert_const_subset)
  next
    case (4 m f a f_args t0)
    have h0: ‹x ∈ to_set (insert_aux (SymbolNode m) (Fun f (a # f_args)) t0)›
      using "4.prems" by blast
    then show ?case
    proof (cases ‹m $$ F f (length (a # f_args))›)
      case None  
      let ?m' = ‹update_entries {$$} [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
      obtain tr2 where h1: ‹tr2 ∈ fmran' (children (insert_aux (SymbolNode m) (Fun f (a # f_args)) t0))›
                   and h2: ‹∃ tr2a ∈ fmran' tr2. x∈  to_set tr2a›
        using None update_entry_ran h0 subtrie_at_path.cases subtrie_to_set by auto
      then have ‹tr2 ∈ fmran' (m(F f (length (a # f_args)) $$:=?m'))›
        using None by simp
      then have ‹tr2 ∈ fmran' m ∨ tr2 = ?m'›
        using None update_entry_ran by force
      then  show ?thesis  
      proof (rule  disjE)
        assume ‹tr2 ∈ fmran' m›
        then show ?thesis
          using h2 by fastforce 
      next
        assume h3: ‹tr2 = ?m'›
        then obtain tr3 where h4: ‹tr3 ∈ fmran' tr2› and h5: ‹x ∈ to_set tr3›
          using h1 h2 by blast
        obtain i where h1: ‹tr2 $$ i = Some tr3›
          using h4 by auto
        then have ‹i∈ fmdom' tr2›
          by (simp add: fmdom'I)
        then have n0: ‹i < length (a # f_args)›
          by (simp add: h3 update_entries_dom)
        then have h6: ‹tr3 = insert_aux empty_trie ((a # f_args) ! i) t0›
          using h1 h3 by (simp add: rew_upd_entries_none)
        then show ?thesis 
          using h3 h5
          by (metis (no_types, lifting) "4.IH" empty_iff insert_iff n0 h6 no_subtrie_in_empty_trie non_empty_to_set_subtrie well_structured_empty_trie)
        qed
    next
      case (Some m2)
      let ?m' = ‹update_entries m2 [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
      obtain tr2 where h1: ‹tr2 ∈ fmran' (children (insert_aux (SymbolNode m) (Fun f (a # f_args)) t0))›
                   and h2: ‹∃ xm2 ∈ fmran' tr2. x∈  to_set xm2›
        using Some update_entry_ran h0 subtrie_at_path.cases subtrie_to_set by auto
      then   have ‹tr2 ∈ fmran' (m(F f (length (a # f_args)) $$:=?m'))›
        using Some by simp
      then  have ‹tr2 ∈ fmran' m ∨ tr2 = ?m'›
        using Some update_entry_ran
        by (smt (verit, best) fmlookup_ran'_iff fmupd_lookup option.inject) 
      then show ?thesis  
      proof (rule disjE)
        assume ‹tr2 ∈ fmran' m›
        then show ?thesis
          using h2 by fastforce 
      next
        assume h3: ‹tr2 = ?m'›
        then obtain tr3 where h4: ‹tr3 ∈ fmran' tr2› and h5: ‹x ∈ to_set tr3›
          using h1 h2 by blast
        obtain  i where h1: ‹tr2 $$ i = Some tr3›
          using h4 by auto
        then have r: ‹i ∈ fmdom' tr2›
          by (simp add: fmdom'I)
        then have b: ‹fmdom' m2 = set [0..<length (a # f_args)]›
          by (metis Some atLeast_upt length_Cons list.size(3) nat.distinct(1) "4.prems"(2) ws_fmdom')
        then have n0: ‹i < length (a # f_args)›
          using h3 b r by (simp add: update_entries_dom)
        then have  n3: ‹tr3 = insert_aux (m2 $$!i ) ((a # f_args) ! i) t0›
          using h3 h1 b n0 insert_some_image[of i f_args m2 a t0] by fastforce
        have n1:  ‹well_structured (m2 $$! i)›
          by (metis "4.prems"(2) Some fmdom'_notI length_greater_0_conv list.distinct(1) n0 option.collapse ws_dom_fun
              ws_subtree)
        then have g: ‹x = t0 ∨ x ∈ to_set tr3›
          by (simp add: h5)
        then show ?thesis proof (cases ‹x = t0›)
          case True
          then show ?thesis
            by blast 
        next
          case False
          then show ?thesis
            by (metis "4.IH" "4.prems"(2) Some entry_to_set fmdom'_notI h5 insert_iff n0 n1 n3 option.collapse ws_dom_fun)
        qed
      qed
    qed
  qed
qed

lemma elim_sound_fp:
  assumes h1: ‹sound_storage_from_position (SymbolNode m) p› 
      and h2: ‹sound_storage_from_position (SymbolNode {s $$:= m1}) p›
    shows ‹sound_storage_from_position (SymbolNode (m(s $$:= m1))) p›
  unfolding sound_storage_from_position_def
proof (intro allI impI)
  fix t p2 sa 
  assume h: ‹subtrie_at_path (SymbolNode (m(s $$:= m1))) p2 (Leaf (insert t sa))›
  show ‹path_of_term t (p @ p2)›
  proof (cases p2)
    case Nil
    then show ?thesis
      using h subtrie_at_nil by blast 
  next
    case (Cons a list)
    then show ?thesis 
    proof-
      from h1 have g1: ‹subtrie_at_path (SymbolNode m) (a # list) (Leaf (insert t sa)) ⟶ path_of_term t (p @ (a # list))›
        using Cons sound_storage_from_position_def by blast
      from  h2 have g2: ‹subtrie_at_path (SymbolNode {s $$:= m1}) (a # list) (Leaf (insert t sa))⟶ path_of_term t (p @ (a # list))› 
        using Cons sound_storage_from_position_def by blast
      then show ?thesis
        by (smt (verit, ccfv_threshold) h fmupd_lookup g1 g2 list.distinct(1) local.Cons subtrie_at_path.simps trie.sel(3))
    qed
  qed
qed

lemma subtrie_at_path_step_simp:
  ‹subtrie_at_path (SymbolNode m) ((k, val) # ps) (Leaf ts) =
    (∃a m2. m $$ k = Some a ∧ a $$ val = Some m2 ∧ subtrie_at_path m2 ps (Leaf ts))›
  using subtrie_cons subtrie_at_path_step by blast

declare well_structured_cases [rule del]

lemma insert_preserves_sound:
  assumes ws: ‹well_structured f_args›
      and sub: ‹subterm_at_path t p t'›
      and ss: ‹sound_storage_from_position f_args p›
  shows ‹sound_storage_from_position (insert_aux f_args t' t) p›
  using assms
proof (induction f_args t' t arbitrary: p rule: insert_aux.induct)
  case (1 s t t0)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x t0)
  then show ?case
  proof (cases ‹m $$ Star›)
    case None
    have ‹sound_storage_from_position (SymbolNode {Star $$:= {0 $$:= Leaf {t0}}}) p›
      unfolding sound_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1 ts
      assume h0: ‹subtrie_at_path (SymbolNode {symbol.Star $$:= {0 $$:= Leaf {t0}}}) p1 (Leaf (insert t1 ts))›
      then have ‹p1 = [(Star, 0)]›
        by (meson subtrie_string_4)
      then show ‹path_of_term t1 (p @ p1)›
        using "2.prems"(2) h0 path_of_term_var subterm_at_path_path_of_term subtrie_string_1 by fastforce 
    qed
    then show ?thesis using 2 None
      by (auto intro: elim_sound_fp)
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts)›
      using "2.prems"(1) ws_dom_var by blast
    have ‹sound_storage_from_position (SymbolNode ({Star $$:= {0 $$:= Leaf (insert t0 ts)}})) p›
      unfolding sound_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1 ts1
      assume h1: ‹subtrie_at_path (SymbolNode {Star $$:= {0 $$:= Leaf (insert t0 ts)}}) p1 (Leaf (insert t1 ts1))›
      then have ‹p1 = [(Star, 0)]›
        by (meson subtrie_string_4)
      then show ‹path_of_term t1 (p @ p1)›
        using "2.prems" Some h0 h1
        by (smt (verit, ccfv_threshold) insertE insertI1 insert_Diff non_empty_to_set_subtrie path_of_term_var singletonD sound_storage_from_position_def subterm_at_path_path_of_term subtrie_at_path_cases subtrie_at_path_step subtrie_string_1 to_set.simps(1) trie.distinct(1))
    qed
    then have ‹sound_storage_from_position (SymbolNode ({Star $$:= m2(0 $$:= Leaf (insert t0 ts))})) p›
      by (metis (no_types, lifting) "2.prems"(1) dom_res_singleton fmdom'_notD fmfilter_true fmupd_idem option.distinct(1) Some ws_dom_var)
    then show ?thesis using 2 Some h0
      by (auto intro: elim_sound_fp)
  qed
next
  case (3 m f t0)
  then show ?case
  proof (cases ‹m $$ F f 0›)
    case None
    have ‹sound_storage_from_position (SymbolNode {F f 0 $$:= {0 $$:= Leaf {t0}}}) p›
      unfolding sound_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1 ts
      assume h0: ‹subtrie_at_path (SymbolNode { F f 0 $$:= {0 $$:= Leaf {t0}}}) p1 (Leaf (insert t1 ts))›
      then have ‹p1 = [(F f 0, 0)]›
        by (meson subtrie_string_4)
      then show ‹path_of_term t1 (p @ p1)›
        using "3.prems"(2) h0 path_of_term_const subterm_at_path_path_of_term  subtrie_string_1 by fastforce
    qed
    then show ?thesis using 3 None
      by (auto intro: elim_sound_fp)
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts)›
      by (meson "3.prems"(1) ws_dom_const)
    have ‹sound_storage_from_position (SymbolNode ({F f 0 $$:= {0 $$:= Leaf (insert t0 ts)}})) p›
      unfolding sound_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1 ts1
      assume h1: ‹subtrie_at_path (SymbolNode { F f 0 $$:= {0 $$:= Leaf (insert t0 ts)}}) p1 (Leaf (insert t1 ts1))›
      then have ‹p1 = [(F f 0, 0)]›
        by (meson subtrie_string_4)
      then show ‹path_of_term t1 (p @ p1)›
        using "3.prems" h1 Some h0
        by (smt (verit, ccfv_threshold) insertE insertI1 insert_Diff path_of_term.intros(2) sound_storage_from_position_def subterm_at_path_path_of_term subtrie_at_path.simps subtrie_string_1)
    qed
    then have ‹sound_storage_from_position (SymbolNode ({F f 0 $$:= m2(0 $$:= Leaf (insert t0 ts))})) p›
      by (metis (no_types, lifting) "3.prems"(1) dom_res_singleton fmdom'_notD fmfilter_true fmupd_idem option.distinct(1) Some ws_dom_const)
    then show ?thesis using 3 h0 Some 
      by (auto intro: elim_sound_fp)
  qed
next
  case (4 m f a f_args t0)
  then show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    let ?m'= ‹update_entries {$$} [0..<length (a # f_args)]
            (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
    have domm': ‹fmdom' ?m' = {..<length (a # f_args)}›
      by (simp add: atLeast_upt update_entries_dom)
    have hi: ‹⋀i. i < length (a # f_args) ⟹ sound_storage_from_position (insert_aux empty_trie ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
    proof-
      fix i
      assume h1: ‹i < length (a # f_args)›
      show ‹sound_storage_from_position (insert_aux empty_trie ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
      proof -
        have h2: ‹well_structured empty_trie›
          by (simp add: ws_node)
        then have h3: ‹subterm_at_path t0 (p @ [(F f (length (a # f_args)), i)])((a # f_args) ! i)›
          using "4.prems"(2) h1 subsubterm_at_path by fastforce
        then show ?thesis
          using "4.IH" [of i ‹empty_trie› ‹(p @ [(F f (length (a # f_args)), i)])›] h1 h2 
          by (metis sound_storage_from_position_def no_subtrie_in_empty_trie )
      qed
    qed
    have ‹sound_storage_from_position(SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p› 
      unfolding sound_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1 ts
      assume h0: ‹subtrie_at_path (SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p1 (Leaf (insert t1 ts))›
      then obtain i ps where h1: ‹p1 = (F f (length (a # f_args)), i) # ps›
        by (smt (verit) h0 subtrie_string_2 subtrie_at_nil subtrie_at_path.simps)
      then have h2: ‹i < length (a # f_args)› using h0 subtrie_string_3 domm' by blast
      then have ‹sound_storage_from_position (insert_aux empty_trie ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
        using hi by presburger
      then show ‹path_of_term t1 (p @ p1)›
        by (smt (verit, best) append.assoc append.left_neutral append_Cons atLeast_upt distinct_upt domm' elim_sub fmempty_lookup fmupd_lookup h0 h1 h2 rew_upd_entries_none sound_storage_from_position_def subtrie_string_3)
    qed
    then show ?thesis using None
      by (auto simp add: intro: elim_sound_fp "4.prems"(3))
  next
    case (Some m2)
    let ?m'= ‹update_entries m2 [0..<length (a # f_args)]
            (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
    have domm2': ‹fmdom' m2 = {..<length (a # f_args)}›
      by (metis "4.prems"(1) Some length_Cons neq_Nil_conv ws_fmdom')
    then have domm': ‹fmdom' ?m' = {..<length (a # f_args)}›
      by (simp add: atLeast0LessThan update_entries_dom)
    have hi: ‹⋀i tr2. i < length (a # f_args) ⟹ m2 $$ i = Some tr2 ⟹ sound_storage_from_position (insert_aux tr2 ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)) , i)])›
    proof -
      fix i tr2
      assume h1: ‹i < length (a # f_args)›
      assume h2: ‹m2 $$ i = Some tr2›
      then have h3: ‹well_structured tr2›
        by (metis "4.prems"(1) Some length_greater_0_conv list.distinct(1) ws_subtree)
      then  have ‹subterm_at_path t0  (p @ [(F f (length (a # f_args)) , i)])((a # f_args) ! i)›
        using "4.prems"(2) h1 subsubterm_at_path by fastforce 
      then show ‹sound_storage_from_position (insert_aux tr2 ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
        using "4.IH" [of i tr2 ‹(p @ [(F f (length (a # f_args)), i)])›] h1 h2 h3
        by (metis "4.prems"(3) Some sound_storage_from_position_subtrie)
    qed
    have ‹sound_storage_from_position (SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p› 
      unfolding sound_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1 ts
      assume h0: ‹subtrie_at_path (SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p1 (Leaf (insert t1 ts))›
      then have ‹p1 ≠ []›
        using subtrie_at_nil by auto
      then obtain i ps where h1: ‹p1 = (F f (length (a # f_args)), i) # ps›
        using h0 subtrie_string_2 subtrie_at_path.simps [of ‹(SymbolNode {F f (length (a # f_args)) $$:= ?m'})› p1 ‹(Leaf (insert t1 ts))›] by blast
      then have h2: ‹i < length (a # f_args)› using h0 subtrie_string_3 domm' by blast
      then obtain tr2 where h42: ‹m2 $$ i = Some tr2›
        by (metis h2 fmdom'_notI not_None_eq lessThan_iff domm2')
      then have h3: ‹?m' $$ i = Some (insert_aux tr2 ((a # f_args) ! i) t0)›
        using insert_some_image [of i f_args m2] domm2' h2 by (simp add: atLeast_upt)
      have h4: ‹sound_storage_from_position (insert_aux tr2 ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
        using h2 h42 hi by auto
      have h5: ‹subtrie_at_path (insert_aux tr2 ((a # f_args) ! i) t0) ps (Leaf (insert t1 ts))›
        using h0 h1 h3 h42
        by (metis (no_types, lifting) elim_sub fmupd_lookup)
      then show ‹path_of_term t1 (p @ p1)›
        by (metis append.assoc append_Cons append_Nil h1 h4 sound_storage_from_position_def)
    qed
    then show ?thesis using Some
      by (auto simp add: Some intro: elim_sound_fp "4.prems"(3))
  qed
qed

lemma elim_complete_fp:
  assumes ‹m $$ s = None›
      and ‹complete_storage_from_position (SymbolNode m) p›
      and ‹complete_storage_from_position (SymbolNode {s $$:= a}) p› 
    shows ‹complete_storage_from_position (SymbolNode (m(s $$:= a))) p›
  unfolding complete_storage_from_position_def
proof (intro allI impI)
  fix t p2
  assume h0: ‹t ∈ to_set (SymbolNode (m(s $$:= a)))› and h1: ‹path_of_term t (p @ p2)›
  then have ‹p2 ≠ []›
    by (smt (verit, del_insts) assms complete_storage_from_position_def entry_to_set fmupd_lookup subtrie_at_nil to_set_exists_entry)
  then obtain s2 i p3 where h2: ‹p2 = (s2, i) # p3›
    by (metis old.prod.exhaust list_4_cases)
  then show ‹∃ts. subtrie_at_path (SymbolNode (m(s $$:= a))) p2 (Leaf (insert t ts))›
  proof (cases ‹s = s2›)
    case True
    then show ?thesis
      using h0 h1 h2 assms unfolding complete_storage_from_position_def
      by (smt (verit, del_insts) entry_to_set fmupd_lookup option.distinct(1) subtrie_at_path_step subtrie_cons to_set_exists_entry)
  next
    case False
    then show ?thesis
      using h0 h1 h2 assms unfolding complete_storage_from_position_def
      by (smt (verit, del_insts) entry_to_set fmupd_lookup subtrie_at_path_step subtrie_cons subtrie_string_2 to_set_exists_entry)
  qed
qed

lemma complete_var:
  assumes ‹well_structured (SymbolNode m)›
      and ‹subterm_at_path t0 p (Var x)›
      and ‹complete_storage_from_position (SymbolNode m) p›
    shows ‹complete_storage_from_position (insert_aux (SymbolNode m) (Var x) t0) p›
  using assms
proof (cases ‹m $$ Star›)
  case None
  have ‹⋀p2. path_of_term t0 (p @ p2) ⟹
          ∃s. subtrie_at_path (SymbolNode {symbol.Star $$:= {0 $$:= Leaf {t0}}}) p2 (Leaf (insert t0 s))› 
    using assms
    by (metis (no_types, lifting) fmupd_lookup path_var path_of_subterm subtrie_at_path_empty subtrie_at_path_step)
  then have ‹complete_storage_from_position (SymbolNode {symbol.Star $$:= {0 $$:= Leaf {t0}}}) p›
    by (simp add: fmran'_alt_def fmran_singleton complete_storage_from_position_def)
  then show ?thesis 
    using assms None by (auto intro: elim_complete_fp) 
next
  case (Some m2)
  then show ?thesis
  proof (cases ‹m2 $$ 0›)
    case None
    then show ?thesis
      using Some assms(1) ws_dom_var by fastforce
  next
    case s2: (Some tr2)
    then show ?thesis
    proof (cases tr2)
      case (Leaf ts)
      then show ?thesis unfolding complete_storage_from_position_def
      proof (intro allI impI)
        fix t1 p1
        assume h0: ‹t1 ∈ to_set (insert_aux (SymbolNode m) (Var x) t0)›
           and h1: ‹path_of_term t1 (p @ p1)›
        consider (a) ‹t1 = t0›
               | (b) ‹t1 ∈ to_set (SymbolNode m)›
          using assms(1) insert_aux_subset h0 by blast
        then show ‹∃ts. subtrie_at_path (insert_aux (SymbolNode m) (Var x) t0) p1 (Leaf (insert t1 ts))›
        proof cases
          case a
          then have ‹p1 = [(Star,0)]›
            by (metis assms(2) h1 path_var path_of_subterm)
          then show ?thesis using h1 a Leaf s2 Some
            by (simp, meson fmupd_lookup subtrie_at_path_empty subtrie_at_path_step_simp)
        next
          case b
          then obtain ts1 where h3: ‹subtrie_at_path (SymbolNode m) p1 (Leaf (insert t1 ts1))›
            by (meson assms(3) complete_storage_from_position_def h1)
          then have ‹p1 ≠ []›
            using subtrie_at_nil by auto
          then obtain sym i list where h4: ‹p1 = (sym, i) # list›
            by (metis old.prod.inject delete_aux.cases)
          then show ?thesis
          proof (cases sym)
            case Star
            then have h5: ‹i = 0 ∧ list = []›
              using h1 assms end_path_var h1 h4 by blast 
            then have h6: ‹p1 = [(Star,0)]›
              using Star h4 by blast
            then obtain ts2 where t1: ‹insert t0 ts = insert t1 ts2›
              using Some s2 h3 h5 Leaf Star assms  
              by (metis (no_types, lifting) insert_absorb insert_iff subtrie_entry_to_set to_set.simps(1))
            then show ?thesis
              by (clarsimp simp add: Some s2 h6, metis (no_types, opaque_lifting) Leaf fmupd_lookup insert_leaf.simps(1) subtrie_at_path.simps)
          next
            case (F f n)
            obtain tr2 m2 where ‹m $$ sym = Some tr2 ∧ tr2 $$ i = Some m2 ∧ subtrie_at_path m2 list (Leaf (insert t1 ts1))›
              using subtrie_cons h3 h4 by metis
            then have ‹subtrie_at_path (insert_aux (SymbolNode m) (Var x) t0) p1 (Leaf (insert t1 ts1))›
              using subtrie_at_path.simps s2 h4 F by fastforce
            then show ?thesis 
              by meson 
          qed
        qed
      qed
    next
      case (SymbolNode m3)
      then show ?thesis
        using Some assms(1) s2 ws_dom_var by fastforce 
    qed
  qed
qed 

lemma complete_const:
  assumes ‹well_structured (SymbolNode m)›
      and ‹subterm_at_path t0 p (Fun f [])›
      and ‹complete_storage_from_position (SymbolNode m) p›
    shows ‹complete_storage_from_position (insert_aux (SymbolNode m) (Fun f []) t0) p›
  using assms
proof (cases ‹m $$ F f 0›)
  case None
  have ‹⋀p2. path_of_term t0 (p @ p2) ⟹
          ∃s. subtrie_at_path (SymbolNode {F f 0 $$:= {0 $$:= Leaf {t0}}}) p2 (Leaf (insert t0 s))› 
    by  (metis (no_types, lifting) assms(2) fmupd_lookup path_const path_of_subterm subtrie_at_path_empty subtrie_at_path_step)
  then  have ‹complete_storage_from_position (SymbolNode {F f 0 $$:= {0 $$:= Leaf {t0}}}) p›
    by (simp add: fmran'_alt_def fmran_singleton complete_storage_from_position_def)
  then show ?thesis 
    using assms None by (auto intro: elim_complete_fp) 
next
  case (Some m2)
  then show ?thesis
  proof (cases ‹m2 $$ 0›)
    case None
    then show ?thesis
      using Some assms(1) ws_dom_const by fastforce
  next
    case s2: (Some tr2)
    then show ?thesis
    proof (cases tr2)
      case (Leaf ts)
      then show ?thesis
        unfolding complete_storage_from_position_def
      proof (intro allI impI)
        fix t1 p1
        assume h0: ‹t1 ∈ to_set (insert_aux (SymbolNode m) (Fun f []) t0)›
        assume h1: ‹path_of_term t1 (p @ p1)›
        consider (a) ‹t1 = t0›
              |  (b) ‹t1 ∈ to_set (SymbolNode m)›
          by (meson assms(1) h0 in_mono insertE insert_aux_subset)
        then show ‹∃ts1. subtrie_at_path (insert_aux (SymbolNode m) (Fun f []) t0) p1 (Leaf (insert t1 ts1))›
        proof cases
          case a
          then have ‹p1 = [(F f 0,0)]›
            by (metis assms(2) h1 path_const path_of_subterm)
          then show ?thesis using h1 a Leaf s2 Some
            by (simp, meson fmupd_lookup subtrie_at_path_empty subtrie_at_path_step_simp)
        next
          case b
          then obtain ts1 where h2: ‹subtrie_at_path (SymbolNode m) p1 (Leaf (insert t1 ts1))›
            by (meson assms(3) h1 complete_storage_from_position_def)
          then have ‹p1 ≠ []›
            using subtrie_at_nil by auto
          then obtain s i ps where h3: ‹p1 = (s, i) # ps›
            by (metis old.prod.inject delete_aux.cases)
          then show ?thesis
          proof (cases ‹s = F f 0›)
            case True
            then have h4: ‹i = 0 ∧ ps = []›
              by (metis h1 h3 end_path_const)
            then have h5: ‹p1 = [(F f 0,0)]›
              using True h3 by blast
            then obtain s where t1: ‹insert t0 ts = insert t1 s›
              using Some s2 h2 h4 Leaf True assms  
              by (metis (no_types, lifting) insert_absorb insert_iff subtrie_entry_to_set to_set.simps(1))
            then show ?thesis
              by (simp add: Some s2 h5, metis (no_types, opaque_lifting) Leaf fmupd_lookup insert_leaf.simps(1) subtrie_at_path.simps)
          next
            case False
            obtain tr3 m3 where ‹m $$ s = Some tr3 ∧ tr3 $$ i = Some m3 ∧ subtrie_at_path m3 ps (Leaf (insert t1 ts1))›
              by (metis h2 h3 subtrie_cons)
            then have ‹subtrie_at_path (insert_aux (SymbolNode m) (Fun f []) t0) p1 (Leaf (insert t1 ts1))›
              by (simp add: h3, metis False fmupd_lookup subtrie_at_path_step_simp)
            then show ?thesis
              by meson 
          qed
        qed
      qed
    next
      case (SymbolNode m3)
      then show ?thesis
        using Some assms(1) s2 ws_dom_const by fastforce 
    qed
  qed
qed 

lemma exists_term_at_end_path: 
  assumes ‹path_of_term t ((F f n, b) # list)›
      and ‹k < n› 
    shows ‹∃list2. path_of_term t ((F f n, k) # list2)› 
proof (cases t)
  case (Var x)
  then show ?thesis  using assms by(simp add: path_var)
next
  case (Fun f f_args)
  then show ?thesis
  proof (cases f_args)
    case Nil
    then show ?thesis using assms 
      by (simp add: Fun path_const)
  next
    case (Cons a f_args')
    then show ?thesis using assms Fun path_func 
      by (metis exists_path fst_conv length_Cons list.distinct(1) list.sel(1) path_of_term_func symbol.inject)
  qed
qed

lemma insert_preserves_complete:
  assumes ‹well_structured f_args›
      and ‹subterm_at_path t p t'›
      and ‹complete_storage_from_position f_args p›
    shows ‹complete_storage_from_position (insert_aux f_args t' t) p›
  using assms
proof (induction f_args t' t arbitrary:p rule:insert_aux.induct)
  case (1 s t t0)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x t0)
  then show ?case 
    by (meson complete_var)
next
  case (3 m f t0)
  then show ?case
    by (meson complete_const)
next
  case (4 m f a f_args t0)
  then show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    let ?m' = ‹update_entries {$$} [0..<length (a # f_args)]
         (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined)
         empty_trie›
    have dom': ‹fmdom'?m' = {..<length (a # f_args)}›
      by (simp add: atLeast_upt update_entries_dom)
    have h0: ‹⋀i. i < length (a # f_args) ⟹ complete_storage_from_position (insert_aux empty_trie ((a # f_args) ! i) t0) (p @ [( F f (length (a # f_args)), i)])›
      by (metis "4.IH" "4.prems"(2) complete_storage_from_position_def fmempty_lookup option.distinct(1) subsubterm_at_path
          to_set_exists_entry well_structured_empty_trie)
    then have ‹complete_storage_from_position (SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p›
      unfolding complete_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1
      assume ‹t1 ∈ to_set (SymbolNode {F f (length (a # f_args)) $$:= ?m'})›
      then obtain tr2 j where h1: ‹?m' $$ j = Some tr2 ∧ t1 ∈ to_set tr2 ∧ j < length (a # f_args)›
        using fmran'_singleton [of ‹F f (length (a # f_args))›  ?m'] dom' by fastforce
      then have defxa: ‹tr2 = insert_aux empty_trie ((a # f_args) ! j) t0›
        using insert_none_image by fastforce
      then have h2: ‹t1 = t0›
        by (metis insert_aux_subset h1 empty_iff in_mono insert_iff no_subtrie_in_empty_trie non_empty_to_set_subtrie well_structured_empty_trie)
      assume h3: ‹path_of_term t1 (p @ p1)›
      then have ‹path_of_term (Fun f (a # f_args)) p1›
        using h2 path_of_subterm "4.prems"(2) by fast
      then obtain k ps where h4: ‹p1 = ((F f (length (a # f_args))), k) # ps ∧ k < length (a # f_args) ∧ path_of_term ((a # f_args) ! k) ps›
        using path_of_term.simps [of ‹Fun f (a # f_args)› p1] by blast
      then have ‹path_of_term t0 (p @ [(F f (length (a # f_args)), k)] @ ps)› using h2 h3 by force
      moreover have ‹t0 ∈ to_set (insert_aux empty_trie ((a # f_args) ! k) t0)›
        by (simp add: insert_aux_adds_element)
      ultimately obtain ts where ‹subtrie_at_path (insert_aux empty_trie ((a # f_args) ! k) t0) ps (Leaf (insert t0 ts))›
        using h0 [of k] h4 unfolding complete_storage_from_position_def by auto
      moreover have ‹?m' $$ k = Some (insert_aux empty_trie ((a # f_args) ! k) t0)›
        using h4 by (simp add: rew_upd_entries_none)
      ultimately show ‹∃ts. subtrie_at_path (SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p1 (Leaf (insert t1 ts))› using h2 h4
        by (smt (verit, best) fmupd_lookup subtrie_at_path.simps)
    qed
    then show ?thesis using elim_complete_fp None "4.prems"(3) by auto
  next
    case (Some m2)
    let ?m' = ‹update_entries m2 [0..<length (a # f_args)]
         (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined)
         empty_trie›
    have domm2: ‹fmdom' m2 = {0..<length (a # f_args)}›
      by (metis ws_fmdom' set_upt Some "4.prems"(1) atLeast_upt list.simps(3))
    then  have dom': ‹fmdom'?m' = {0..<length (a # f_args)}›
      using update_entries_dom by (metis atLeastLessThan_upt sup.idem)
    have fmran_image: ‹⋀i. i < length (a # f_args) ⟹ ?m' $$ i = Some (insert_aux (m2 $$! i) ((a # f_args) ! i) t0)›
      by (simp add: domm2 insert_some_image)
    have h0: ‹⋀i tr2. i < length (a # f_args) ⟹ m2 $$ i = Some tr2 ⟹ complete_storage_from_position (insert_aux tr2 ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
    proof - 
      fix i tr2
      assume h1: ‹i < length (a # f_args)›
         and h2: ‹m2 $$ i = Some tr2› 
      then have h3: ‹well_structured tr2› 
        using Some h1 "4.prems"(1) ws_subtree by fastforce
      have h4: ‹subterm_at_path t0 (p @ [( F f (length (a # f_args)), i)]) ((a # f_args) ! i)›
        using "4.prems"(2) h1 subsubterm_at_path by fastforce 
      have ‹complete_storage_from_position tr2 (p @ [(F f (length (a # f_args)), i)])›
        by (metis "4.prems"(3) h2 Some complete_storage_from_position_subtrie)
      then show ‹complete_storage_from_position (insert_aux tr2 ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
        using 4 h1 h3 h4 by auto
    qed
    show ?thesis unfolding complete_storage_from_position_def
    proof (intro allI impI)
      fix t1 p1
      assume h1: ‹t1 ∈ to_set (insert_aux (SymbolNode m) (Fun f (a # f_args)) t0)›
      assume h2: ‹path_of_term t1 (p @ p1)›
      then obtain s i ps where h3: ‹p1 = (s, i) # ps›
        by (metis "4.prems"(2) surj_pair sub_path_not_path append.right_neutral neq_Nil_conv)
      then show ‹∃ts. subtrie_at_path (insert_aux (SymbolNode m) (Fun f (a # f_args)) t0) p1 (Leaf (insert t1 ts))›
      proof (cases ‹s = F f (length (a # f_args))›)
        case True
        then have h4: ‹i < length (a # f_args)›
          using h2 h3 by (simp add: path_of_term_element)
        then obtain tr2 where h5: ‹m2 $$ i = Some tr2› using domm2 fmlookup_dom'_iff by force
        then have ‹well_structured tr2›
          by (metis "4.prems"(1) Some length_greater_0_conv list.distinct(1) ws_subtree)
        then have ‹t1 ∈ to_set (insert_aux tr2 ((a # f_args) ! i) t0)›
          by (smt (verit, best) "4.prems"(1,3) Some True complete_storage_from_position_def h1 h2 h3 h5 insert_aux_adds_element insert_aux_keeps_elements insert_aux_subset insert_iff
              subsetD subtrie_entry_to_set)
        moreover have ‹complete_storage_from_position (insert_aux tr2 ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
          using h0 [of i] h3 h4 h5 by force
        ultimately obtain ts where ‹subtrie_at_path (insert_aux tr2 ((a # f_args) ! i) t0) ps (Leaf (insert t1 ts))›
          using True h2 h3 unfolding complete_storage_from_position_def by auto
        then have ‹subtrie_at_path (SymbolNode (m(F f (length (a # f_args)) $$:= ?m'))) p1 (Leaf (insert t1 ts))›
          by (metis (no_types, lifting) h4 fmran_image fmupd_lookup True h3 h5 option.sel subtrie_at_path_step_simp)
        moreover have ‹insert_aux (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (m(F f (length (a # f_args)) $$:= ?m'))›
          using Some by auto
        ultimately show ?thesis by auto
      next
        case False
        let ?m' = ‹update_entries m2 [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then insert_aux tr ((a # f_args) ! i) t0 else undefined) empty_trie›
        obtain ts where ‹subtrie_at_path (SymbolNode m) p1 (Leaf (insert t1 ts))›
          by (metis False "4.prems"(1-3) path_func path_of_subterm insert_aux_subset add.right_neutral add_Suc_right complete_storage_from_position_def fst_conv h1 h2 h3 in_mono insert_iff list.sel(1) list.size(4))
        then obtain m3 tr2 where ‹m $$ s = Some m3 ∧ m3 $$ i = Some tr2 ∧ subtrie_at_path tr2 ps (Leaf (insert t1 ts))›
          using subtrie_at_path.simps [of ‹SymbolNode m› p1 ‹Leaf (insert t1 ts)›] h3 by blast
        then have ‹subtrie_at_path (SymbolNode (m(F f (length (a # f_args)) $$:= ?m'))) p1 (Leaf (insert t1 ts))›
          using h3 False subtrie_at_path_step [of ‹m(F f (length (a # f_args)) $$:= ?m')› s m3 i tr2 ps ‹Leaf (insert t1 ts)›] by fastforce
        then show ?thesis using Some by auto
      qed
    qed
  qed
qed

subsection ‹Term removal›

fun remove_leaf :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) trie option› where
  ‹remove_leaf (Leaf ts) t = (if ts = {t} then None else Some (Leaf (ts - {t})))›
| ‹remove_leaf (SymbolNode m) t = undefined›

function (sequential) remove_aux :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) term ⇒ ('f, 'v) trie option› where
  ‹remove_aux (Leaf ts) t t0 = undefined›
| ‹remove_aux (SymbolNode m) (Var x) t0 =
   (let nm = update_or_remove_entry m Star (λm2. let nm2 = update_or_remove_entry m2 0 (λtr. remove_leaf tr t0)
                                                 in if nm2 = {$$} then None else Some nm2)
    in if nm = {$$} then None else Some (SymbolNode nm))›
| ‹remove_aux (SymbolNode m) (Fun f []) t0 = 
   (let nm = update_or_remove_entry m (F f 0) (λm2. let nm2 = update_or_remove_entry m2 0 (λtr. remove_leaf tr t0)
                                                    in if nm2 = {$$} then None else Some nm2)
    in if nm = {$$} then None else Some (SymbolNode nm))›
| ‹remove_aux (SymbolNode m) (Fun f f_args) t0 =
   (let nm = update_or_remove_entry m (F f (length f_args)) (λm2. let nm2 = update_or_remove_entries m2 [0..<length f_args]
                                                                                 (λi tr. if i < length f_args
                                                                                         then remove_aux tr (f_args ! i) t0
                                                                                         else undefined)
                                                                       in if nm2 = {$$} then None else Some nm2)
    in if nm = {$$} then None else Some (SymbolNode nm))›
  by pat_completeness auto
termination
proof (relation ‹measure (λ(p, q, r). depth q)›)
  show ‹wf (measure (λ(p, q, r). depth q))› by blast
next
  show ‹⋀m f a f_args t0 x xa xb. xa < length (a # f_args) ⟹ ((xb, (a # f_args) ! xa, t0), SymbolNode m, Fun f (a # f_args), t0) ∈ measure (λ(p, q, r). depth q)›
    by (clarsimp; metis List.finite_set Max_ge finite_imageI image_eqI image_insert le_imp_less_Suc length_Cons list.simps(15) nth_mem)
qed

fun remove_term :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) term ⇒ ('f, 'v) trie› where
  ‹remove_term tr t t0 = (case remove_aux tr t t0 of Some x ⇒ x | None ⇒ empty_trie)›

lemma update_or_remove_entries_nth:
  assumes ‹fmdom' m = {0..<length (a # f_args)}›
      and ‹k < length (a # f_args)›
    shows ‹update_or_remove_entries m [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined) $$ k = remove_aux (m $$! k) ((a # f_args) ! k) t0› 
  by (smt (verit) assms atLeastLessThan_iff distinct_upt fmdom'_notI option.collapse set_upt update_or_remove_entries_some zero_order(1))

lemma exists_in_non_fmempty:
  assumes ‹m ≠ {$$}›
  shows ‹∃x∈fmdom' m. ∃z. m $$ x = Some z›
  using assms by (metis fmap_ext fmdom'I fmempty.rep_eq not_Some_eq)

lemma remove_keeps_elements:
  assumes ‹well_structured tr›
    shows ‹to_set tr - {t0} ⊆ to_set (remove_term tr t t0)›
proof
  fix u
  assume ‹u ∈ to_set tr - {t0}›
  then show ‹u ∈ to_set (remove_term tr t t0)›
    using assms
  proof (induction tr t t0 rule: remove_aux.induct)
    case (1 ts t t0)
    then show ?case
      using well_structured.simps by blast
  next
    case (2 m x t0)
    then obtain s m2 i tr where h0: ‹m $$ s = Some m2 ∧ m2 $$ i = Some tr ∧ u ∈ to_set tr ∧ u ≠ t0›
      using to_set_exists_entry by blast
    show ?case
    proof (cases ‹s = Star›)
      case True
      then obtain ts where h1: ‹i = 0 ∧ tr = Leaf ts ∧ u ∈ ts› using h0
        by (metis "2.prems"(2) fmdom'I option.sel singletonD to_set.elims trie.distinct(1) ws_dom_var)
      then have h2: ‹remove_leaf tr t0 ≠ None›
        using h0 by auto
      then have ‹u ∈ to_set (SymbolNode (m(s $$:= m2(0 $$:= Leaf (ts - {t0})))))›
        by (metis h0 entry_to_set fmupd_lookup to_set.simps(1) insert_iff insert_Diff_single h1)
      then show ?thesis using h0 h1 h2 True by auto
    next
      case False
      then have ‹⋀v0. m(Star $$:= v0) $$ s = Some m2› using h0 by auto
      then have h1: ‹⋀v0. u ∈ to_set (SymbolNode (m(Star $$:= v0)))› using h0 entry_to_set by blast
      have ‹fmdrop Star m $$ s = Some m2› using h0 False by auto
      then have h2: ‹u ∈ to_set (SymbolNode (fmdrop Star m))› using h0 entry_to_set by blast
      have ‹u ∈ to_set (SymbolNode m) ∧ u ≠ t0› using 2 by auto
      then show ?thesis
         by (simp, smt (verit, del_insts) h1 h2 option.case_eq_if option.simps(5))
    qed
  next
    case (3 m f t0)
    then obtain s m2 i tr where h0: ‹m $$ s = Some m2 ∧ m2 $$ i = Some tr ∧ u ∈ to_set tr›
      using to_set_exists_entry by blast
    show ?case
    proof (cases ‹s = F f 0›)
      case True
      then obtain ts where h1: ‹i = 0 ∧ tr = Leaf ts ∧ u ∈ ts› using h0
        by (metis "3.prems"(2) fmdom'I option.sel singletonD to_set.elims trie.distinct(1) ws_dom_const)
      then have h2: ‹remove_leaf tr t0 ≠ None›
        using "3.prems"(1) by auto
      then have ‹u ∈ to_set (SymbolNode (m(s $$:= m2(0 $$:= Leaf (ts - {t0})))))›
        by (metis entry_to_set fmupd_lookup to_set.simps(1) "3.prems"(1) h1 Diff_iff)
      then show ?thesis using h0 h1 h2 True by auto
    next
      case False
      then have ‹⋀v0. m(F f 0 $$:= v0) $$ s = Some m2› using h0 by auto
      then have h1: ‹⋀v0. u ∈ to_set (SymbolNode (m(F f 0 $$:= v0)))› using h0 entry_to_set by blast
      have ‹(fmdrop (F f 0) m) $$ s = Some m2› using h0 False by auto
      then have h2: ‹u ∈ to_set (SymbolNode (fmdrop (F f 0) m))› using h0 entry_to_set by blast
      have ‹u ∈ to_set (SymbolNode m) ∧ u ≠ t0› using 3 by auto
      then show ?thesis
        by (simp, smt (verit, del_insts) h1 h2 option.case_eq_if option.simps(5))
    qed
  next
    case (4 m f a f_args t0)
    then obtain s m2 i tr where h0: ‹m $$ s = Some m2 ∧ m2 $$ i = Some tr ∧ u ∈ to_set tr›
      using to_set_exists_entry by blast
    then show ?case
    proof (cases ‹s = F f (length (a # f_args))›)
      case True
      then have h1: ‹i < length (a # f_args)› using h0
        using "4.prems"(2) ws_dom_fun2 by force
      then have ‹well_structured tr› using "4.prems"(2) h0 ws_subtree True by fast
      then have ‹u ∈ to_set (remove_term tr ((a # f_args) ! i) t0)› using 4 h0 h1 by blast
      then obtain tr2 where h2: ‹remove_aux tr ((a # f_args) ! i) t0 = Some tr2 ∧ u ∈ to_set tr2›
        by (metis remove_term.simps exists_leaf no_subtrie_in_empty_trie option.case_eq_if option.collapse)
      let ?upre = ‹update_or_remove_entries m2 [0..<Suc (length f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›
      have h3: ‹?upre $$ i = Some tr2 ∧ u ∈ to_set tr2›
        using h0 h1 h2 update_or_remove_entries_some [of ‹[0..<Suc (length f_args)]› i m2 tr] by auto
      then have h4: ‹u ∈ to_set (SymbolNode (m(s $$:= ?upre)))›
        using entry_to_set [of ‹m(s $$:= ?upre)› s ?upre i tr2 u] by auto
      have ‹?upre ≠ {$$}› using h3 by auto
      then show ?thesis using h0 h4 True by auto
    next
      case False
      then have ‹⋀v0. m(F f (Suc (length f_args)) $$:= v0) $$ s = Some m2› using h0 by auto
      then have h1: ‹⋀v0. u ∈ to_set (SymbolNode (m(F f (Suc (length f_args)) $$:= v0)))› using h0 entry_to_set by blast
      have ‹(fmdrop (F f (Suc (length f_args))) m) $$ s = Some m2› using h0 False by auto
      then have h2: ‹u ∈ to_set (SymbolNode (fmdrop (F f ((Suc (length f_args)))) m))› using h0 entry_to_set by blast
      have ‹u ∈ to_set (SymbolNode m) ∧ u ≠ t0› using 4 by auto
      then show ?thesis
        by (simp, smt (verit, del_insts) h1 h2 option.case_eq_if option.simps(5))
    qed
  qed
qed

lemma remove_term_subset:
  assumes ‹well_structured tr›
      and ‹u ∈ to_set (remove_term tr t t0)›
    shows ‹u ∈ to_set tr›
  using assms 
proof (induction tr t t0  rule: remove_aux.induct)
  case (1 s t t0)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x t0)
  then obtain m2 where h0: ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode m2›
    by (smt (verit, ccfv_SIG) option.simps(4,5) remove_aux.simps(2) remove_term.elims)
  show ?case
  proof (cases ‹m $$ Star›)
    case None
    then have ‹m = m2›
      by (smt (verit, ccfv_SIG) h0 option.simps(4,5) remove_aux.simps(2) remove_term.simps trie.sel(3) update_or_remove_entry.simps)
    then show ?thesis using h0 2 by auto
  next
    case (Some m3)
    then obtain ts where h1: ‹m3 $$ 0 = Some (Leaf ts)›
      using "2.prems"(1) ws_dom_var by blast
    show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then consider (a) ‹m2 = fmdrop Star m›
                  | (b) ‹m2 = m(Star $$:= fmdrop 0 m3)›
        using Some h0 h1
        by (simp, smt (verit, best) option.simps(4,5) trie.inject(2))
      then show ?thesis
      proof (cases)
        case a
        then show ?thesis using 2 h0
          by (metis entry_to_set fmlookup_drop option.distinct(1) to_set_exists_entry)
      next
        case b
        then show ?thesis using 2 h0
          by (metis (mono_tags, lifting) Diff_iff Some entry_to_set fmdom'_drop fmdom'_notD fmupd_lookup option.distinct(1) option.sel to_set_exists_entry ws_dom_var)
      qed
    next
      case False
      then have ‹m2 = m(Star $$:= m3(0 $$:= Leaf (ts - {t0})))›
        using Some h0 h1 by simp
      then show ?thesis using 2 h0
        by (smt (verit, ccfv_threshold) Diff_empty Diff_insert0 Some entry_to_set fmupd_lookup h1 insert_Diff insert_iff option.inject to_set.simps(1) to_set_exists_entry)
    qed
  qed
next
  case (3 m f t0)
  then obtain m2 where h0: ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode m2›
    by (smt (verit, best) option.case_eq_if option.sel remove_aux.simps(3) remove_term.simps)
  show ?case
  proof (cases ‹m $$ F f 0›)
    case None
    then have ‹m = m2›
      by (smt (verit, ccfv_SIG) h0 option.simps(4,5) remove_aux.simps(3) remove_term.simps trie.sel(3) update_or_remove_entry.simps)
    then show ?thesis using h0 3 by auto
  next
    case (Some m3)
    then obtain ts where h1: ‹m3 $$ 0 = Some (Leaf ts)›
      using "3.prems"(1) ws_dom_const by metis
    show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then consider (a) ‹m2 = fmdrop (F f 0) m›
        | (b) ‹m2 = m(F f 0 $$:= fmdrop 0 m3)›
        using Some h0 h1 by (simp, smt (verit, best) option.simps(4,5) trie.sel(3))
      then show ?thesis
      proof (cases)
        case a
        then show ?thesis using 3 h0
          by (metis entry_to_set fmlookup_drop option.distinct(1) to_set_exists_entry)
      next
        case b
        then show ?thesis using 3 h0
          by (metis (mono_tags, lifting) Diff_iff Some entry_to_set fmdom'_drop fmdom'_notD fmupd_lookup option.distinct(1) option.sel to_set_exists_entry ws_dom_const)
      qed
    next
      case False
      then have ‹m2 = m(F f 0 $$:= m3(0 $$:= Leaf (ts - {t0})))›
        using Some h0 h1 by simp
      then show ?thesis using 3 h0
        by (smt (verit, ccfv_threshold) Diff_empty Diff_insert0 Some entry_to_set fmupd_lookup h1 insert_Diff insert_iff option.inject to_set.simps(1) to_set_exists_entry)
    qed
  qed
next
  case (4 m f a f_args t0)
  then obtain m2 where h0: ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode m2›
    by (smt (verit, best) option.case_eq_if option.sel remove_aux.simps(4) remove_term.simps)
  show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    then have ‹m = m2›
      by (smt (verit, ccfv_SIG) h0 option.simps(4,5) remove_aux.simps(4) remove_term.simps trie.sel(3) update_or_remove_entry.simps)
    then show ?thesis using h0 4 by auto
  next
    case (Some m3)
    let ?m' = ‹update_or_remove_entries m3 [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›
    have domm3: ‹fmdom' m3 = {0..<length (a # f_args)}›
      by (metis "4.prems"(1) Some atLeast_upt list.distinct(1) set_upt ws_fmdom')
    then have domm: ‹fmdom' ?m' ⊆ fmdom' m3›
      using update_or_remove_entries_dom by force
    then have in_d: ‹⋀i. i ∈ fmdom' ?m' ⟹ ?m' $$ i = remove_aux (m3 $$! i) ((a # f_args) ! i) t0›
      by (metis (no_types, lifting) domm3 ext atLeastLessThan_iff subsetD update_or_remove_entries_nth)
    show ?thesis
    proof (cases ‹?m' = {$$}›)
      case True
      then show ?thesis
        using "4.prems"(2) True Some
        by (auto simp add: Let_def split: if_splits; metis (no_types, lifting) fmlookup_drop fmlookup_ran'_iff option.discI)
    next
      case False
      obtain s m1 tr2 where r: ‹m(F f (length (a # f_args)) $$:= ?m') $$ s = Some m1 ∧ tr2 ∈ fmran' m1 ∧ u ∈ to_set tr2›
        using "4.prems"(2) Some False by auto
      then show ?thesis 
      proof (cases ‹s = F f (length (a # f_args))›)
        case True
        then have g: ‹m1 = ?m'›
          using r by auto
        obtain m4 i where t0: ‹m1 $$ i = Some m4› and t2: ‹u ∈ to_set m4›
          using r by blast
        then have hj: ‹i < length (a # f_args)›
          using g domm domm3 by force
        then have th0: ‹m4 = remove_term (m3 $$! i) ((a # f_args) ! i) t0›
          using t0 fmdom'I in_d by (auto simp add: fmlookup_dom'_iff g)
        then show ?thesis
          using "4.prems"(2) True r t0 t2
          by (metis (no_types, lifting) "4.IH" "4.prems"(1) Some entry_to_set fmdom'_notI hj length_Cons length_greater_0_conv list.distinct(1) option.collapse th0 ws_dom_fun ws_subtree)
      next
        case False
        then show ?thesis
          using r entry_to_set by fastforce
      qed
    qed
  qed
qed

lemma remove_deletes_element:
  assumes ‹well_structured tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path t0 p t› 
      and ‹remove_aux tr t t0 = Some tr2›
    shows ‹t0 ∉ to_set tr2›
  using assms
proof (induction tr t t0 arbitrary: p tr2 rule: remove_aux.induct)
  case (1 ts t t0)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x t0)
  have h0: ‹path_of_term t0 (p @ [(Star, 0)])›
    by (meson "2.prems"(3) path_var subterm_at_path_path_of_term)
  then show ?case
  proof (cases ‹m $$ Star›)
    case None
    then show ?thesis
      using 2
      by (clarsimp, metis exists_leaf option.distinct(1) option.inject path_var sound_storage_from_position_def path_of_subterm subtrie_cons)
  next
    case (Some m2)
    then obtain ts where h1: ‹m2 $$ 0 = Some (Leaf ts)›
      by (metis ws_dom_var "2.prems"(1))
    have h2: ‹⋀m3 tr3. m3 ∈ fmran' (fmdrop Star m) ⟹ tr3 ∈ fmran' m3 ⟹ t0 ∈ to_set tr3 ⟹ False›
    proof (elim fmran'E)
      fix m3 tr3 s i
      assume ‹t0 ∈ to_set tr3› and ‹fmdrop Star m $$ s = Some m3› and ‹m3 $$ i = Some tr3›
      then have ‹m $$ s = Some m3 ⟹ s = Star›
        by (smt (verit, del_insts) "2.prems"(2,3) h0 sound_storage_from_position_def path_var exists_leaf [of t0 tr3] list.inject path_var [of x p] prod.sel(1) path_of_subterm [of t0 p ‹Var x›] subtrie_at_path_step_simp)
      then show False
        by (metis ‹fmdrop Star m $$ s = Some m3› option.distinct(1) fmlookup_drop)
    qed
    show ?thesis    
    proof (cases ‹ts = {t0}›)
      case True
      have ‹fmdrop 0 m2 = {$$}›
        by (metis fmdrop_set_fmdom fmdrop_set_single Some ws_dom_var "2.prems"(1))
      then have ‹tr2 = SymbolNode (fmdrop Star m)› using "2.prems"(4)
        by (clarsimp simp add: Let_def Some h1 True split: if_splits)
      then show ?thesis using h2 by auto
    next
      case False
      then have h0: ‹tr2 = SymbolNode (m(Star $$:= m2(0 $$:= Leaf (ts - {t0}))))› using "2.prems"(4)
        by (clarsimp simp add: Let_def Some h1 split: if_splits)
      then have ‹t0 ∈ to_set tr2 ⟹ t0 ∈ to_set (SymbolNode (fmdrop Star m))›
      proof -
        assume ‹t0 ∈ to_set tr2›
        then obtain s i m4 tr4 where h3: ‹m(Star $$:= m2(0 $$:= Leaf (ts - {t0}))) $$ s = Some m4 ∧ m4 $$ i = Some tr4 ∧ t0 ∈ to_set tr4› using h0 by force
        then have ‹s ≠ Star›
          by (metis "2.prems"(1) to_set.simps(1) Diff_idemp Diff_insert_absorb Some fmdom'_notD fmupd_lookup mk_disjoint_insert option.distinct(1) option.sel singletonD ws_dom_var)
        then show ?thesis
          by (metis (mono_tags, lifting) h3 entry_to_set fmlookup_drop fmupd_lookup)
      qed
      then show ?thesis using h2 by auto
    qed 
  qed
next
  case (3 m f t0)
  have h0: ‹path_of_term t0 (p @ [(F f 0, 0)])›
    by (meson "3.prems"(3) path_const subterm_at_path_path_of_term)
  then show ?case 
  proof (cases ‹m $$ F f 0›)
    case None
    then show ?thesis using 3
      by (clarsimp, metis exists_leaf option.distinct(1) option.inject path_const sound_storage_from_position_def path_of_subterm subtrie_cons)
  next
    case (Some m2)
    then obtain ts where h1: ‹m2 $$ 0 = Some (Leaf ts)›
      by (meson "3.prems"(1) ws_dom_const)
    have h2: ‹⋀m3 tr3. m3 ∈ fmran' (fmdrop (F f 0) m) ⟹ tr3 ∈ fmran' m3 ⟹ t0 ∈ to_set tr3 ⟹ False›
    proof (elim fmran'E)
      fix m3 tr3 s i
      assume ‹t0 ∈ to_set tr3› and ‹fmdrop (F f 0) m $$ s = Some m3› and ‹m3 $$ i = Some tr3›
      then have ‹m $$ s = Some m3 ⟹ s = F f 0›
        by (smt (verit, best) "3.prems"(2,3) h0 sound_storage_from_position_def path_var exists_leaf [of t0 tr3] list.inject path_const [of f] prod.sel(1) path_of_subterm [of t0 p] subtrie_at_path_step_simp subtrie_at_path_step)
      then show False
        by (metis ‹fmdrop (F f 0) m $$ s = Some m3› fmlookup_drop option.distinct(1))
    qed
    show ?thesis     
    proof (cases ‹ts = {t0}›)
      case True
      have ‹fmdrop 0 m2 = {$$}›
        by (metis "3.prems"(1) Some fmdrop_set_fmdom fmdrop_set_single ws_dom_const)  
      then have ‹tr2 = SymbolNode (fmdrop (F f 0) m)› using "3.prems"(4)
        by (clarsimp simp add: Let_def Some h1 True split: if_splits)
      then show ?thesis using h2 by auto
    next
      case False
      then have h0: ‹tr2 = SymbolNode (m(F f 0 $$:= m2(0 $$:= Leaf (ts - {t0}))))› using "3.prems"(4)
        by (clarsimp simp add: Let_def Some h1 split: if_splits)
      then have ‹t0 ∈ to_set tr2 ⟹ t0 ∈ to_set (SymbolNode (fmdrop (F f 0) m))›
      proof -
        assume ‹t0 ∈ to_set tr2›
        then obtain s i m4 tr4 where h3: ‹m(F f 0 $$:= m2(0 $$:= Leaf (ts - {t0}))) $$ s = Some m4 ∧ m4 $$ i = Some tr4 ∧ t0 ∈ to_set tr4› using h0 by force
        then have ‹s ≠ F f 0›
          by (metis "3.prems"(1) to_set.simps(1) Diff_idemp Diff_insert_absorb Some fmdom'_notD fmupd_lookup mk_disjoint_insert option.distinct(1) option.sel singletonD ws_dom_const)
        then show ?thesis
          by (metis (mono_tags, lifting) h3 entry_to_set fmlookup_drop fmupd_lookup)
      qed
      then show ?thesis using h2 by auto
    qed
  qed
next
  case (4 m f a f_args t0)
  then show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    then have ‹tr2 = SymbolNode m›
      using remove_aux.simps(4) [of m f a f_args t0] update_or_remove_entry.simps [of m ‹F f (length (a # f_args))›]
      by (smt (verit, best) "4.prems"(4) option.distinct(1) option.inject option.simps(4))
    moreover have ‹t0 ∉ to_set (SymbolNode m)›
    proof
      assume ‹t0 ∈ to_set (SymbolNode m)›
      then obtain ts p2 where ‹subtrie_at_path (SymbolNode m) p2 (Leaf (insert t0 ts))› using exists_leaf by blast
      then obtain s i ps where h: ‹subtrie_at_path (SymbolNode m) ((s, i) # ps) (Leaf (insert t0 ts))› using subtrie_at_path.simps [of ‹SymbolNode m› p2 ‹Leaf (insert t0 ts)›] by auto
      then have ‹path_of_term t0 (p @ (s, i) # ps)› using sound_storage_from_position_def "4.prems"(2) by blast
      then have ‹s = F f (length (a # f_args))›
        by (metis "4.prems"(3) length_Cons list.sel(1) path_func path_of_subterm prod.sel(1))
      then show False
        using None h subtrie_cons by fastforce
    qed
    ultimately show ?thesis by auto
  next
    case (Some m2)
    let ?m' = ‹update_or_remove_entries m2 [0..< length (a # f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›
    show ?thesis
    proof (cases ‹?m' = {$$}›)
      case True
      then have ‹tr2 = SymbolNode (fmdrop (F f (length (a # f_args))) m)›
        using "4.prems"(4) Some by (simp add: Let_def split: if_splits)
      moreover have ‹t0 ∉ to_set (SymbolNode (fmdrop (F f (length (a # f_args))) m))›
      proof
        assume ‹t0 ∈ to_set (SymbolNode (fmdrop (F f (length (a # f_args))) m))›
        then obtain ts p2 where ‹subtrie_at_path (SymbolNode (fmdrop (F f (length (a # f_args))) m)) p2 (Leaf (insert t0 ts))› using exists_leaf by blast
        then obtain s i ps where h: ‹subtrie_at_path (SymbolNode (fmdrop (F f (length (a # f_args))) m)) ((s, i) # ps) (Leaf (insert t0 ts))›
          using subtrie_at_path.simps [of ‹SymbolNode (fmdrop (F f (length (a # f_args))) m)› p2 ‹Leaf (insert t0 ts)›] by auto
        then have ‹subtrie_at_path (SymbolNode m) ((s, i) # ps) (Leaf (insert t0 ts))›
          by (smt (verit, best) fmlookup_drop option.distinct(1) subtrie_at_path.simps subtrie_cons)
        then have ‹path_of_term t0 (p @ (s, i) # ps)› using sound_storage_from_position_def "4.prems"(2) by blast
        then have ‹s = F f (length (a # f_args))›
          by (metis "4.prems"(3) length_Cons list.sel(1) path_func path_of_subterm prod.sel(1))
        then show False using h subtrie_cons by fastforce
      qed
      ultimately show ?thesis by auto
    next
      case False
      then have h0: ‹tr2 = SymbolNode (m(F f (length (a # f_args)) $$:= ?m'))›
        using "4.prems"(4) Some by (simp add: Let_def split: if_splits)
      moreover have ‹t0 ∉ to_set (SymbolNode (m(F f (length (a # f_args)) $$:= ?m')))›
      proof
        assume ‹t0 ∈ to_set (SymbolNode (m(F f (length (a # f_args)) $$:= ?m')))›
        then obtain s i m3 tr3 where h1: ‹(m(F f (length (a # f_args)) $$:= ?m')) $$ s = Some m3 ∧ m3 $$ i = Some tr3 ∧ t0 ∈ to_set tr3›
          by fastforce
        show False
        proof (cases ‹s = F f (length (a # f_args))›)
          case True
          then have h2: ‹m3 = ?m'› using h1 by auto
          then have h3: ‹i < length (a # f_args)›
            by (metis (no_types, lifting) "4.prems"(1) Some update_or_remove_entries_dom fmdom'I h1 length_Cons subset_eq ws_dom_fun2)
          then obtain tr4 where h4: ‹m2 $$ i = Some tr4›
            by (meson "4.prems"(1) Some fmlookup_dom'_iff ws_dom_fun)
          then have ‹Some tr3 = remove_aux tr4  ((a # f_args) ! i) t0›
            by (smt (verit, ccfv_SIG) h1 h2 h3 "4.prems"(1) Some atLeast_upt distinct_upt fmdom'_notD list.distinct(1) option.distinct(1) update_or_remove_entries_some ws_fmdom')
          then show False
            using "4.IH" [of i tr4] "4.prems"(1,2,3) Some h1 h3 h4 sound_storage_from_position_subtrie subsubterm_at_path ws_subtree by fastforce
        next
          case False
          then have h2: ‹m $$ s = m(F f (length (a # f_args)) $$:= ?m') $$ s› by auto
          then obtain ts p2 where ‹subtrie_at_path tr2 ((s, i) # p2) (Leaf (insert t0 ts))›
            using h0 h1 exists_leaf subtrie_at_path_step by blast
          then have ‹path_of_term t0 (p @ (s, i) # p2)›
            by (smt (verit, best) "4.prems"(2) h0 h2 sound_storage_from_position_def subtrie_at_path_step subtrie_cons)
          then show False
            using "4.prems"(3) False path_func path_of_subterm by fastforce
        qed
      qed
      ultimately show ?thesis by auto
    qed
  qed
qed

lemma term_removed_from_trie_set: 
  assumes ‹well_structured tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path t0 p t›
    shows ‹t0 ∉ to_set (remove_term tr t t0)›
  using assms
  by (metis exists_leaf option.case_eq_if option.collapse remove_deletes_element remove_term.simps no_subtrie_in_empty_trie)

lemma to_set_remove_none: 
  assumes ‹well_structured tr›
      and ‹remove_aux tr t t0 = None› 
    shows ‹to_set tr ⊆ {t0}›
  by (metis assms exists_leaf option.simps(4) all_not_in_conv no_subtrie_in_empty_trie remove_term.simps remove_keeps_elements Diff_single_insert)

lemma to_set_remove:
  assumes ‹well_structured tr›
      and ‹sound_storage tr›
    shows ‹to_set (remove_term tr t t) = to_set tr - {t}›
  using assms remove_keeps_elements term_removed_from_trie_set sound_storage_alt_def subterm_at_path_empty remove_term_subset by blast

lemma remove_preserves_sound:
  assumes ‹well_structured tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path t0 p t›
    shows ‹sound_storage_from_position (remove_term tr t t0) p›
  using assms
proof (induction tr t t0 arbitrary: p rule: remove_aux.induct)
  case (1 s t t0)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x t0)
  then show ?case
  proof (cases ‹m $$ Star›)
    case None
    then show ?thesis using 2 by force
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts)›
      using "2.prems"(1) ws_dom_var by blast
    then show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then have ‹fmdrop 0 m2 = {$$}›
        by (metis "2.prems"(1) Some fmdrop_set_fmdom fmdrop_set_single ws_dom_var)
      then have ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode (fmdrop Star m)›
        by (simp add: Let_def h0 Some True split: if_splits)
      then have ‹⋀p t ts. subtrie_at_path (remove_term (SymbolNode m) (Var x) t0) p (Leaf (insert t ts)) ⟹ subtrie_at_path (SymbolNode m) p (Leaf (insert t ts))›
        by (smt (verit, del_insts) subtrie_at_path.simps subtrie_at_path_fmdrop_subset trie.disc(1,2))
      then show ?thesis
        using sound_storage_from_position_def "2.prems"(2) by blast
    next
      case False
      have ‹⋀t. t ∈ ts ⟹ path_of_term t (p @ [(Star, 0)])›
        by (metis "2.prems"(2) Some h0 insert_Diff sound_storage_from_position_def subtrie_at_path_empty subtrie_at_path_step)
      then have ‹sound_storage_from_position (SymbolNode {Star $$:= m2(0 $$:= Leaf (ts - {t0}))}) p›
        by (smt (verit, ccfv_threshold) "2.prems"(1) Diff_iff Diff_iff Diff_insert_absorb Some fmdom'_fmupd fmupd_lookup fmupd_lookup insertCI insert_Diff_single option.sel option.sel
            singletonD sound_storage_from_position_def subtrie_at_path.simps subtrie_string_2 subtrie_string_3 to_set.simps(1) trie.distinct(1) trie.sel(3) ws_dom_var)
      then show ?thesis
        by (auto simp add: 2 Let_def Some h0 False intro: elim_sound_fp) 
    qed
  qed
next
  case (3 m f t0)
  then show ?case
  proof (cases ‹m $$ F f 0›)
    case None
    then show ?thesis using 3 
      by force 
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts)›
      by (meson "3.prems"(1) ws_dom_const)
    show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then have ‹fmdrop 0 m2 = {$$}›
        by (metis "3.prems"(1) Some fmdrop_set_fmdom fmdrop_set_single ws_dom_const)
      then have ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode (fmdrop (F f 0) m)›
        by (simp add: Let_def Some h0 True split: if_splits)
      then show ?thesis
        by (smt (verit, ccfv_threshold) "3.prems"(1,2) fmlookup_drop option.discI sound_storage_from_position_def subtrie_at_path.simps subtrie_at_path_step trie.distinct(1) trie.sel(3)) 
    next
      case False
      have ‹sound_storage_from_position (SymbolNode ({F f 0 $$:= m2(0 $$:= Leaf (ts - {t0}))})) p›
        unfolding sound_storage_from_position_def
      proof (intro allI impI)
        fix t p2 s
        assume h1: ‹subtrie_at_path (SymbolNode {F f 0 $$:= m2(0 $$:= Leaf (ts - {t0}))}) p2 (Leaf (insert t s))›
        then have h2: ‹p2 = [(F f 0, 0)]› 
          by (smt (verit, del_insts) "3.prems"(1) Some fmdom'I fmupd_lookup option.sel singletonD subtrie_at_path.simps subtrie_string_2 trie.distinct(1) trie.sel(3) ws_dom_const)
        then have ‹ts - {t0} = insert t s› using h1
          by (metis fmupd_lookup option.sel subtrie_at_nil_iff_eq subtrie_cons trie.inject(1))
        then show ‹path_of_term t (p @ p2)›
          by (smt (verit, ccfv_threshold) "3.prems"(2) Diff_empty Diff_insert0 Some h2 h0 insert_Diff insert_commute sound_storage_from_position_def
              subtrie_at_path.simps)
      qed
      then show ?thesis 
        using 3 by (auto simp add: Some h0 False intro: elim_sound_fp)
    qed 
  qed
next
  case (4 m f a f_args t0)
  then show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    then show ?thesis using 4 by force 
  next
    case (Some m2)
    then have h0: ‹fmdom' m2 = {0..<length (a # f_args)}›
      by (metis Some ws_fmdom' set_upt "4.prems"(1) atLeast_upt list.simps(3))
    let ?m' = ‹update_or_remove_entries m2 [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›
    show ?thesis
    proof (cases ‹?m'= {$$}›)
      case t1: True
      then show ?thesis
      proof (cases ‹fmdrop (F f (length (a # f_args))) m = {$$}›)
        case True
        then show ?thesis
          using 4 Some t1
          by (simp add: sound_storage_from_position_def no_subtrie_in_empty_trie)
      next
        case False
        then have ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (fmdrop (F f (length (a # f_args))) m)›
          using Some t1 by simp
        then show ?thesis
          by (smt (verit, del_insts) "4.prems"(2) sound_storage_from_position_def subtrie_at_path.simps subtrie_at_path_fmdrop_subset trie.distinct(1))
      qed    
    next
      case False
      have h1: ‹⋀i. i < length (a # f_args) ⟹ sound_storage_from_position (remove_term (m2 $$! i) ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
      proof-
        fix i 
        assume h2: ‹i < length (a # f_args)›
        then have indom: ‹i ∈ fmdom' m2›
          by (metis "4.prems"(1) Some ws_dom_fun)
        then  have wel: ‹well_structured (m2 $$! i)›
          by (metis "4.prems"(1) Some fmdom'_notI length_greater_0_conv list.distinct(1) option.collapse ws_subtree)
        then have so: ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length (a # f_args)), i)])›
          by (metis "4.prems"(2) Some fmdom'_notI indom length_Cons option.collapse sound_storage_from_position_subtrie)
        then have ‹subterm_at_path t0 (p @ [(F f (length (a # f_args)), i)]) ((a # f_args) ! i)›
          using "4.prems"(3) subsubterm_at_path h2 by fastforce 
        then show ‹sound_storage_from_position (remove_term (m2 $$! i) ((a # f_args) ! i) t0) (p @ [(F f (length (a # f_args)), i)])›
          using "4.IH" so h2 wel by auto
      qed
      have ‹sound_storage_from_position (SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p› 
        unfolding sound_storage_from_position_def
      proof (intro allI impI)
        fix t1 p1 ts
        assume h3: ‹subtrie_at_path (SymbolNode {F f (length (a # f_args)) $$:= ?m'}) p1 (Leaf (insert t1 ts))›
        then obtain j ps where h2: ‹p1 = (F f (length (a # f_args)), j) # ps›
          using subtrie_at_path.cases subtrie_string_2
          by (smt (verit, best) fmap_distinct(1) trie.sel(2,3))
        have ‹?m' ≠ {$$}› using False by auto
        then have h4: ‹j < length (a # f_args)›
          by (metis (no_types, lifting) h2 h3 subtrie_string_3 update_or_remove_entries_dom "4.prems"(1) Some length_Cons subsetD ws_dom_fun2)
        then obtain tr2 where h5: ‹?m' $$ j = Some tr2›
          by (metis (no_types, lifting) h2 h3 fmlookup_dom'_iff subtrie_string_3)
        then have ‹Some tr2 = remove_aux (m2 $$! j) ((a # f_args) ! j) t0›
          by (metis (no_types, lifting) h0 h4 ext update_or_remove_entries_nth h0)
        then have ‹tr2 = remove_term (m2 $$! j) ((a # f_args) ! j) t0›
          by (metis option.simps(5) remove_term.simps) 
        then have ‹sound_storage_from_position tr2 (p @ [(F f (length (a # f_args)), j)])› using h1 h4 by auto
        then show ‹path_of_term t1 (p @ p1)› using h3 h2 h5 subtrie_cons [of ‹{F f (length (a # f_args)) $$:= ?m'}› ‹F f (length (a # f_args))› j ps]
            sound_storage_from_position_def [of tr2 ‹p @ [(F f (length (a # f_args)), j)]›] by auto
      qed
      then show ?thesis using 4 Some False by (auto intro: elim_sound_fp)
    qed 
  qed 
qed

lemma remove_preserves_complete:
  assumes ‹well_structured tr›
      and ‹complete_storage_from_position tr p›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path t0 p t›
    shows ‹complete_storage_from_position (remove_term tr t t0) p›
  unfolding complete_storage_from_position_def
proof (intro allI impI)
  fix u p2
  assume ‹u ∈ to_set (remove_term tr t t0)›
  then have ‹u ≠ t0 ∧ u ∈ to_set tr›
    using assms(1,3,4) remove_term_subset term_removed_from_trie_set by blast
  then show ‹path_of_term u (p @ p2) ⟹ ∃s. subtrie_at_path (remove_term tr t t0) p2 (Leaf (insert u s))›
    using assms
  proof (induction tr t t0 arbitrary: p p2 rule: remove_aux.induct)
    case (1 ts t t0)
    then show ?case using well_structured.simps by auto
  next
    case (2 m x t0)
    obtain ts where h0: ‹subtrie_at_path (SymbolNode m) p2 (Leaf (insert u ts))›
      using "2.prems"(1,2,4) unfolding complete_storage_from_position_def by blast
    obtain s i ps where h1: ‹p2 = (s, i) # ps›
      by (smt (verit, ccfv_SIG) "2.prems"(1,2,4,6) sub_path_not_path append.right_neutral complete_storage_from_position_def subtrie_at_path.cases)
    show ?case
    proof (cases ‹m $$ Star›)
      case None
      then have ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode m› by simp
      then show ?thesis using h0 by auto
    next
      case (Some m2)
      then obtain ts2 where h2: ‹m2 $$ 0 = Some (Leaf ts2)›
        using "2.prems"(3) ws_dom_var by blast
      show ?thesis
      proof (cases ‹ts2 = {t0}›)
        case True
        then have ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode (fmdrop Star m)›
          by (simp add: Some h2; smt (verit, ccfv_SIG) "2.prems"(3) Some fmdrop_set_fmdom fmdrop_set_single option.simps(4,5) ws_dom_var)
        moreover have ‹s ≠ Star›
          by (metis "2.prems"(1,2) Some True end_path_var h0 h1 h2 singletonD subtrie_entry_to_set to_set.simps(1))
        ultimately show ?thesis
          by (smt (verit, best) fmlookup_drop h0 h1 subtrie_at_path_step_simp)
      next
        case False
        then have h3: ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode (m(Star $$:= m2(0 $$:= Leaf (ts2 - {t0}))))›
          by (simp add: Some h2)
        show ?thesis
        proof (cases s)
          case Star
          then have h4: ‹i = 0 ∧ ps = []› using "2.prems"(1) h1 end_path_var by fast
          then have ‹m2 $$ 0 = Some (Leaf (insert u ts))›
            using Some Star elim_sub h0 h1 h2 subtrie_at_nil_iff_eq by blast
          then have ‹ts2 = insert u ts› using h2 by auto
          then have ‹subtrie_at_path (remove_term (SymbolNode m) (Var x) t0) [(s, i)] (Leaf (insert u ts - {t0}))›
            using h3 subtrie_at_path_step_simp [of ‹m(Star $$:= m2(0 $$:= Leaf (ts2 - {t0})))› s i ‹[]› ‹insert u ts - {t0}›]
            by (metis Star fmupd_lookup h4 subtrie_at_path_empty)
          then show ?thesis
            by (metis "2.prems"(2) Diff_cancel Diff_iff h1 h4 insert_Diff_if insert_iff)
        next
          case (F f n)
          then obtain m3 tr2 where ‹m $$ s = Some m3 ∧ m3 $$ i = Some tr2 ∧ subtrie_at_path tr2 ps (Leaf (insert u ts))›
            using h0 h1 subtrie_at_path_step_simp by blast
          then have ‹subtrie_at_path (remove_term (SymbolNode m) (Var x) t0) p2 (Leaf (insert u ts))›
            using h1 h3 F subtrie_at_path_step_simp [of _ s i ps ‹insert u ts›] by simp
          then show ?thesis by blast
        qed
      qed
    qed
  next
    case (3 m f t0)
    obtain ts where h0: ‹subtrie_at_path (SymbolNode m) p2 (Leaf (insert u ts))›
      using "3.prems"(1,2,4) unfolding complete_storage_from_position_def by blast
    obtain s i ps where h1: ‹p2 = (s, i) # ps›
      by (smt (verit, ccfv_SIG) "3.prems"(1,2,4,6) sub_path_not_path append.right_neutral complete_storage_from_position_def subtrie_at_path.cases)
    show ?case
    proof (cases ‹m $$ F f 0›)
      case None
      then have ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode m› by simp
      then show ?thesis using h0 by auto
    next
      case (Some m2)
      then obtain ts2 where h2: ‹m2 $$ 0 = Some (Leaf ts2)›
        using "3.prems"(3) ws_dom_const by metis
      show ?thesis
      proof (cases ‹ts2 = {t0}›)
        case True
        then have ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode (fmdrop (F f 0) m)›
          by (simp add: Some h2; smt (verit, best) "3.prems"(3) Some fmdrop_set_fmdom fmdrop_set_single option.simps(4,5) ws_dom_const)
        moreover have ‹s ≠ F f 0›
          by (metis "3.prems"(1,2) Some True end_path_const h0 h1 h2 option.sel singleton_insert_inj_eq' subtrie_at_nil_iff_eq subtrie_cons to_set.simps(1))
        ultimately show ?thesis
          by (metis (mono_tags, lifting) fmlookup_drop h0 h1 subtrie_at_path_step_simp)
      next
        case False
        then have h3: ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode (m(F f 0 $$:= m2(0 $$:= Leaf (ts2 - {t0}))))›
          by (simp add: Some h2)
        show ?thesis
        proof (cases ‹s = F f 0›)
          case True
          then have h4: ‹i = 0 ∧ ps = []› using "3.prems"(1) h1 end_path_const by fast
          then have ‹m2 $$ 0 = Some (Leaf (insert u ts))›
            by (metis h0 h1 Some True elim_sub subtrie_at_nil_iff_eq ‹⋀thesis. (⋀ts2. m2 $$ 0 = Some (Leaf ts2) ⟹ thesis) ⟹ thesis›)
          then have ‹ts2 = insert u ts› using h2 by auto
          then have ‹subtrie_at_path (remove_term (SymbolNode m) (Fun f []) t0) [(s, i)] (Leaf (insert u ts - {t0}))›
            using h3 subtrie_at_path_step_simp [of ‹m(F f 0 $$:= m2(0 $$:= Leaf (ts2 - {t0})))› s i ‹[]› ‹insert u ts - {t0}›]
            by (metis True fmupd_lookup h4 subtrie_at_path_empty)
          then show ?thesis
            by (metis "3.prems"(2) Diff_cancel Diff_iff h1 h4 insert_Diff_if insert_iff)
        next
          case False
          then obtain m3 tr2 where ‹m $$ s = Some m3 ∧ m3 $$ i = Some tr2 ∧ subtrie_at_path tr2 ps (Leaf (insert u ts))›
            using h0 h1 subtrie_at_path_step_simp by blast
          then have ‹subtrie_at_path (remove_term (SymbolNode m) (Fun f []) t0) p2 (Leaf (insert u ts))›
            using h1 h3 False subtrie_at_path_step_simp [of _ s i ps ‹insert u ts›] by simp
          then show ?thesis by blast
        qed
      qed
    qed
  next
    case (4 m f a f_args t0)
    obtain ts where h0: ‹subtrie_at_path (SymbolNode m) p2 (Leaf (insert u ts))›
      using "4.prems"(1,2,4) unfolding complete_storage_from_position_def by blast
    obtain s i ps where h1: ‹p2 = (s, i) # ps›
      by (smt (verit, ccfv_SIG) "4.prems"(1,2,4,6) sub_path_not_path append.right_neutral complete_storage_from_position_def subtrie_at_path.cases)
    show ?case
    proof (cases ‹m $$ F f (length (a # f_args))›)
      case None
      then have ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode m› by simp
      then show ?thesis using h0 by auto
    next
      case (Some m2)
      let ?m'= ‹update_or_remove_entries m2 [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›
      show ?thesis
      proof (cases ‹?m' = {$$}›)
        case True
        then have ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (fmdrop (F f (length (a # f_args))) m)›
          by (simp, smt (verit, best) Some length_Cons option.simps(4,5))
        moreover have ‹s ≠ F f (length (a # f_args))›
        proof
          assume h2: ‹s = F f (length (a # f_args))›
          then obtain tr2 where h3: ‹m2 $$ i = Some tr2› and ‹subtrie_at_path tr2 ps (Leaf (insert u ts))›
            by (metis Some h0 h1 option.inject subtrie_at_path_step_simp)
          then have ‹remove_aux tr2 ((a # f_args) ! i) t0 ≠ None›
            by (metis (no_types, lifting) "4.prems"(2,3) Some h2 empty_iff h0 h1 insert_iff length_greater_0_conv list.distinct(1) subsetD subtrie_entry_to_set
                to_set_remove_none ws_subtree)
          moreover have ‹i < length (a # f_args)›
            using "4.prems"(3) Some h3 ws_dom_fun2 by force
          ultimately show False
            using True Some h3 Update_Map_Entries.update_or_remove_entries_some [of ‹[0..<length (a # f_args)]› i m2 tr2]
            by (smt (verit, ccfv_threshold) atLeastLessThan_iff distinct_upt fmempty_lookup set_upt zero_le)
        qed
        ultimately show ?thesis
          by (metis (mono_tags, lifting) fmlookup_drop h0 h1 subtrie_at_path_step_simp)
      next
        case False
        then have h2: ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (m(F f (length (a # f_args)) $$:= ?m'))›
          using Some by auto
        show ?thesis
        proof (cases ‹s = F f (length (a # f_args))›)
          case True
          then obtain tr2 where h3: ‹m2 $$ i = Some tr2› and ‹subtrie_at_path tr2 ps (Leaf (insert u ts))›
            by (metis Some h0 h1 option.inject subtrie_at_path_step_simp)
          moreover have ‹u ∈ to_set tr2›
            using calculation(2) subtrie_to_set by blast
          moreover have ‹well_structured tr2›
            using "4.prems"(3) Some h3 ws_subtree by fastforce
          moreover have h4: ‹i < length (a # f_args)›
            using "4.prems"(3) Some h3 ws_dom_fun2 by force
          moreover have ‹complete_storage_from_position tr2 (p @ [(s, i)])›
            using h3 "4.prems"(4) Some True complete_storage_from_position_subtrie by blast
          moreover have ‹sound_storage_from_position tr2 (p @ [(s, i)])›
            using "4.prems"(5) Some True calculation(1) sound_storage_from_position_subtrie by blast
          moreover have ‹subterm_at_path t0 (p @ [(s, i)]) ((a # f_args) ! i)›
            using "4.prems"(6) calculation(5) True subsubterm_at_path by fast
          moreover have ‹path_of_term u ((p @ [(s, i)]) @ ps)›
            using "4.prems"(1) h1 by auto
          ultimately obtain ts2 where ‹subtrie_at_path (remove_term tr2 ((a # f_args) ! i) t0) ps (Leaf (insert u ts2))› 
            using "4.IH" [of i ‹p @ [(s, i)]› ps tr2] "4.prems"(2) by auto
          moreover have ‹?m' $$ i = Some (remove_term tr2 ((a # f_args) ! i) t0)›
            using h3 Update_Map_Entries.update_or_remove_entries_some [of ‹[0..<length (a # f_args)]› i m2 tr2 ‹(λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›]
            by (simp, metis (no_types, lifting) calculation h4 length_Cons no_subtrie_in_empty_trie option.case_eq_if option.collapse remove_term.simps)
          ultimately have ‹subtrie_at_path (remove_term (SymbolNode m) (Fun f (a # f_args)) t0) ((s, i) # ps) (Leaf (insert u ts2))›
            using h2 h3 True subtrie_at_path_step_simp [of _ s i ps ‹insert u ts2›] by auto
          then show ?thesis using h1 by auto
        next
          case False
          then have ‹subtrie_at_path (remove_term (SymbolNode m) (Fun f (a # f_args)) t0) ((s, i) # ps) (Leaf (insert u ts))›
            by (smt (verit, ccfv_SIG) fmupd_lookup h0 h1 h2 list.inject prod.inject subtrie_at_path.simps trie.distinct(1) trie.inject(2))
          then show ?thesis using h1 by auto
        qed
      qed
    qed
  qed
qed


lemma remove_some_not_empty: 
  assumes ‹well_structured tr›
      and ‹remove_aux tr t t0 = Some r›
    shows ‹r ≠ empty_trie›
  using assms
  by (induction tr t t0 arbitrary: r rule: remove_aux.induct) (auto simp add: well_structured.simps Let_def split: if_splits)

lemma remove_preserves_minimal: 
  assumes ‹well_structured tr›
      and ‹minimal_storage tr› 
    shows ‹minimal_storage (remove_term tr t t0)›
  using assms 
proof (induct tr t t0 rule: remove_aux.induct)
  case (1 s t t0)
  then show ?case
    using well_structured.simps by blast 
next
  case (2 m x t0)
  show ?case
  proof (cases ‹m $$ Star›)
    case None
    then show ?thesis
      using "2.prems"(2) by auto 
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts)›
      using "2.prems"(1) ws_dom_var by blast
    show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then have ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode (fmdrop Star m)›
        by (simp add: Some h0; smt (verit, ccfv_SIG) "2.prems"(1) Some fmdrop_set_fmdom fmdrop_set_single option.simps(4,5) ws_dom_var)
      then show ?thesis
        by (metis minimal_storage_drop "2.prems"(2))
    next
      case False
      then have h3: ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode (m(Star $$:= m2(0 $$:= Leaf (ts - {t0}))))›
        by (simp add: Some h0)
      have h4: ‹∀m2∈fmran' m. ∀tr∈fmran' m2. minimal_storage tr ∧ tr ≠ empty_trie› using "2.prems"(2) Some
        by (metis minimal_storage.simps trie.distinct(1) trie.sel(3))
      then have ‹ts ≠ {}›
        by (metis Some h0 fmran'I to_set.simps(1) trie.distinct(1) minimal_storage.simps)
      then have h5: ‹minimal_storage (Leaf (ts - {t0}))›
        by (metis False minimal_storage_leaf insert_Diff1 insert_Diff Diff_insert_absorb insertCI)
      have ‹∀m2∈fmran' (m(Star $$:= m2(0 $$:= Leaf (ts - {t0})))). ∀tr∈fmran' m2. minimal_storage tr ∧ tr ≠ empty_trie›
        by (smt (verit) Some fmlookup_ran'_iff fmupd_lookup option.sel trie.distinct h4 h5)
      then show ?thesis
        by (metis h3 minimal_storage_node)
    qed
  qed
next
  case (3 m f t0)
  show ?case
  proof (cases ‹m $$ F f 0›)
    case None
    then show ?thesis
      using "3.prems"(2) by auto 
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts)›
      using "3.prems"(1) ws_dom_const by meson
    show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then have ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode (fmdrop (F f 0) m)›
        by (simp add: Some h0; smt (verit, ccfv_SIG) "3.prems"(1) Some fmdrop_set_fmdom fmdrop_set_single option.simps(4,5) ws_dom_const)
      then show ?thesis
        by (metis minimal_storage_drop "3.prems"(2))
    next
      case False
      then have h3: ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode (m(F f 0 $$:= m2(0 $$:= Leaf (ts - {t0}))))›
        by (simp add: Some h0)
      have h4: ‹∀m2∈fmran' m. ∀tr∈fmran' m2. minimal_storage tr ∧ tr ≠ empty_trie› using "3.prems"(2) Some
        by (metis minimal_storage.simps trie.distinct(1) trie.sel(3))
      then have ‹ts ≠ {}›
        by (metis Some h0 fmran'I to_set.simps(1) trie.distinct(1) minimal_storage.simps)
      then have h5: ‹minimal_storage (Leaf (ts - {t0}))›
        by (metis False minimal_storage_leaf insert_Diff1 insert_Diff Diff_insert_absorb insertCI)
      have ‹∀m2∈fmran' (m(F f 0 $$:= m2(0 $$:= Leaf (ts - {t0})))). ∀tr∈fmran' m2. minimal_storage tr ∧ tr ≠ empty_trie›
        by (smt (verit) Some fmlookup_ran'_iff fmupd_lookup option.sel trie.distinct h4 h5)
      then show ?thesis
        by (metis h3 minimal_storage_node)
    qed
  qed
next
  case (4 m f a f_args t0)
  show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    then show ?thesis
      using "4.prems"(2) by auto
  next
    case (Some m2)
    let ?m' = ‹update_or_remove_entries m2 [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›
    show ?thesis
    proof (cases ‹?m' = {$$}›)
      case True
      then have ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (fmdrop (F f (length (a # f_args))) m)›
        by (simp, smt (verit, best) Some length_Cons option.simps(4,5))
      then show ?thesis
        by (simp add: "4.prems"(2))
    next
      case False
      then have h0: ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (m(F f (length (a # f_args)) $$:= ?m'))›
        using Some by auto
      have h1: ‹∀m2∈fmran' m. ∀tr∈fmran' m2. minimal_storage tr ∧ tr ≠ empty_trie› using "4.prems"(2) Some
        by (metis minimal_storage.simps trie.distinct(1) trie.sel(3))
      have ‹∀m3∈fmran' (m(F f (length (a # f_args)) $$:= ?m')). ∀tr3∈fmran' m3. minimal_storage tr3 ∧ tr3 ≠ empty_trie›
        unfolding Ball_def
      proof (intro allI impI)
        fix m3 tr3
        assume ‹m3 ∈ fmran' (m(F f (length (a # f_args)) $$:= ?m'))› and h2: ‹tr3 ∈ fmran' m3›
        then obtain s where h3: ‹m(F f (length (a # f_args)) $$:= ?m') $$ s = Some m3› by fast
        show ‹minimal_storage tr3 ∧ tr3 ≠ empty_trie›
        proof (cases ‹s = F f (length (a # f_args))›)
          case True
          then have ‹m3 = ?m'›
            using h3 by auto
          then obtain i where h10: ‹?m' $$ i = Some tr3›
            using h2 by blast
          then have h4: ‹i < length (a # f_args)›
            by (metis (no_types, lifting) "4.prems"(1) update_or_remove_entries_dom [of m2] Some fmdom'I length_Cons subsetD ws_dom_fun2)
          then obtain tr2 where h11: ‹m2 $$ i = Some tr2›
            by (meson "4.prems"(1) Some fmlookup_dom'_iff ws_dom_fun)
          then have h5: ‹well_structured tr2 ∧ minimal_storage tr2›
            by (metis "4.prems"(1) Some fmran'I h1 length_greater_0_conv list.distinct(1) ws_subtree)
          then have h6: ‹minimal_storage (remove_term tr2 ((a # f_args) ! i) t0)›
            using "4.hyps" [of i tr2] h4 by auto
          have ‹remove_aux tr2 ((a # f_args) ! i) t0 = Some tr3›
            using h4 h10 h11 update_or_remove_entries_some [of ‹[0..<length (a # f_args)]› i m2 tr2 ‹(λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›]
            by auto
          then show ?thesis
            by (metis option.simps(5) h6 h5 remove_term.simps remove_some_not_empty)
        next
          case False
          then show ?thesis using h1 h2 h3 fmran'I by force
        qed
      qed
      then show ?thesis using minimal_storage_node h0 by auto
    qed
  qed
qed

lemma remove_preserves_structure:
  assumes ‹well_structured tr›
      and ‹complete_storage_from_position tr p›
      and ‹minimal_storage tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path t0 p t›
    shows ‹well_structured (remove_term tr t t0)›
  using assms
proof (induction tr t t0 arbitrary: p rule: remove_aux.induct)
  case (1 s t t0)
  then show ?case using well_structured.simps by blast
next
  case (2 m x t0)
  show ?case
  proof (cases ‹m $$ Star›)
    case None
    then show ?thesis
      using "2.prems"(1) by force
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts) ∧ fmdom' m2 = {0}›
      using "2.prems"(1) ws_dom_var by blast
    have h1: ‹∀s. s ∈ fmdom' m ⟶ well_structured_map_entry s (m $$! s)›
      using "2.prems"(1) by (simp add: well_structured.simps)
    show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then have ‹remove_term (SymbolNode m) (Var x) t0 = SymbolNode (fmdrop Star m)›
        by (simp add: Some h0; smt (verit, ccfv_SIG) "2.prems"(1) Some fmdrop_set_fmdom fmdrop_set_single option.simps(4,5) ws_dom_var)
      then show ?thesis
        by (simp add: "2.prems"(1))
    next
      case False
      have ‹well_structured_map_entry Star (m2(0 $$:= Leaf (ts - {t0})))› using wsme_var h0
        by (metis Diff_insert_absorb fmdom'_fmupd fmupd_lookup insert_Diff_single mk_disjoint_insert)
      then have ‹well_structured (SymbolNode (m(Star $$:= m2(0 $$:= Leaf (ts - {t0})))))›
        by (simp add: h1 well_structured.simps)
      then show ?thesis by (simp add: False Some h0)
    qed
  qed
next
  case (3 m f t0)
  show ?case
  proof (cases ‹m $$ F f 0›)
    case None
    then show ?thesis
      using "3.prems"(1) by force
  next
    case (Some m2)
    then obtain ts where h0: ‹m2 $$ 0 = Some (Leaf ts) ∧ fmdom' m2 = {0}›
      using "3.prems"(1) ws_dom_const by metis
    have h1: ‹∀s. s ∈ fmdom' m ⟶ well_structured_map_entry s (m $$! s)›
      using "3.prems"(1) by (simp add: well_structured.simps)
    show ?thesis
    proof (cases ‹ts = {t0}›)
      case True
      then have ‹remove_term (SymbolNode m) (Fun f []) t0 = SymbolNode (fmdrop (F f 0) m)›
        by (simp add: Some h0; smt (verit, ccfv_SIG) "3.prems"(1) Some fmdrop_set_fmdom fmdrop_set_single option.simps(4,5) ws_dom_const)
      then show ?thesis
        by (simp add: "3.prems"(1))
    next
      case False
      have ‹well_structured_map_entry (F f 0) (m2(0 $$:= Leaf (ts - {t0})))› using wsme_const h0
        by (metis Diff_insert_absorb fmdom'_fmupd fmupd_lookup insert_Diff_single mk_disjoint_insert)
      then have ‹well_structured (SymbolNode (m(F f 0 $$:= m2(0 $$:= Leaf (ts - {t0})))))›
        by (simp add: h1 well_structured.simps)
      then show ?thesis
        by (simp add: False Some h0)
    qed
  qed
next
  case (4 m f a f_args t0)
  then show ?case
  proof (cases ‹m $$ F f (length (a # f_args))›)
    case None
    then show ?thesis 
      using "4.prems"(1) None by force
  next
    case (Some m2)
    let ?m' = ‹update_or_remove_entries m2 [0..<length (a # f_args)] (λi tr. if i < length (a # f_args) then remove_aux tr ((a # f_args) ! i) t0 else undefined)›
    have h0: ‹fmdom' m2 = {0..<length (a # f_args)}›
      by (metis set_upt ws_fmdom' Some atLeast_upt "4.prems"(1) list.simps(3))
    then obtain tr2 where h1: ‹m2 $$ 0 = Some tr2›
      by (metis "4.prems"(1) Some fmlookup_dom'_iff length_greater_0_conv list.distinct(1) ws_dom_fun)
    show ?thesis
    proof (cases ‹to_set tr2 ⊆ {t0}›)
      case True
      have ‹⋀i. ?m' $$ i = None›
      proof -
        fix i
        show ‹?m' $$ i = None›
        proof (cases ‹i < length (a # f_args)›)
          case t0: True
          then obtain tr3 where h2: ‹m2 $$ i = Some tr3›
            by (meson "4.prems"(1) Some fmlookup_dom'_iff ws_dom_fun)
          then have h3: ‹to_set tr3 ⊆ {t0}›
            using True Some h1 sibling_nodes_to_set [of m p f ‹length (a # f_args)› m2 0 tr2 i tr3] 4 by blast
          have h4: ‹well_structured tr3›
            using "4.prems"(1) Some h2 ws_subtree by fastforce
          have h5: ‹complete_storage_from_position tr3 (p @ [(F f (length (a # f_args)), i)])›
            using "4.prems"(2) Some complete_storage_from_position_subtrie h2 by blast
          have h6: ‹minimal_storage tr3›
            by (metis fmran'I "4.prems"(3) trie.sel(3) h2 minimal_storage.simps Some trie.distinct(1))
          have h7: ‹sound_storage_from_position tr3 (p @ [(F f (length (a # f_args)), i)])›
            using "4.prems"(4) Some h2 sound_storage_from_position_subtrie by blast
          have h8: ‹subterm_at_path t0 (p @ [(F f (length (a # f_args)), i)]) ((a # f_args) ! i)›
            by (meson "4.prems"(5) subsubterm_at_path t0)
          have ‹remove_aux tr3 ((a # f_args) ! i) t0 = None›
          proof (rule ccontr)
            assume ‹remove_aux tr3 ((a # f_args) ! i) t0 ≠ None›
            then obtain tr4 where h5: ‹remove_aux tr3 ((a # f_args) ! i) t0 = Some tr4› by auto
            then have h9: ‹remove_term tr3 ((a # f_args) ! i) t0 = tr4› by auto
            then have ‹to_set tr4 ⊆ {t0}›
              using h3 h4 remove_term_subset [of tr3 _ ‹((a # f_args) ! i)› t0] by auto
            then have ‹to_set tr4 = {}›
              using remove_deletes_element [of tr3 ‹p @ [(F f (length (a # f_args)), i)]› t0 ‹((a # f_args) ! i)› tr4] h4 h5 h7 h8 by blast
            moreover have ‹minimal_storage tr4›
              using remove_preserves_minimal [of tr3 ‹((a # f_args) ! i)› t0] h4 h6 h9 by auto
            moreover have ‹well_structured tr4›
              using "4.IH" [of i tr3 ‹p @ [(F f (length (a # f_args)), i)]›] "4.prems"(2) Some complete_storage_from_position_subtrie h2 h4 h6 h7 h8 h9 t0 by blast
            ultimately show False
              using h5 h4 remove_some_not_empty only_empty_trie_is_empty by blast
          qed
          then show ?thesis
            using update_or_remove_entries_some [of ‹[0..<length (a # f_args)]› i m2] t0 h2 by auto
        next
          case False
          then show ?thesis using update_or_remove_entries_dom h0 by force
        qed
      qed
      then have ‹?m' = {$$}›
        using exists_in_non_fmempty by fastforce
      then have ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (fmdrop (F f (length (a # f_args))) m)›
        by (simp, smt (verit, best) Some length_Cons option.simps(4,5))
      then show ?thesis
        by (simp add: "4.prems"(1))
    next
      case False
      then obtain t1 where h3: ‹t1 ≠ t0 ∧ t1 ∈ to_set tr2› by auto
      then have h4: ‹⋀i. i < length (a # f_args) ⟹ (∃tr3. ?m' $$ i = Some tr3 ∧ well_structured tr3)›
      proof
        fix i
        assume h5: ‹i < length (a # f_args)›
        then obtain tr2 where h6: ‹m2 $$ i = Some tr2›
          by (meson "4.prems"(1) Some fmlookup_dom'_iff ws_dom_fun)
        then have h7: ‹t1 ∈ to_set tr2›
          by (metis "4.prems"(1,2,4) Some h1 h3 sibling_nodes_to_set)
        have h8: ‹well_structured tr2›
          using h6 "4.prems"(1) Some ws_subtree by fastforce
        have h9: ‹complete_storage_from_position tr2 (p @ [(F f (length (a # f_args)), i)])› using h6 "4.prems"(2) Some complete_storage_from_position_subtrie by blast
        have h10: ‹minimal_storage tr2›
          by (metis h6 Some "4.prems"(3) trie.sel(3) trie.distinct(1) fmran'I minimal_storage.simps)
        have h11: ‹sound_storage_from_position tr2 (p @ [(F f (length (a # f_args)), i)])›
          using "4.prems"(4) Some h6 sound_storage_from_position_subtrie by blast
        have h12: ‹subterm_at_path t0 (p @ [(F f (length (a # f_args)), i)]) ((a # f_args) ! i)›
          by (metis subsubterm_at_path h5 "4.prems"(5))
        obtain tr3 where h13: ‹remove_aux tr2 ((a # f_args) ! i) t0 = Some tr3›
          by (metis "4.prems"(1) Some h3 h6 h7 insert_absorb insert_iff insert_not_empty length_Cons option.collapse subset_singleton_iff to_set_remove_none ws_subtree
              zero_less_Suc)
        then have ‹remove_term tr2 ((a # f_args) ! i) t0 = tr3› by auto
        then have ‹well_structured tr3›
          by (meson "4.prems"(5) "4.IH" [of i tr2 ‹p @ [(F f (length (a # f_args)), i)]›] h5 h6 h7 h8 h9 h10 h11 h12)
        then show ‹(∃tr3. ?m' $$ i = Some tr3 ∧ well_structured tr3)›
          by (metis (no_types, lifting) ext h0 h5 h6 h13 option.sel update_or_remove_entries_nth)
      qed
      have h5: ‹fmdom' ?m' = {..<length (a # f_args)}›
      proof
        show ‹fmdom' ?m' ⊆ {..<length (a # f_args)}›
          by (metis (no_types, lifting) atLeast0LessThan h0 update_or_remove_entries_dom)
      next
        show ‹{..<length (a # f_args)} ⊆ fmdom' ?m'›
          using h4 fmdom'_notD by fastforce
      qed
      then have h6: ‹?m' ≠ {$$}› by force
      have ‹∀tr3. tr3 ∈ fmran' ?m' ⟶ well_structured tr3›
      proof (intro allI impI)
        fix tr3
        assume ‹tr3 ∈ fmran' ?m'›
        then obtain i where h7: ‹?m' $$ i = Some tr3› by auto
        then have ‹i < length (a # f_args)› using h5 by force
        then show ‹well_structured tr3› using h4 h7 by force
      qed
      then have ‹well_structured_map_entry (F f (length (a # f_args))) ?m'›
        using wsme_func [of ‹length (a # f_args)›] h5 by auto
      moreover have ‹remove_term (SymbolNode m) (Fun f (a # f_args)) t0 = SymbolNode (m(F f (length (a # f_args)) $$:= ?m'))›
        using Some h6 by simp
      ultimately show ?thesis
        by (metis (lifting) "4.prems"(1) fmdom'_notD fmdom'_notI fmupd_lookup option.sel trie.inject(2) well_structured.simps)
    qed
  qed
qed

subsection ‹Retrieval operations›

fun var_terms :: ‹(('f symbol , (nat, ('f, 'v) trie) fmap) fmap) ⇒ ('f, 'v) term set› where 
  ‹var_terms m = (case m $$ Star of
                    None ⇒ {}
                  | Some m2 ⇒ to_set (m2 $$! 0))›

fun retrieve_generalizations :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› where
  ‹retrieve_generalizations (Leaf ts) t = undefined›
| ‹retrieve_generalizations (SymbolNode m) (Var x) = var_terms m›
| ‹retrieve_generalizations (SymbolNode m) (Fun f f_args) =
     var_terms m ∪ (case m $$ (F f (length f_args)) of
                      None ⇒ {}
                    | Some m2 ⇒ if f_args = []
                                 then to_set (m2 $$! 0)
                                 else ⋂ i ∈ fmdom' m2. retrieve_generalizations (m2 $$! i) (f_args ! i))›

fun retrieve_unifications :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› where
  ‹retrieve_unifications (Leaf ts) t = undefined›
| ‹retrieve_unifications (SymbolNode m) (Var x) = to_set (SymbolNode m)›
| ‹retrieve_unifications (SymbolNode m) (Fun f f_args) =
     var_terms m ∪ (case m $$ (F f (length f_args)) of
                      None ⇒ {}
                    | Some m2 ⇒ if f_args = []
                                 then to_set (m2 $$! 0)
                                 else ⋂ i ∈ fmdom' m2. retrieve_unifications (m2 $$! i) (f_args ! i))›

fun retrieve_instances :: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› where
  ‹retrieve_instances (Leaf ts) t = undefined›
| ‹retrieve_instances (SymbolNode m) (Var x) = to_set (SymbolNode m)›
| ‹retrieve_instances (SymbolNode m) (Fun f f_args) =
     (case m $$ (F f (length f_args)) of
        None ⇒ {}
      | Some m2 ⇒ if f_args = []
                   then to_set (m2 $$! 0)
                   else ⋂ i ∈ fmdom' m2. retrieve_instances (m2 $$! i) (f_args ! i))›

fun retrieve_variants:: ‹('f, 'v) trie ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› where
  ‹retrieve_variants (Leaf ts) t = undefined›
| ‹retrieve_variants (SymbolNode m) (Var x) = var_terms m›
| ‹retrieve_variants (SymbolNode m) (Fun f f_args) =
     (case m $$ (F f (length f_args)) of
        None ⇒ {}
      | Some m2 ⇒ if f_args = []
                   then to_set (m2 $$! 0)
                   else ⋂ i ∈ fmdom' m2. retrieve_variants (m2 $$! i) (f_args ! i))›

lemma var_terms_in_set: 
  assumes ‹well_structured (SymbolNode m)›
    shows ‹var_terms m ⊆ to_set (SymbolNode m)›
proof (cases ‹m $$ Star›)
  case None
  then show ?thesis by force
next
  case (Some m2)
  then have ‹well_structured_map_entry Star m2›
    by (metis assms fmdom'I option.sel trie.inject(2) well_structured.simps)
  then have dom: ‹fmdom' m2 = { 0 }›
    by (simp add: well_structured_map_entry.simps)
  have ‹m2 ∈ fmran' m›
    by (meson Some fmran'I)
  then have ‹to_set (m2 $$! 0) ⊆ ⋃ (to_set ` ⋃ (fmran' ` (fmran' m)))›
    by (metis Sup_upper UN_I dom fmdom'_notI fmran'I image_eqI insertI1 option.collapse)
  then show ?thesis
    using Some by auto
qed

lemma simp_storage :
  assumes ‹complete_storage_from_position tr p›
      and ‹sound_storage_from_position tr p›
      and ‹t ∈ to_set tr›
    shows ‹path_of_term t (p @ p') ⟷  (∃ts. subtrie_at_path tr p' (Leaf (insert t ts)))›
  using assms complete_storage_from_position_def sound_storage_from_position_def 
  by metis  

lemma sound_storage_subterm_symbol_fun : 
  assumes ‹well_structured (SymbolNode m1)›
      and ‹sound_storage_from_position (SymbolNode m1) p›
      and ‹subterm_at_path t p t'› 
      and ‹t ∈ to_set (m2 $$! 0)› 
      and ‹m1 $$ F f (length f_args) = Some m2›
    shows ‹root_symbol t' = F f (length f_args)›
  by (smt (verit) Pair_inject assms exists_leaf fmdom'_notI length_greater_0_conv list.inject list.size(3) option.collapse option.sel path_of_subterm
      path_of_term.simps sound_storage_from_position_def subtrie_at_path_step symbol.distinct(1) root_symbol.simps(2) ws_dom_const ws_dom_fun)

lemma sound_storage_subterm_symbol_var: 
  assumes ‹well_structured (SymbolNode m1)›
      and ‹sound_storage_from_position (SymbolNode m1) p›
      and ‹subterm_at_path t p t'›
      and ‹t ∈ to_set (m2 $$! 0)›
      and ‹m1 $$ Star = Some m2›
    shows ‹root_symbol t' = Star›
  by (smt (verit, ccfv_threshold) Pair_inject assms exists_leaf fmdom'I fmdom'_notI list.simps(1) list.size(3) option.collapse path_of_subterm
      path_of_term.simps sound_storage_from_position_def subtrie_at_path_step root_symbol.simps(1,2) ws_dom_var)

lemma retrieve_generalizations_in_set:
  assumes ‹well_structured tr›
      and ‹t ∈ retrieve_generalizations tr t'›
    shows ‹t ∈ to_set tr›
  using assms 
proof (induction arbitrary: t rule: retrieve_generalizations.induct)
  case (1 ts t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case
    using var_terms_in_set by fastforce
next
  case (3 m f f_args)
  then consider (a) ‹t ∈ var_terms m›
              | (b) ‹t ∈ (case m $$ F f (length f_args) of
                            None ⇒ {}
                          | Some m2 ⇒ if f_args = []
                                       then to_set (m2 $$! 0)
                                       else ⋂i∈fmdom' m2. retrieve_generalizations (m2 $$! i) (f_args ! i))› by force
  then show ?case
  proof cases
    case a
    then show ?thesis
      using var_terms_in_set "3.prems"(1) by blast
  next
    case b
    then show ?thesis
    proof (cases f_args)
      case Nil
      then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                       and h1: ‹t ∈ to_set (m2 $$! 0)›
        by (smt (verit, best) b emptyE option.exhaust_sel option.split_sel)
      then show ?thesis
        by (metis "3.prems"(1) list.size(3) local.Nil option.sel entry_to_set ws_dom_const)
    next
      case (Cons _ _)
      then obtain m2 i where ‹m $$ F f (length f_args) = Some m2›
                         and ‹i ∈ fmdom' m2›
                         and ‹t ∈ retrieve_generalizations (m2 $$! i) (f_args ! i)›
        by (smt (verit, ccfv_SIG) "3.prems"(1) b empty_iff length_greater_0_conv list.distinct(1) mem_simps(10) option.case_eq_if option.collapse ws_dom_fun)
      then show ?thesis
        by (metis (no_types, lifting) "3.IH" "3.prems"(1) fmlookup_dom'_iff fmran'I length_0_conv length_Cons list.simps(3) local.Cons
            local.Cons option.sel symbol.inject symbol.simps(3) entry_to_set trie.inject(2) well_structured.simps well_structured_map_entry.cases)
    qed
  qed
qed

lemma retrieve_generalizations_sound:
  assumes ‹well_structured tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path e p e'›
      and ‹e ∈ retrieve_generalizations tr t'›
    shows ‹linear_instance t' e'›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_generalizations.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then obtain m2 where ‹m $$ Star = Some m2 ∧ e ∈ to_set (m2 $$! 0)›
    by (metis (no_types, lifting) empty_iff option.exhaust_sel option.split_sel_asm retrieve_generalizations.simps(2) var_terms.simps)
  then obtain y where ‹e' = Var y›
    by (metis "2.prems"(1,2,3) sound_storage_subterm_symbol_var symbol.distinct(1) root_symbol.elims)
  then show ?case
    by (simp add: li_var)
next
  case (3 m f f_args)
  then consider (a) ‹e ∈ var_terms m›
              | (b) ‹e ∈ (case m $$ F f (length f_args) of
                            None ⇒ {}
                          | Some m2 ⇒ if f_args = []
                                       then to_set (m2 $$! 0)
                                       else ⋂i∈fmdom' m2. retrieve_generalizations (m2 $$! i) (f_args ! i))› by force
  then show ?case
  proof cases
    case a
    then obtain m2 where ‹m $$ Star = Some m2 ∧ e ∈ to_set (m2 $$! 0)›
      by (metis (no_types, lifting) empty_iff option.case_eq_if option.exhaust_sel var_terms.simps)
    then obtain x where ‹e' = Var x›
      by (metis "3.prems"(1,2,3) sound_storage_subterm_symbol_var symbol.distinct(1) root_symbol.elims)
    then show ?thesis
      by (simp add: li_var)
  next
    case b
    then show ?thesis
    proof (cases f_args)
      case Nil
      then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                       and h1: ‹e ∈ to_set (m2 $$! 0)›
        by (smt (verit, del_insts) b empty_iff option.case_eq_if option.collapse)
      then have ‹e' = Fun f []›
        by (smt (verit, best) "3.prems"(1,2,3) length_0_conv local.Nil sound_storage_subterm_symbol_fun symbol.distinct(1) symbol.inject root_symbol.elims
            root_symbol.simps(2))
      then show ?thesis
        by (simp add: li_func local.Nil)
    next
      case (Cons _ _)
      then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                       and h1: ‹∀i ∈ fmdom' m2. e ∈ retrieve_generalizations (m2 $$! i) (f_args ! i)›
        by (smt (verit, ccfv_threshold) b empty_iff list.distinct(1) mem_simps(10) option.case_eq_if option.collapse)
      then have ‹e ∈ to_set (m2 $$! 0)›
        by (metis (no_types, lifting) "3.prems"(1) fmlookup_dom'_iff fmran'I length_0_conv length_greater_0_conv list.distinct(1) local.Cons option.sel
            retrieve_generalizations_in_set symbol.distinct(1) symbol.inject trie.inject(2) well_structured.simps well_structured_map_entry.cases ws_dom_fun)
      then obtain f_args' where h2: ‹e' = Fun f f_args'›
                            and h3: ‹length f_args' = length f_args›
        using sound_storage_subterm_symbol_fun [of m p e e' m2 f f_args]
        by (metis "3.prems"(1,2,3) h0 symbol.distinct(1) symbol.inject root_symbol.elims)
      have ‹⋀i. i ∈ fmdom' m2 ⟹ linear_instance (f_args ! i) (f_args' ! i)›
      proof -
        fix i
        assume h4: ‹i ∈ fmdom' m2›
        moreover have ‹e ∈ retrieve_generalizations (m2 $$! i) (f_args ! i)› using h1 h4 by auto
        moreover have ‹well_structured (m2 $$! i)›
          by (metis "3.prems"(1) h4 fmlookup_dom'_iff fmran'I h0 length_0_conv list.distinct(1) local.Cons option.sel symbol.distinct(1) symbol.inject
              trie.inject(2) well_structured.simps well_structured_map_entry.cases)
        moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
          by (metis "3.prems"(2) fmlookup_dom'_iff h0 h4 option.sel sound_storage_from_position_subtrie)
        moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (f_args' ! i)›
          by (metis "3.prems"(1,3) h0 h2 h3 h4 lessThan_iff list.distinct(1) local.Cons subsubterm_at_path ws_fmdom')
        ultimately show ‹linear_instance (f_args ! i) (f_args' ! i)›
          using "3.IH" h0 local.Cons by blast
      qed
      then show ?thesis using li_func h0 h2 h3
        by (metis "3.prems"(1) ws_dom_fun)
    qed
  qed
qed

lemma retrieve_generalizations_complete:
  assumes ‹linear_instance t e'›
      and ‹well_structured tr›
      and ‹complete_storage_from_position tr p›
      and ‹sound_storage_from_position tr p›
      and ‹e ∈ to_set tr›
      and ‹subterm_at_path e p e'›
    shows ‹e ∈ retrieve_generalizations tr t›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_generalizations.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then obtain y where ‹e' = Var y›
    using linear_instance.cases by blast
  then obtain m2 ts where ‹m $$ Star = Some m2›
                      and ‹m2 $$ 0 = Some (Leaf ts)›
                      and ‹e ∈ ts›
    by (smt (verit, ccfv_threshold) "2.prems"(3,5,6) complete_storage_from_position_def insertI1 list.distinct(1) path_var subterm_at_path_path_of_term
        subtrie_at_path.cases subtrie_cons)
  then show ?case by simp
next
  case (3 m f f_args)
  then show ?case
  proof (cases e')
    case (Var x)
    then obtain m2 ts where ‹m $$ Star = Some m2›
                        and ‹m2 $$ 0 = Some (Leaf ts)›
                        and ‹e ∈ ts›
      by (smt (verit, ccfv_threshold) "3.prems"(4,5,6) exists_leaf insertI1 list.distinct(1) path_of_subterm path_var sound_storage_from_position_def
          subtrie_at_path.cases subtrie_cons)
    then show ?thesis by simp
  next
    case (Fun g g_args)
    then have h0: ‹g = f ∧ length g_args = length f_args ∧ (∀i<length f_args. linear_instance (f_args ! i) (g_args ! i))›
      using "3.prems"(1) linear_instance.cases by fastforce
    show ?thesis
    proof (cases f_args)
      case Nil
      then obtain m2 ts where ‹m $$ F f (length f_args) = Some m2›
                          and ‹m2 $$ 0 = Some (Leaf ts)›
                          and ‹e ∈ ts›
        by (smt (verit, ccfv_threshold) "3.prems"(2,4,5,6) Fun exists_leaf h0 insertI1 length_0_conv no_subtrie_in_empty_trie option.sel path_const path_of_subterm
            sound_storage_from_position_def subtrie_at_path.cases subtrie_cons trie.sel(2,3) ws_dom_const)
      then show ?thesis
        by (simp add: local.Nil)
    next
      case (Cons _ _)
      then obtain m2 where h1: ‹m $$ F f (length f_args) = Some m2›
        by (smt (verit, ccfv_threshold) "3.prems"(4,5,6) Fun Term.term.simps(4) exists_leaf h0 list.simps(1) list.size(3) no_subtrie_in_empty_trie path_of_subterm
            path_of_term.simps prod.sel(1) sound_storage_from_position_def subtrie_at_path.cases root_symbol.simps(2) trie.sel(2,3))
      have ‹⋀i. i ∈ fmdom' m2 ⟹ e ∈ retrieve_generalizations (m2 $$! i) (f_args ! i)›
      proof -
        fix i
        assume h3: ‹i ∈ fmdom' m2›
        moreover have ‹linear_instance (f_args ! i) (g_args ! i)›
          by (metis "3.prems"(2) h0 h1 h3 key_map_entry_simp length_0_conv list.distinct(1) local.Cons)
        moreover have ‹well_structured (m2 $$! i)›
          by (metis "3.prems"(2) fmlookup_dom'_iff fmran'I h1 h3 length_greater_0_conv less_not_refl list.distinct(1) local.Cons option.sel symbol.distinct(1)
              symbol.inject trie.inject(2) well_structured.simps well_structured_map_entry.cases)
        moreover have ‹complete_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
          by (meson "3.prems"(3) complete_storage_from_position_subtrie fmdom'_notI h1 h3 option.exhaust_sel)
        moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
          by (meson "3.prems"(4) fmdom'_notI h1 h3 option.exhaust_sel sound_storage_from_position_subtrie)
        moreover have ‹e ∈ to_set (m2 $$! i)›
        proof - 
          obtain p2 where ‹path_of_term (Fun f g_args) ((F f (length g_args), i) # p2)›
            by (metis "3.prems"(2) exists_path h0 h1 h3 key_map_entry length_0_conv list.distinct(1) local.Cons path_of_term_func)
          then have ‹path_of_term e (p @ ((F f (length f_args), i) # p2))›
            using "3.prems"(6) Fun h0 subterm_at_path_path_of_term by auto
          then show ?thesis
            by (meson "3.prems"(3-5) fmdom'_notI h1 h3 option.exhaust_sel simp_storage subtrie_entry_to_set)
        qed
        moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (g_args ! i)›
          by (metis "3.prems"(2,6) Fun h0 h1 h3 lessThan_iff list.distinct(1) local.Cons subsubterm_at_path ws_fmdom')
        ultimately show ‹e ∈ retrieve_generalizations (m2 $$! i) (f_args ! i)›
          using "3.IH" h1 local.Cons by blast
      qed
      then show ?thesis
        using h1 local.Cons by auto
    qed
  qed
qed

lemma retrieve_instances_in_set:
  assumes ws : ‹well_structured tr›
      and ret: ‹e ∈ retrieve_instances tr t›
    shows ‹e ∈ to_set tr›
  using assms 
proof (induction arbitrary: e rule: retrieve_instances.induct)
  case (1 ts t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case
    using var_terms_in_set by fastforce
next
  case (3 m f f_args)
  then show ?case
  proof (cases f_args)
    case Nil
    then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                     and h1: ‹e ∈ to_set (m2 $$! 0)›
      by (smt (verit, ccfv_threshold) "3.prems"(2) empty_iff option.collapse option.split_sel_asm retrieve_instances.simps(3))
    then show ?thesis
      by (metis "3.prems"(1) list.size(3) local.Nil option.sel entry_to_set ws_dom_const)
  next
    case (Cons _ _)
    then obtain m2 i where ‹m $$ F f (length f_args) = Some m2›
                       and ‹i ∈ fmdom' m2›
                       and ‹e ∈ retrieve_instances (m2 $$! i) (f_args ! i)›
      by (smt (verit, best) "3.prems"(1,2) empty_iff length_greater_0_conv list.distinct(1) mem_simps(10) option.case_eq_if option.collapse
          retrieve_instances.simps(3) ws_dom_fun)
    then show ?thesis
      by (metis (no_types, lifting) "3.IH" "3.prems"(1) fmlookup_dom'_iff fmran'I length_0_conv length_Cons list.simps(3) local.Cons
          local.Cons option.sel symbol.inject symbol.simps(3) entry_to_set trie.inject(2) well_structured.simps well_structured_map_entry.cases)
  qed
qed

lemma retrieve_instances_sound:
  assumes ‹well_structured tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path e p e'›
      and ‹e ∈ retrieve_instances tr t›
    shows ‹linear_instance e' t›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_instances.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case
    by (simp add: li_var)
next
  case (3 m f f_args)
  then show ?case
  proof (cases f_args)
    case Nil
    then obtain m2 where ‹m $$ F f (length f_args) = Some m2›
                     and ‹e ∈ to_set (m2 $$! 0)›
      by (smt (verit, ccfv_threshold) "3.prems"(4) empty_iff option.collapse option.split_sel_asm retrieve_instances.simps(3))
    then have ‹e' = Fun f []›
      by (smt (verit, best) "3.prems"(1,2,3) length_0_conv local.Nil sound_storage_subterm_symbol_fun symbol.distinct(1) symbol.inject root_symbol.elims
          root_symbol.simps(2))
    then show ?thesis
      by (simp add: li_func local.Nil)
  next
    case (Cons _ _)
    then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                     and h1: ‹∀i ∈ fmdom' m2. e ∈ retrieve_instances (m2 $$! i) (f_args ! i)›
      by (smt (verit, ccfv_threshold) "3.prems"(4) emptyE list.distinct(1) mem_simps(10) not_Some_eq option.simps(5) option.split_sel_asm
          retrieve_instances.simps(3))
    then have ‹e ∈ to_set (m2 $$! 0)›
      by (metis (no_types, lifting) "3.prems"(1) fmlookup_dom'_iff fmran'I length_greater_0_conv list.distinct(1) list.size(3) local.Cons option.sel
          retrieve_instances_in_set symbol.distinct(1) symbol.inject trie.inject(2) well_structured.simps well_structured_map_entry.cases ws_dom_fun)
    then obtain f_args' where h2: ‹e' = Fun f f_args'›
                          and h3: ‹length f_args' = length f_args›
      using sound_storage_subterm_symbol_fun [of m p e e' m2 f f_args]
      by (metis "3.prems"(1,2,3) h0 symbol.distinct(1) symbol.inject root_symbol.elims)
    have ‹⋀i. i ∈ fmdom' m2 ⟹ linear_instance (f_args' ! i) (f_args ! i)›
    proof -
      fix i
      assume h4: ‹i ∈ fmdom' m2›
      moreover have ‹e ∈ retrieve_instances (m2 $$! i) (f_args ! i)› using h1 h4 by auto
      moreover have ‹well_structured (m2 $$! i)›
        by (metis "3.prems"(1) h4 fmlookup_dom'_iff fmran'I h0 length_0_conv list.distinct(1) local.Cons option.sel symbol.distinct(1) symbol.inject
            trie.inject(2) well_structured.simps well_structured_map_entry.cases)
      moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
        by (metis "3.prems"(2) fmlookup_dom'_iff h0 h4 option.sel sound_storage_from_position_subtrie)
      moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (f_args' ! i)›
        by (metis "3.prems"(1,3) h0 h2 h3 h4 lessThan_iff list.distinct(1) local.Cons subsubterm_at_path ws_fmdom')
      ultimately show ‹linear_instance (f_args' ! i) (f_args ! i)›
        using "3.IH" h0 local.Cons by blast
    qed
    then show ?thesis using li_func h0 h2 h3
      by (metis "3.prems"(1) ws_dom_fun)
  qed
qed

lemma retrieve_instances_complete: 
  assumes ‹linear_instance  e' t›
      and ‹well_structured tr›
      and ‹complete_storage_from_position tr p›
      and ‹sound_storage_from_position tr p›
      and ‹e ∈ to_set tr› 
      and ‹subterm_at_path e p e'›
    shows ‹e ∈ retrieve_instances tr t›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_instances.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case by auto
next
  case (3 m f f_args)
  then obtain f_args' where h0: ‹e' = Fun f f_args'›
                        and h1: ‹length f_args = length f_args'›
                        and h2: ‹∀i<length f_args. linear_instance (f_args' ! i) (f_args ! i)›
    by (metis linear_instance.cases term.distinct(1) term.inject(2))
  show ?case
  proof (cases f_args)
    case Nil
    then obtain m2 ts where ‹m $$ F f (length f_args) = Some m2›
                        and ‹m2 $$ 0 = Some (Leaf ts)›
                        and ‹e ∈ ts›
      by (smt (verit, ccfv_threshold) "3.prems"(1,4,5,6) exists_leaf length_0_conv linear_instance.simps list.distinct(1) path_const path_of_subterm
          sound_storage_from_position_def subtrie_at_path.cases subtrie_cons subtrie_to_set term.distinct(1) term.inject(2) to_set.simps(1))
    then show ?thesis
      by (simp add: local.Nil)
  next
    case (Cons _ _)
    obtain m2 where h3: ‹m $$ F f (length f_args) = Some m2›
      by (smt (verit, ccfv_threshold) "3.prems"(4,5,6) Term.term.simps(4) exists_leaf h0 h1 length_greater_0_conv list.distinct(1) local.Cons path_of_subterm
          path_of_term.simps sound_storage_from_position_def subtrie_cons term.inject(2))
    have ‹⋀i. i ∈ fmdom' m2 ⟹ e ∈ retrieve_instances (m2 $$! i) (f_args ! i)›
    proof -
      fix i
      assume h4: ‹i ∈ fmdom' m2›
      moreover have ‹linear_instance (f_args' ! i) (f_args ! i)›
        by (metis "3.prems"(2) h2 h3 h4 key_map_entry_simp length_0_conv list.distinct(1) local.Cons)
      moreover have ‹well_structured (m2 $$! i)›
        by (metis "3.prems"(2) fmlookup_dom'_iff fmran'I h3 h4 length_0_conv list.distinct(1) local.Cons option.sel symbol.distinct(1) symbol.inject trie.inject(2)
            well_structured.simps well_structured_map_entry.cases)
      moreover have ‹complete_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
        by (metis "3.prems"(3) complete_storage_from_position_subtrie fmdom'_notI h3 h4 option.collapse)
      moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
        by (metis "3.prems"(4) fmdom'_notI h3 h4 option.collapse sound_storage_from_position_subtrie)
      moreover have ‹e ∈ to_set (m2 $$! i)›
      proof - 
        obtain p2 where ‹path_of_term (Fun f f_args') ((F f (length f_args), i) # p2)›
          by (metis "3.prems"(2) append_Nil append_eq_append_conv exists_path h1 h3 h4 lessThan_iff list.distinct(1) local.Cons path_of_term_func ws_fmdom')
        then have ‹path_of_term e (p @ ((F f (length f_args), i) # p2))›
          using "3.prems"(6) h0 subterm_at_path_path_of_term by auto
        then show ?thesis
          by (meson "3.prems"(3,4,5) fmdom'_notI h3 h4 option.exhaust_sel simp_storage subtrie_entry_to_set)
      qed
      moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (f_args' ! i)›
        by (metis "3.prems"(2,6) h0 h1 h3 h4 key_map_entry_simp length_0_conv list.distinct(1) local.Cons subsubterm_at_path)
      ultimately show ‹e ∈ retrieve_instances (m2 $$! i) (f_args ! i)›
        using "3.IH" h3 local.Cons by blast
    qed
    then show ?thesis
      using h3 local.Cons by force
  qed
qed

lemma retrieve_unifications_in_set:
  assumes ‹well_structured tr›
      and ‹e ∈ retrieve_unifications tr t›
    shows ‹e ∈ to_set tr›
  using assms
proof (induction arbitrary: e rule: retrieve_unifications.induct)
  case (1 ts t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case by auto
next
  case (3 m f f_args)
  then consider (a) ‹e ∈ var_terms m›
              | (b) ‹e ∈ (case m $$ F f (length f_args) of
                            None ⇒ {}
                          | Some m2 ⇒ if f_args = []
                                       then to_set (m2 $$! 0)
                                       else ⋂i∈fmdom' m2. retrieve_unifications (m2 $$! i) (f_args ! i))› by force
  then show ?case
  proof cases
    case a
    then show ?thesis
      using var_terms_in_set "3.prems"(1) by blast
  next
    case b
    then show ?thesis
    proof (cases f_args)
      case Nil
      then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                       and h1: ‹e ∈ to_set (m2 $$! 0)›
        by (smt (verit, best) b emptyE option.exhaust_sel option.split_sel)
      then show ?thesis
        by (metis "3.prems"(1) list.size(3) local.Nil option.sel entry_to_set ws_dom_const)
    next
      case (Cons _ _)
      then obtain m2 i where ‹m $$ F f (length f_args) = Some m2›
                         and ‹i ∈ fmdom' m2›
                         and ‹e ∈ retrieve_unifications (m2 $$! i) (f_args ! i)›
        by (smt (verit, ccfv_SIG) "3.prems"(1) b empty_iff length_greater_0_conv list.distinct(1) mem_simps(10) option.case_eq_if option.collapse ws_dom_fun)
      then show ?thesis
        by (metis (no_types, lifting) "3.IH" "3.prems"(1) fmlookup_dom'_iff fmran'I length_0_conv length_Cons list.simps(3) local.Cons
            local.Cons option.sel symbol.inject symbol.simps(3) entry_to_set trie.inject(2) well_structured.simps well_structured_map_entry.cases)
    qed
  qed
qed

lemma retrieve_unifications_sound:
  assumes ‹well_structured tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path e p e'›
      and ‹e ∈ retrieve_unifications tr t›
    shows ‹linear_unification t e'›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_unifications.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case
    by (simp add: lu_varl)
next
  case (3 m f f_args)
  then consider (a) ‹e ∈ var_terms m›
              | (b) ‹e ∈ (case m $$ F f (length f_args) of
                            None ⇒ {}
                          | Some m2 ⇒ if f_args = []
                                       then to_set (m2 $$! 0)
                                       else ⋂i∈fmdom' m2. retrieve_unifications (m2 $$! i) (f_args ! i))› by force
  then show ?case
  proof cases
    case a
    then obtain m2 where ‹m $$ Star = Some m2 ∧ e ∈ to_set (m2 $$! 0)›
      by (metis (no_types, lifting) empty_iff option.case_eq_if option.exhaust_sel var_terms.simps)
    then obtain x where ‹e' = Var x›
      by (metis "3.prems"(1,2,3) sound_storage_subterm_symbol_var symbol.distinct(1) root_symbol.elims)
    then show ?thesis
      by (simp add: lu_varr)
  next
    case b
    then show ?thesis
    proof (cases f_args)
      case Nil
      then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                       and h1: ‹e ∈ to_set (m2 $$! 0)›
        by (smt (verit, del_insts) b empty_iff option.case_eq_if option.collapse)
      then have ‹e' = Fun f []›
        by (smt (verit, best) "3.prems"(1,2,3) length_0_conv local.Nil sound_storage_subterm_symbol_fun symbol.distinct(1) symbol.inject root_symbol.elims
            root_symbol.simps(2))
      then show ?thesis
        by (simp add: lu_func local.Nil)
    next
      case (Cons _ _)
      then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                       and h1: ‹∀i ∈ fmdom' m2. e ∈ retrieve_unifications (m2 $$! i) (f_args ! i)›
        by (smt (verit, ccfv_threshold) b empty_iff list.distinct(1) mem_simps(10) option.case_eq_if option.collapse)
      then have ‹e ∈ to_set (m2 $$! 0)›
        by (metis (no_types, lifting) "3.prems"(1) fmlookup_dom'_iff fmran'I length_0_conv length_greater_0_conv list.distinct(1) local.Cons option.sel
            retrieve_unifications_in_set symbol.distinct(1) symbol.inject trie.inject(2) well_structured.simps well_structured_map_entry.cases ws_dom_fun)
      then obtain f_args' where h2: ‹e' = Fun f f_args'›
                            and h3: ‹length f_args' = length f_args›
        using sound_storage_subterm_symbol_fun [of m p e e' m2 f f_args]
        by (metis "3.prems"(1,2,3) h0 symbol.distinct(1) symbol.inject root_symbol.elims)
      have ‹⋀i. i ∈ fmdom' m2 ⟹ linear_unification (f_args ! i) (f_args' ! i)›
      proof -
        fix i
        assume h4: ‹i ∈ fmdom' m2›
        moreover have ‹e ∈ retrieve_unifications (m2 $$! i) (f_args ! i)› using h1 h4 by auto
        moreover have ‹well_structured (m2 $$! i)›
          by (metis "3.prems"(1) h4 fmlookup_dom'_iff fmran'I h0 length_0_conv list.distinct(1) local.Cons option.sel symbol.distinct(1) symbol.inject
              trie.inject(2) well_structured.simps well_structured_map_entry.cases)
        moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
          by (metis "3.prems"(2) fmlookup_dom'_iff h0 h4 option.sel sound_storage_from_position_subtrie)
        moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (f_args' ! i)›
          by (metis "3.prems"(1,3) h0 h2 h3 h4 lessThan_iff list.distinct(1) local.Cons subsubterm_at_path ws_fmdom')
        ultimately show ‹linear_unification (f_args ! i) (f_args' ! i)›
          using "3.IH" h0 local.Cons by blast
      qed
      then show ?thesis using lu_func h0 h2 h3
        by (metis "3.prems"(1) ws_dom_fun)
    qed
  qed
qed

lemma retrieve_unifications_complete:
  assumes ‹linear_unification t e'›
      and ‹well_structured tr›
      and ‹complete_storage_from_position tr p›
      and ‹sound_storage_from_position tr p›
      and ‹e ∈ to_set tr›
      and ‹subterm_at_path e p e'›
    shows ‹e ∈ retrieve_unifications tr t›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_unifications.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case by auto
next
  case (3 m f f_args)
  then show ?case
  proof (cases e')
    case (Var x)
    then obtain m2 ts where ‹m $$ Star = Some m2›
                        and ‹m2 $$ 0 = Some (Leaf ts)›
                        and ‹e ∈ ts›
      by (smt (verit, ccfv_threshold) "3.prems"(4,5,6) exists_leaf insertI1 list.distinct(1) path_of_subterm path_var sound_storage_from_position_def
          subtrie_at_path.cases subtrie_cons)
    then show ?thesis by simp
  next
    case (Fun g g_args)
    then have h0: ‹g = f ∧ length g_args = length f_args ∧ (∀i<length f_args. linear_unification (f_args ! i) (g_args ! i))›
      using "3.prems"(1) linear_unification.cases by fastforce
    show ?thesis
    proof (cases f_args)
      case Nil
      then obtain m2 ts where ‹m $$ F f (length f_args) = Some m2›
                          and ‹m2 $$ 0 = Some (Leaf ts)›
                          and ‹e ∈ ts›
        by (smt (verit, ccfv_threshold) "3.prems"(2,4,5,6) Fun exists_leaf h0 insertI1 length_0_conv no_subtrie_in_empty_trie option.sel path_const path_of_subterm
            sound_storage_from_position_def subtrie_at_path.cases subtrie_cons trie.sel(2,3) ws_dom_const)
      then show ?thesis
        by (simp add: local.Nil)
    next
      case (Cons _ _)
      then obtain m2 where h1: ‹m $$ F f (length f_args) = Some m2›
        by (smt (verit, ccfv_threshold) "3.prems"(4,5,6) Fun Term.term.simps(4) exists_leaf h0 list.simps(1) list.size(3) no_subtrie_in_empty_trie path_of_subterm
            path_of_term.simps prod.sel(1) sound_storage_from_position_def subtrie_at_path.cases root_symbol.simps(2) trie.sel(2,3))
      have ‹⋀i. i ∈ fmdom' m2 ⟹ e ∈ retrieve_unifications (m2 $$! i) (f_args ! i)›
      proof -
        fix i
        assume h3: ‹i ∈ fmdom' m2›
        moreover have ‹linear_unification (f_args ! i) (g_args ! i)›
          by (metis "3.prems"(2) h0 h1 h3 key_map_entry_simp length_0_conv list.distinct(1) local.Cons)
        moreover have ‹well_structured (m2 $$! i)›
          by (metis "3.prems"(2) fmlookup_dom'_iff fmran'I h1 h3 length_greater_0_conv less_not_refl list.distinct(1) local.Cons option.sel symbol.distinct(1)
              symbol.inject trie.inject(2) well_structured.simps well_structured_map_entry.cases)
        moreover have ‹complete_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
          by (meson "3.prems"(3) complete_storage_from_position_subtrie fmdom'_notI h1 h3 option.exhaust_sel)
        moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
          by (meson "3.prems"(4) fmdom'_notI h1 h3 option.exhaust_sel sound_storage_from_position_subtrie)
        moreover have ‹e ∈ to_set (m2 $$! i)›
        proof - 
          obtain p2 where ‹path_of_term (Fun f g_args) ((F f (length g_args), i) # p2)›
            by (metis "3.prems"(2) exists_path h0 h1 h3 key_map_entry length_0_conv list.distinct(1) local.Cons path_of_term_func)
          then have ‹path_of_term e (p @ ((F f (length f_args), i) # p2))›
            using "3.prems"(6) Fun h0 subterm_at_path_path_of_term by auto
          then show ?thesis
            by (meson "3.prems"(3-5) fmdom'_notI h1 h3 option.exhaust_sel simp_storage subtrie_entry_to_set)
        qed
        moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (g_args ! i)›
          by (metis "3.prems"(2,6) Fun h0 h1 h3 lessThan_iff list.distinct(1) local.Cons subsubterm_at_path ws_fmdom')
        ultimately show ‹e ∈ retrieve_unifications (m2 $$! i) (f_args ! i)›
          using "3.IH" h1 local.Cons by blast
      qed
      then show ?thesis
        using h1 local.Cons by auto
    qed
  qed
qed

lemma retrieve_variants_in_set:
  assumes ‹well_structured tr›
      and ‹e ∈ retrieve_variants tr t›
    shows ‹e ∈ to_set tr›
  using assms
proof (induction arbitrary: e rule: retrieve_unifications.induct)
  case (1 ts t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then show ?case
    using var_terms_in_set by fastforce
next
  case (3 m f f_args)
  then show ?case
  proof (cases f_args)
    case Nil
    then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                     and h1: ‹e ∈ to_set (m2 $$! 0)›
      by (smt (verit, ccfv_threshold) "3.prems"(2) empty_iff option.collapse option.split_sel_asm retrieve_variants.simps(3))
    then show ?thesis
      by (metis "3.prems"(1) list.size(3) local.Nil option.sel entry_to_set ws_dom_const)
  next
    case (Cons _ _)
    then obtain m2 i where ‹m $$ F f (length f_args) = Some m2›
                       and ‹i ∈ fmdom' m2›
                       and ‹e ∈ retrieve_variants (m2 $$! i) (f_args ! i)›
      by (smt (verit, best) "3.prems"(1,2) empty_iff length_greater_0_conv list.distinct(1) mem_simps(10) option.case_eq_if option.collapse
          retrieve_variants.simps(3) ws_dom_fun)
    then show ?thesis
      by (metis (no_types, lifting) "3.IH" "3.prems"(1) fmlookup_dom'_iff fmran'I length_0_conv length_Cons list.simps(3) local.Cons
          local.Cons option.sel symbol.inject symbol.simps(3) entry_to_set trie.inject(2) well_structured.simps well_structured_map_entry.cases)
  qed
qed

lemma retrieve_variants_sound:
  assumes ‹well_structured tr›
      and ‹sound_storage_from_position tr p›
      and ‹subterm_at_path e p e'›
      and ‹e ∈ retrieve_variants tr t›
    shows ‹linear_variant  e' t›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_variants.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then obtain m2 where ‹m $$ Star = Some m2 ∧ e ∈ to_set (m2 $$! 0)›
    by (metis (no_types, lifting) empty_iff option.exhaust_sel option.split_sel_asm retrieve_variants.simps(2) var_terms.simps)
  then obtain y where ‹e' = Var y›
    by (metis "2.prems"(1,2,3) sound_storage_subterm_symbol_var symbol.distinct(1) root_symbol.elims)
  then show ?case
    by (simp add: lv_var)
next
  case (3 m f f_args)
  then show ?case
  proof (cases f_args)
    case Nil
    then obtain m2 where ‹m $$ F f (length f_args) = Some m2›
                     and ‹e ∈ to_set (m2 $$! 0)›
      by (smt (verit, ccfv_threshold) "3.prems"(4) empty_iff option.collapse option.split_sel_asm retrieve_variants.simps(3))
    then have ‹e' = Fun f []›
      by (smt (verit, best) "3.prems"(1,2,3) length_0_conv local.Nil sound_storage_subterm_symbol_fun symbol.distinct(1) symbol.inject root_symbol.elims
          root_symbol.simps(2))
    then show ?thesis
      by (simp add: lv_func local.Nil)
  next
    case (Cons _ _)
    then obtain m2 where h0: ‹m $$ F f (length f_args) = Some m2›
                     and h1: ‹∀i ∈ fmdom' m2. e ∈ retrieve_variants (m2 $$! i) (f_args ! i)›
      by (smt (verit, ccfv_threshold) "3.prems"(4) emptyE list.distinct(1) mem_simps(10) not_Some_eq option.simps(5) option.split_sel_asm
          retrieve_variants.simps(3))
    then have ‹e ∈ to_set (m2 $$! 0)›
      by (metis (no_types, lifting) "3.prems"(1) fmlookup_dom'_iff fmran'I length_greater_0_conv list.distinct(1) list.size(3) local.Cons option.sel
          retrieve_variants_in_set symbol.distinct(1) symbol.inject trie.inject(2) well_structured.simps well_structured_map_entry.cases ws_dom_fun)
    then obtain f_args' where h2: ‹e' = Fun f f_args'›
                          and h3: ‹length f_args' = length f_args›
      using sound_storage_subterm_symbol_fun [of m p e e' m2 f f_args]
      by (metis "3.prems"(1,2,3) h0 symbol.distinct(1) symbol.inject root_symbol.elims)
    have ‹⋀i. i ∈ fmdom' m2 ⟹ linear_variant (f_args' ! i) (f_args ! i)›
    proof -
      fix i
      assume h4: ‹i ∈ fmdom' m2›
      moreover have ‹e ∈ retrieve_variants (m2 $$! i) (f_args ! i)› using h1 h4 by auto
      moreover have ‹well_structured (m2 $$! i)›
        by (metis "3.prems"(1) h4 fmlookup_dom'_iff fmran'I h0 length_0_conv list.distinct(1) local.Cons option.sel symbol.distinct(1) symbol.inject
            trie.inject(2) well_structured.simps well_structured_map_entry.cases)
      moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
        by (metis "3.prems"(2) fmlookup_dom'_iff h0 h4 option.sel sound_storage_from_position_subtrie)
      moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (f_args' ! i)›
        by (metis "3.prems"(1,3) h0 h2 h3 h4 lessThan_iff list.distinct(1) local.Cons subsubterm_at_path ws_fmdom')
      ultimately show ‹linear_variant (f_args' ! i) (f_args ! i)›
        using "3.IH" h0 local.Cons by blast
    qed
    then show ?thesis using lv_func h0 h2 h3
      by (metis "3.prems"(1) ws_dom_fun)
  qed
qed

lemma retrieve_variants_complete:
  assumes ‹linear_variant e' t›
      and ‹well_structured tr›
      and ‹complete_storage_from_position tr p›
      and ‹sound_storage_from_position tr p›
      and ‹e ∈ to_set tr›
      and ‹subterm_at_path e p e'›
    shows ‹e ∈ retrieve_variants tr t›
  using assms
proof (induction arbitrary: e p e' rule: retrieve_instances.induct)
  case (1 s t)
  then show ?case
    using well_structured.simps by blast
next
  case (2 m x)
  then obtain y where ‹e' = Var y›
    using linear_variant.cases by blast
  then obtain m2 ts where ‹m $$ Star = Some m2›
                      and ‹m2 $$ 0 = Some (Leaf ts)›
                      and ‹e ∈ ts›
    by (smt (verit, ccfv_threshold) "2.prems"(3,5,6) complete_storage_from_position_def insertI1 list.distinct(1) path_var subterm_at_path_path_of_term
        subtrie_at_path.cases subtrie_cons)
  then show ?case by simp
next
  case (3 m f f_args)
  then obtain f_args' where h0: ‹e' = Fun f f_args'›
                        and h1: ‹length f_args = length f_args'›
                        and h2: ‹∀i<length f_args. linear_variant (f_args' ! i) (f_args ! i)›
    by (metis linear_variant.cases term.distinct(1) term.inject(2))
  show ?case
  proof (cases f_args)
    case Nil
    then obtain m2 ts where ‹m $$ F f (length f_args) = Some m2›
                        and ‹m2 $$ 0 = Some (Leaf ts)›
                        and ‹e ∈ ts›
      by (smt (verit, ccfv_threshold) "3.prems"(1,4,5,6) exists_leaf length_0_conv linear_variant.simps list.distinct(1) path_const path_of_subterm
          sound_storage_from_position_def subtrie_at_path.cases subtrie_cons subtrie_to_set term.distinct(1) term.inject(2) to_set.simps(1))
    then show ?thesis
      by (simp add: local.Nil)
  next
    case (Cons _ _)
    obtain m2 where h3: ‹m $$ F f (length f_args) = Some m2›
      by (smt (verit, ccfv_threshold) "3.prems"(4,5,6) Term.term.simps(4) exists_leaf h0 h1 length_greater_0_conv list.distinct(1) local.Cons path_of_subterm
          path_of_term.simps sound_storage_from_position_def subtrie_cons term.inject(2))
    have ‹⋀i. i ∈ fmdom' m2 ⟹ e ∈ retrieve_variants (m2 $$! i) (f_args ! i)›
    proof -
      fix i
      assume h4: ‹i ∈ fmdom' m2›
      moreover have ‹linear_variant (f_args' ! i) (f_args ! i)›
        by (metis h4 h2 key_map_entry_simp local.Cons length_0_conv "3.prems"(2) h3 list.distinct(1))
      moreover have ‹well_structured (m2 $$! i)›
        by (metis "3.prems"(2) fmlookup_dom'_iff fmran'I h3 h4 length_0_conv list.distinct(1) local.Cons option.sel symbol.distinct(1) symbol.inject trie.inject(2)
            well_structured.simps well_structured_map_entry.cases)
      moreover have ‹complete_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
        by (metis "3.prems"(3) complete_storage_from_position_subtrie fmdom'_notI h3 h4 option.collapse)
      moreover have ‹sound_storage_from_position (m2 $$! i) (p @ [(F f (length f_args), i)])›
        by (metis "3.prems"(4) fmdom'_notI h3 h4 option.collapse sound_storage_from_position_subtrie)
      moreover have ‹e ∈ to_set (m2 $$! i)›
      proof - 
        obtain p2 where ‹path_of_term (Fun f f_args') ((F f (length f_args), i) # p2)›
          by (metis "3.prems"(2) append_Nil append_eq_append_conv exists_path h1 h3 h4 lessThan_iff list.distinct(1) local.Cons path_of_term_func ws_fmdom')
        then have ‹path_of_term e (p @ ((F f (length f_args), i) # p2))›
          using "3.prems"(6) h0 subterm_at_path_path_of_term by auto
        then show ?thesis
          by (meson "3.prems"(3,4,5) fmdom'_notI h3 h4 option.exhaust_sel simp_storage subtrie_entry_to_set)
      qed
      moreover have ‹subterm_at_path e (p @ [(F f (length f_args), i)]) (f_args' ! i)›
        by (metis "3.prems"(2,6) h0 h1 h3 h4 key_map_entry_simp length_Cons local.Cons nat.simps(3) subsubterm_at_path)
      ultimately show ‹e ∈ retrieve_variants (m2 $$! i) (f_args ! i)›
        using "3.IH" h3 local.Cons by blast
    qed
    then show ?thesis
      using h3 local.Cons by force
  qed
qed

subsection ‹Index type and main theorems›

typedef ('f, 'v) index =
  ‹{ t :: ('f, 'v) trie. well_structured t ∧ sound_storage t ∧ complete_storage t ∧ minimal_storage t }›
  by (rule exI [of _ ‹empty_trie›]) auto

setup_lifting type_definition_index

lift_definition index_to_set :: ‹('f, 'v) index ⇒ ('f, 'v) term set› is to_set .

lift_definition index_insert :: ‹('f, 'v) index ⇒ ('f, 'v) term ⇒ ('f, 'v) index› is ‹λtr. λt. insert_aux tr t t›
  by (simp add: complete_storage_alt_def insert_preserves_complete insert_preserves_sound insert_preserves_structure insert_preserves_minimal sound_storage_alt_def subterm_at_path.intros(1))

theorem index_insert_spec: ‹index_to_set (index_insert tr t) = insert t (index_to_set tr)›
  using insert_aux_keeps_elements insert_aux_subset insert_aux_adds_element
  by (metis (mono_tags, lifting) eq_iff Rep_index index_insert.rep_eq index_to_set.rep_eq insertE mem_Collect_eq subsetI)

lift_definition index_remove :: ‹('f, 'v) index ⇒ ('f, 'v) term ⇒ ('f, 'v) index› is ‹λtr. λt. remove_term tr t t›
  by (metis complete_storage_alt_def remove_preserves_complete remove_preserves_minimal remove_preserves_structure remove_preserves_sound sound_storage_alt_def subterm_at_path.intros(1))

theorem index_remove_spec: ‹index_to_set (index_remove tr t) = index_to_set tr - {t}›
  by (metis (no_types, lifting) Rep_index index_remove.rep_eq index_to_set.rep_eq mem_Collect_eq to_set_remove)

lift_definition index_retrieve_unifications :: ‹('f, 'v) index ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› is retrieve_unifications.

theorem index_retrieve_unifications_spec: ‹index_retrieve_unifications tr t1 = {t2. t2 ∈ index_to_set tr ∧ linear_unification t1 t2}›
  using retrieve_unifications_in_set retrieve_unifications_sound retrieve_unifications_complete sound_storage_alt_def complete_storage_alt_def subterm_at_path_empty
  by (smt (verit, best) Rep_index index_retrieve_unifications.rep_eq index_to_set.rep_eq mem_Collect_eq set_eqI)

lift_definition index_retrieve_variants :: ‹('f, 'v) index ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› is retrieve_variants.

theorem index_retrieve_variant_spec: ‹index_retrieve_variants tr t1 = {t2. t2 ∈ index_to_set tr ∧ linear_variant t2 t1}›
  using retrieve_variants_in_set retrieve_variants_sound retrieve_variants_complete sound_storage_alt_def complete_storage_alt_def subterm_at_path_empty
  by (smt (verit, best) Rep_index index_retrieve_variants.rep_eq index_to_set.rep_eq mem_Collect_eq set_eqI)

lift_definition index_retrieve_instances :: ‹('f, 'v) index ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› is retrieve_instances.

theorem index_retrieve_instances_spec: ‹index_retrieve_instances tr t1 = {t2. t2 ∈ index_to_set tr ∧ linear_instance t2 t1}›
  using retrieve_instances_in_set retrieve_instances_sound retrieve_instances_complete sound_storage_alt_def complete_storage_alt_def subterm_at_path_empty
  by (smt (verit, best) Rep_index index_retrieve_instances.rep_eq index_to_set.rep_eq mem_Collect_eq set_eqI)

lift_definition index_retrieve_generalizations :: ‹('f, 'v) index ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› is retrieve_generalizations.

theorem index_retrieve_generalizations_spec: ‹index_retrieve_generalizations tr t1 = {t2. t2 ∈ index_to_set tr ∧ linear_instance t1 t2}›
  using retrieve_generalizations_in_set retrieve_generalizations_sound retrieve_generalizations_complete sound_storage_alt_def complete_storage_alt_def subterm_at_path_empty
  by (smt (verit, best) Rep_index index_retrieve_generalizations.rep_eq index_to_set.rep_eq mem_Collect_eq set_eqI)

end