Theory Discrimination_Tree

theory Discrimination_Tree
  imports
    Linear_Unification
    Update_Map_Entries
begin

section ‹Discrimination trees›

datatype (plugins del: size) ('f,'v) dt_trie =
  DTLeaf ‹('f,'v) term set›
| is_DTNode: DTNode ‹(('f symbol , ('f, 'v) dt_trie) fmap)›

abbreviation empty_dt_trie :: ‹('f, 'v) dt_trie› where ‹empty_dt_trie ≡ DTNode fmempty›

function (domintros) depth_dt_trie :: ‹('f,'v) dt_trie ⇒ nat› where
  ‹depth_dt_trie (DTLeaf t) = 1›
| ‹depth_dt_trie (DTNode m) = Suc (Max (depth_dt_trie ` (fmran' m)))›
  by pat_completeness auto
termination
proof (intro allI)
  fix x :: ‹('f, 'v) dt_trie›
  show ‹depth_dt_trie_dom x›
  proof (induction x)
    case (DTLeaf ts)
    then show ?case
      by (simp add: depth_dt_trie.domintros(1))
  next
    case (DTNode m)
    then show ?case
      using depth_dt_trie.domintros(2) by blast
  qed
qed

instantiation dt_trie :: (type, type) size
begin

definition size_dt_trie where
  size_dt_trie_overloaded_def: ‹size_dt_trie = depth_dt_trie›
instance ..

end

lemma subdt_trie_size_lt [simp]: ‹x ∈ fmran' m ⟹ size x < size (DTNode m)›
  by (simp add: fmran'_alt_def le_imp_less_Suc size_dt_trie_overloaded_def)

fun to_set :: ‹('f,'v) dt_trie ⇒ ('f,'v) term set› where
  ‹to_set (DTLeaf s) = s›
| ‹to_set (DTNode m) = ⋃ (to_set ` (fmran' m))›


inductive subdt_trie_at_path :: ‹('f, 'v) dt_trie ⇒ ('f symbol) list ⇒ ('f, 'v) dt_trie ⇒ bool› where
  subdt_trie_at_path_empty: ‹subdt_trie_at_path t [] t›
| subdt_trie_at_path_step: ‹m $$ s = Some tr ⟹ subdt_trie_at_path tr p t0 ⟹ subdt_trie_at_path (DTNode m) (s # p) t0›

lemma subdt_trie_at_path_trans: ‹subdt_trie_at_path tr1 p1 tr2 ⟹ subdt_trie_at_path tr2 p2 tr3 ⟹ subdt_trie_at_path tr1 (p1 @ p2) tr3›
proof (induction p1 arbitrary: tr1)
  case Nil
  then show ?case
    using subdt_trie_at_path.cases by auto
next
  case (Cons a p1)
  then show ?case
    by (smt (verit, ccfv_threshold) Cons_eq_appendI list.distinct(1) list.inject subdt_trie_at_path.simps)
qed

lemma subdt_toset: ‹subdt_trie_at_path tr p (DTLeaf (insert t ts)) ⟹ t ∈ to_set tr›
proof (induction tr arbitrary: ts p)
  case (DTLeaf ts2) 
  then show ?case
    using subdt_trie_at_path.cases by auto
next
  case (DTNode m)
  then obtain s tr p2 where ‹m $$ s = Some tr›
                        and ‹subdt_trie_at_path tr p2 (DTLeaf (insert t ts))›
    by (metis dt_trie.distinct(1) dt_trie.sel(2) subdt_trie_at_path.simps)
  then show ?case
    by (metis DTNode.IH UN_I fmran'I to_set.simps(2))
qed

subsection ‹Preliminaries: term traversal›

text ‹This subsection defines the extended positions of a term, which include its standard
      positions plus a special position ‹None› that corresponds to the end of the traversal of that
      term. Two functions ‹after_position› and ‹next_position› are also defined, they are used to
      enumerate extended positions in the order in which they are visited in a preorder traversal.
      These functions are used to retrieve terms from the index.›

type_synonym epos = ‹pos option›

fun eposs :: ‹('f, 'v) term  ⇒ epos set› where
 ‹eposs t = insert None (Some ` poss t)›

lemma finite_eposs: ‹finite (eposs t)›
  by simp

lemma nil_in_eposs: ‹Some [] ∈ eposs t›
  by simp

lemma None_in_eposs: ‹None ∈ eposs t›
  by simp

lemma poss_in_eposs: ‹p ∈ poss t ⟹ Some p  ∈ eposs t›
  by simp

fun after_position :: ‹('f, 'v) term ⇒ pos ⇒ epos› where
  ‹after_position t [] = None›
| ‹after_position t p = (let i = last p; ps = butlast p in
                         if Suc i < arity (t |_ ps)
                         then Some (ps @ [Suc i])
                         else after_position t ps)›
  
fun next_position :: ‹('f, 'v) term ⇒ pos ⇒ epos› where
  ‹next_position t p = (if arity (t |_ p) = 0 then after_position t p else Some (p @ [0]))›

lemma after_position_subterm: ‹p1 ∈ poss t ⟹ after_position (t |_ p1) p2 = Some p3 ⟹ after_position t (p1 @ p2) = Some (p1 @ p3)›
proof (induction p2 rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc i ps)
  then show ?case
    by (smt (verit, best) after_position.elims append.assoc option.inject snoc_eq_iff_butlast subt_at_append)
qed

lemma next_position_subterm: ‹p1 ∈ poss t ⟹ next_position (t |_ p1) p2 = Some p3 ⟹ next_position t (p1 @ p2) = Some (p1 @ p3)›
  using after_position_subterm by fastforce

lemma in_after_poss: 
  assumes ‹p ∈ poss t› 
    and ‹after_position t p = Some q› 
  shows ‹q ∈ poss t›
  using assms
proof (induction p rule: rev_induct)
  case Nil
  then show ?case by simp
next
  case (snoc i ps)
  then show ?case
  proof (cases ‹arity (t |_ ps)›)
    case 0
    then show ?thesis
      by (smt (verit, del_insts) after_position.elims args_poss arity.simps(2) butlast_snoc empty_pos_in_poss option.distinct(1) option.inject poss_Cons_poss
          poss_append_poss snoc.IH snoc.prems(1,2) term.sel(4))
  next
    case (Suc _)
    then show ?thesis
      by (smt (verit) after_position.elims append_is_Nil_conv args_poss arity.simps(2) butlast_snoc empty_pos_in_poss option.inject poss_Cons_poss poss_append_poss
          snoc.IH snoc.prems(1,2) term.sel(4))
  qed
qed

lemma next_position_in_poss:  
  assumes ‹p ∈ poss t›
      and ‹next_position t p = Some q› 
    shows ‹q ∈ poss t›
  using assms
  by (smt (verit, del_insts) arity.elims empty_pos_in_poss in_after_poss length_greater_0_conv list.size(3) next_position.simps option.inject poss_Cons_poss
      poss_append_poss term.sel(4))

lemma in_after_eposs: 
  assumes ‹p ∈ poss t› 
    shows ‹after_position t p ∈ eposs t›
  using in_after_poss assms
  by (metis eposs.elims in_these_eq insertCI option.exhaust_sel these_image_Some_eq)

lemma next_position_in_eposs:  
  assumes ‹p ∈ poss t› 
   shows  ‹next_position t p ∈ eposs t›
  by (metis assms eposs.elims image_eqI in_after_eposs insertCI next_position.elims next_position_in_poss)

lemma after_position_none_butlast: ‹after_position t (ps @ [i]) = None ⟹ after_position t ps = None›
  by (smt (verit, ccfv_SIG) after_position.elims option.discI snoc_eq_iff_butlast)

lemma after_position_last:
  assumes ‹after_position t p1 = Some p2›
  obtains i where ‹last p2 = Suc i›
  using assms
proof (induction p1 rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc i ps)
  then show ?case
    by (smt (verit, best) after_position.elims butlast_snoc last_snoc option.distinct(1) option.inject)
qed

lemma before_position_none:
  assumes ‹after_position t p1 = None›
      and ‹p1 ∈ poss t›
    shows ‹∀p2 i p3. p1 = p2 @ [i] @ p3 ⟶ arity (t |_ p2) = Suc i›
  using assms
proof (induction p1 rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc i ps)
  show ?case
  proof (cases ‹Suc i < arity (t |_ ps)›)
    case True
    then show ?thesis
      by (smt (verit, best) after_position.elims butlast_snoc last_snoc length_append_singleton list.size(3) old.nat.distinct(1) option.distinct(1)
          snoc.prems(1))
  next
    case False
    then have ‹Suc i = arity (t |_ ps)›
      by (metis Suc_lessI snoc.prems(2) args_poss arity.simps(2) subterm_poss_conv)
    then show ?thesis
      by (smt (verit, ccfv_SIG) False after_position.elims append.right_neutral append_is_Nil_conv butlast_append butlast_snoc last_snoc poss_append_poss snoc.IH
          snoc.prems(1,2))
  qed
qed

lemma before_position_some:
  assumes ‹after_position t p1 = Some p2›
      and ‹p1 ∈ poss t›
    shows ‹∃p3. p1 = butlast p2 @ (last p2 - 1) # p3 ∧ (∀p5 i p6. p3 = p5 @ [i] @ p6 ⟶ arity (t |_ (butlast p2 @ (last p2 - 1) # p5)) = Suc i)›
  using assms
proof (induction p1 arbitrary: p2 rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc i ps)
  then have h: ‹ps ∈ poss t› by simp
  show ?case
  proof (cases ‹Suc i < arity (t |_ ps)›)
    case True
    then have ‹p2 = ps @ [Suc i]›
      by (smt (verit) Nil_is_append_conv after_position.elims butlast_snoc last_snoc list.discI option.inject snoc.prems(1))
    then show ?thesis by auto
  next
    case False
    then have ‹after_position t ps = Some p2›
      by (smt (verit, best) after_position.elims snoc.prems(1) snoc_eq_iff_butlast)
    then obtain p3 where ‹ps = butlast p2 @ (last p2 - 1) # p3›
                     and ‹∀p5 i p6. p3 = p5 @ [i] @ p6 ⟶ arity (t |_ (butlast p2 @ (last p2 - 1) # p5)) = Suc i›
      using snoc.IH [of p2] h by blast
    moreover have ‹arity (t |_ ps) = Suc i›
      by (metis False snoc.prems(2) Suc_lessI args_poss arity.simps(2) subterm_poss_conv)
    ultimately show ?thesis
      by (smt (verit, ccfv_threshold) append.assoc append.right_neutral append_Cons butlast_append butlast_snoc last_appendL last_appendR last_snoc
          list.distinct(1))
  qed
qed

lemma before_position_prefix:
  assumes ‹ps1 ∈ poss t›
      and ‹ps2 ∈ poss t›
      and ‹after_position t ps1 = after_position t ps2›
    shows ‹prefix ps1 ps2 ∨ prefix ps2 ps1›
proof -
  obtain ps3 ps1' ps2' where h0: ‹ps1 = ps3 @ ps1'›
                         and h1: ‹ps2 = ps3 @ ps2'›
                         and h2: ‹∀p2 i p3. ps1' = p2 @ [i] @ p3 ⟶ arity (t |_ (ps3 @ p2)) = Suc i›
                         and h3: ‹∀p2 i p3. ps2' = p2 @ [i] @ p3 ⟶ arity (t |_ (ps3 @ p2)) = Suc i›
  proof (cases ‹after_position t ps1›)
    case None
    then show ?thesis
      by (smt (verit, del_insts) assms before_position_none eq_Nil_appendI that)
  next
    case (Some p)
    obtain p3 where ‹ps1 = (butlast p @ [last p - 1]) @ p3›
                and ‹∀p5 i p6. p3 = p5 @ [i] @ p6 ⟶ arity (t |_ ((butlast p @ [last p - 1]) @ p5)) = Suc i›
      using assms before_position_some [of t ps1 p] Some by auto
    moreover obtain p4 where ‹ps2 = (butlast p @ [last p - 1]) @ p4›
                and ‹∀p5 i p6. p4 = p5 @ [i] @ p6 ⟶ arity (t |_ ((butlast p @ [last p - 1]) @ p5)) = Suc i›
      using assms before_position_some [of t ps2 p] Some by auto
    ultimately show ?thesis
      using that by blast
  qed
  from h2 h3 have ‹prefix ps1' ps2' ∨ prefix ps2' ps1'›
  proof (induction ps1' arbitrary: ps2' ps3)
    case Nil
    then show ?case by simp
  next
    case (Cons i ps1'')
    then show ?case
    proof (cases ps2')
      case Nil
      then show ?thesis by auto
    next
      case (Cons j ps2'')
      then have ‹i = j›
        using Cons.prems(1,2) by fastforce
      then have ‹prefix ps1'' ps2'' ∨ prefix ps2'' ps1''›
        using Cons.IH [of ‹ps3 @ [i]› ps2''] Cons.prems(1,2) local.Cons by auto
      then show ?thesis
        using local.Cons ‹i = j› by auto
    qed
  qed
  then show ?thesis
    using h0 h1 by auto
qed

lemma unique_leaf_position:
  assumes ‹p1 ∈ poss t›
      and ‹prefix p2 p1›
      and ‹arity (t |_ p2) = 0›
    shows ‹p1 = p2›
proof -
  obtain p3 where h: ‹p1 = p2 @ p3›
    using assms(2) prefix_def by blast
  then have ‹p3 = []›
    by (smt (verit, ccfv_threshold) Cons_poss_Var arity.elims assms(1,3) bot_nat_0.extremum_strict h poss_Cons_poss poss_append_poss term.sel(4) subt_at.elims)
  then show ?thesis using h by auto
qed

lemma before_position_unique_leaf:
  assumes ‹p1 ∈ poss t›
      and ‹p2 ∈ poss t›
      and ‹after_position t p1 = after_position t p2›
      and ‹arity (t |_ p1) = 0›
      and ‹arity (t |_ p2) = 0›
    shows ‹p1 = p2›
  using assms before_position_prefix unique_leaf_position by blast

lemma previous_position_injective:
  assumes ‹p1 ∈ poss t›
      and ‹p2 ∈ poss t›
      and ‹next_position t p1 = next_position t p2›
    shows ‹p1 = p2›
proof (cases ‹arity (t |_ p1)›)
  case 0
  then have h: ‹next_position t p2 = after_position t p1› using assms(3) by auto
  then show ?thesis
  proof (cases ‹arity (t |_ p2)›)
    case 0
    then have ‹after_position t p1 = after_position t p2› using h by auto
    then show ?thesis using before_position_unique_leaf
      by (metis 0 after_position_last assms last_snoc next_position.simps old.nat.distinct(1))
  next
    case (Suc _)
    then have ‹after_position t p1 = Some (p2 @ [0])› using h by auto
    then show ?thesis using after_position_last by force
  qed
next
  case (Suc _)
  then have h: ‹next_position t p2 = Some (p1 @ [0])› using assms(3) by auto
  show ?thesis
  proof (cases ‹arity (t |_ p2)›)
    case 0
    then have ‹after_position t p2 = Some (p1 @ [0])›
      using h by force
    then show ?thesis using after_position_last by force
  next
    case (Suc _)
    then show ?thesis using h by auto
  qed
qed

lemma after_position_non_empty [simp]: ‹after_position t u ≠ Some []›
  proof (induction t u rule: after_position.induct)
  case (1 t)
  then show ?case by simp
next
  case (2 t v va)
  then show ?case by (simp add: Let_def del: last.simps butlast.simps split: if_splits) 
qed
 
lemma next_position_non_empty [simp]: ‹next_position t u ≠ Some []›
  by auto

fun preorder_positions :: ‹('f, 'v) term ⇒ pos list› where
  ‹preorder_positions (Var x) = [[]]›
| ‹preorder_positions (Fun f f_args) = [] # concat (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args])›

lemma preorder_positions_poss: ‹set (preorder_positions t) = poss t›
  by (induction t; auto)

lemma preorder_positions_distinct: ‹distinct (preorder_positions t)›
proof (induction t)
  case (Var x)
  then show ?case by auto
next
  case (Fun f f_args)
  have ‹distinct (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args])›
    using distinct_map [of ‹(λi. map ((#) i) (preorder_positions (f_args ! i)))› ‹[0..<length f_args]›]
    by (smt (verit, ccfv_SIG) distinct_upt length_greater_0_conv linorder_inj_onI' list.distinct(1) list.inject map_nth_conv nat_less_le preorder_positions.elims)
  moreover have ‹(⋀ys. ys ∈ set (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]) ⟹ distinct ys)›
    using Fun distinct_conv_nth by force
  ultimately have ‹distinct (concat (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]))›
    using distinct_concat [of ‹map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]›] by force
  then show ?case by auto
qed

lemma preorder_positions_distinct_nth: ‹i < length (preorder_positions t) ⟹ j < length (preorder_positions t) ⟹ preorder_positions t ! i = preorder_positions t ! j ⟹ i = j›
  using preorder_positions_distinct distinct_conv_nth by auto

lemma preorder_string_preorder_positions:
  ‹preorder_string t = map (λp. root_symbol (t |_ p)) (preorder_positions t)›
proof (induction t)
  case (Var x)
  then show ?case by simp
next
  case (Fun f f_args)
  have ‹concat (map preorder_string f_args) = concat (map (λi. preorder_string (f_args ! i)) [0..<length f_args])›
    by (simp add: map_upt_len_conv)
  also have ‹... = concat (map (λi. map (λp. root_symbol (f_args ! i |_ p)) (preorder_positions (f_args ! i))) [0..<length f_args])›
    using Fun.IH by (smt (verit, best) length_map map_equality_iff map_nth nth_map nth_mem)
  also have ‹... = concat (map (map (λp. root_symbol (Fun f f_args |_ p))) (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]))›
    by (smt (verit, ccfv_SIG) length_map map_equality_iff nth_map subt_at.simps(2))
  also have ‹... = map (λp. root_symbol (Fun f f_args |_ p)) (concat (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]))›
    using List.map_concat by metis
  finally show ?case by auto
qed

lemma hd_preorder_positions: ‹∃l. preorder_positions t = [] # l›
  by (meson preorder_positions.elims)

lemma split_enumeration:
  assumes ‹i ≤ j› and ‹[i..<j] = l1 @ l2›
  shows ‹∃k. i ≤ k ∧ k ≤ j ∧ l1 = [i..<k] ∧ l2 = [k..< j]›
  using assms
proof (induction l1 arbitrary: l2 i)
  case Nil
  then show ?case by force
next
  case (Cons _ _)
  then show ?case
    by (smt (z3) append_Cons le_trans lessI order.strict_iff_not upt_Suc upt_conv_Cons upt_eq_Cons_conv)
qed

lemma last_concat: ‹xs ≠ [] ⟹ last xs ≠ [] ⟹ last (concat xs) = last (last xs)›
  by (metis append.right_neutral concat.simps(1,2) concat_append last_appendR snoc_eq_iff_butlast)

lemma last_preorder_position: ‹f_args ≠ [] ⟹ last (preorder_positions (Fun f f_args)) = (length f_args - 1) # last (preorder_positions (last f_args))›
proof -
  assume h0: ‹f_args ≠ []›
  have ‹⋀ x. x ∈ set (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]) ⟹ x ≠ []›
    by (metis (no_types, lifting) ex_map_conv hd_preorder_positions list.simps(3) map_is_Nil_conv)
  then have h1: ‹concat (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]) ≠ []›
    using h0 by auto
  then have ‹last (preorder_positions (Fun f f_args)) = last (concat (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]))› by auto
  also have ‹... = last (last (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]))›
    by (metis (no_types, lifting) Nil_is_map_conv h1 concat.simps(1) hd_preorder_positions last_concat last_map
        list.simps(3))
  ultimately show ?thesis
    by (metis (no_types, lifting) h0 diff_zero last_conv_nth last_map last_upt length_greater_0_conv length_upt list.distinct(1) preorder_positions.elims)
qed

lemma arity_last_preorder_position [simp]: ‹arity (t |_ last (preorder_positions t)) = 0›
proof (induction t)
  case (Var x)
  then show ?case by auto
next
  case (Fun f f_args)
  then show ?case
  proof (cases f_args rule: rev_exhaust)
    case Nil
    then show ?thesis by auto
  next
    case (snoc f_args' a)
    then have ‹arity (a |_ last (preorder_positions a)) = 0›
      by (simp add: Fun)
    moreover have ‹last (preorder_positions (Fun f f_args)) = (length f_args - 1) # last (preorder_positions a)›
      by (metis last_preorder_position snoc snoc_eq_iff_butlast)
    ultimately show ?thesis
      by (simp add: snoc)
  qed
qed

lemma trans_subt: ‹i < arity t ⟹ t |_ (i # p) = t |_ [i] |_ p›
  by (metis arity.simps(1) not_less0 root.cases subt_at.simps(1,2))

lemma args_subt_at: ‹0 < arity t ⟹ args t ! i = subt_at t [i]›
  by (metis arity.simps(1) less_not_refl subt_at.simps(1,2) term.exhaust_sel)

lemma next_position_arg_next:
  assumes ‹i # p2 ∈ poss t›
      and ‹next_position (t |_ [i]) p2 = Some p3›
    shows ‹next_position t (i # p2) = Some (i # p3)›
proof (cases ‹arity (t |_ [i] |_ p2)›)
  case 0
  then have h: ‹Some p3 = after_position (t |_ [i]) p2› using assms(2) by auto
  have ‹next_position t (i # p2) = after_position t (i # p2)› using assms(1) 0 by auto
  also have ‹... = Some (i # p3)› using h
  proof (induction p2 rule: rev_induct)
    case Nil
    then show ?case by auto
  next
    case (snoc j p4)
    then show ?case
    proof (cases ‹Suc j < arity (t |_ [i] |_ p4)›)
      case True
      then show ?thesis
        by (smt (verit, best) after_position.elims append_Cons args_poss arity.simps(2) assms(1) butlast.simps(2) butlast_snoc last_snoc list.discI option.inject snoc.prems trans_subt)
    next
      case False
      then show ?thesis
        by (smt (verit, best) Nil_is_append_conv after_position.elims after_position.simps(2) args_poss arity.simps(2) assms(1) butlast.simps(2) butlast_snoc last.simps last_snoc snoc.IH snoc.prems
            trans_subt)
    qed
  qed
  finally show ?thesis by auto
next
  case (Suc _)
  then show ?thesis using assms by auto
qed

lemma after_position_append:
  assumes ‹after_position t p1 = Some p›
      and ‹⋀ ps1 j ps2. p2 = ps1 @ j # ps2 ⟹ Suc j = arity (t |_ (p1 @ ps1))›
    shows ‹after_position t (p1 @ p2) = Some p›
  using assms
proof (induction p2 rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc j ps)
  then have ‹Suc j = arity (t |_ (p1 @ ps))› by blast
  then have ‹after_position t (p1 @ ps @ [j]) = after_position t (p1 @ ps)›
    by (smt (verit, ccfv_SIG) after_position.elims append_assoc less_not_refl snoc_eq_iff_butlast)
  then show ?case
    by (metis append.assoc append_Cons snoc.IH snoc.prems(1,2))
qed

lemma last_preorder_position_arity: ‹⋀ps1 j ps2. last (preorder_positions t) = ps1 @ j # ps2 ⟹ Suc j = arity (t |_ ps1)›
proof (induction t)
  case (Var x)
  then show ?case by auto
next
  case (Fun f f_args)
  then show ?case
  proof (cases ps1)
    case Nil
    then show ?thesis
      by (metis (lifting) Fun.prems One_nat_def Suc_pred add_less_same_cancel1 append.left_neutral arity.simps(2) last_in_set last_preorder_position list.discI list.sel(1) list.size(3) not_add_less1
          not_gr0 poss_Cons_poss preorder_positions.elims preorder_positions_poss subt_at.simps(1) term.sel(4))
  next
    case (Cons a ps1')
    then have ‹ps1' @ j # ps2 = last (preorder_positions (last f_args))›
      by (metis (lifting) Fun.prems append_Cons last_in_set last_preorder_position list.distinct(1) list.inject preorder_positions.elims preorder_positions_poss subt_at_nepos_imp_supt
          supt_const)
    then show ?thesis
      by (metis (no_types, lifting) Fun.IH Fun.prems append_Cons last_conv_nth last_in_set last_preorder_position list.distinct(1) list.inject local.Cons preorder_positions.simps(2)
          preorder_positions_poss subt_at.simps(2) subt_at_nepos_imp_supt supt_const)
  qed
qed

lemma after_position_arg_after: ‹Suc i < arity t ⟹
  after_position t (i # last (preorder_positions (t |_ [i]))) = Some ([Suc i])›
proof -
  assume h0: ‹Suc i < arity t›
  have h1: ‹arity (t |_ [i] |_ last (preorder_positions (t |_ [i]))) = 0› by auto
  have h2: ‹after_position t [i] = Some ([Suc i])› using h0 by fastforce
  have h3: ‹⋀ ps1 j ps2. last (preorder_positions (t |_ [i])) = ps1 @ j # ps2 ⟹ Suc j = arity (t |_ (i # ps1))›
    by (metis last_preorder_position_arity Suc_lessD h0 trans_subt)
  then show ?thesis
    by (metis after_position_append append.left_neutral append_Cons h2 h3)
qed

lemma next_position_arg_after: ‹Suc i < arity t ⟹
  next_position t (i # last (preorder_positions (t |_ [i]))) = Some ([Suc i])›
proof -
  assume h0: ‹Suc i < arity t›
  have h1: ‹arity (t |_ [i] |_ last (preorder_positions (t |_ [i]))) = 0› by auto
  then have ‹after_position t (i # last (preorder_positions (t |_ [i]))) = Some ([Suc i])›
    using h0 after_position_arg_after by blast
  then show ?thesis
    by (metis h0 h1 Suc_lessD next_position.simps trans_subt)
qed

lemma preorder_positions_ordered_by_next:
  assumes ‹preorder_positions t = l1 @ p1 # p2 # l2›
    shows ‹next_position t p1 = Some p2›
  using assms
proof (induction t arbitrary: l1 p1 p2 l2)
  case (Var x)
  then show ?case by auto
next
  case (Fun f f_args)
  show ?case
  proof (cases f_args)
    case Nil
    then show ?thesis using Fun.prems by auto
  next
    case (Cons a f_args')
    show ?thesis
    proof (cases l1)
      case Nil
      then have ‹p2 # l2 = map ((#) 0) (preorder_positions a) @ concat (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [1..<length f_args])›
        using upt_rec Fun.prems by (simp add: local.Cons)
      then have ‹p2 = [0]› using hd_preorder_positions [of a] by force
      moreover have ‹p1 = []›
        using Fun.prems local.Nil by auto
      ultimately show ?thesis
        by (simp add: local.Cons)
    next
      case (Cons _ l1')
      then have ‹l1' @ p1 # p2 # l2 = concat (map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args])›
        using Fun.prems by auto
      then obtain xss1 xs xs' xss2 where h0: ‹map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args] = xss1 @ (xs @ xs') # xss2›
                                     and h1: ‹l1' @ [p1] = concat xss1 @ xs›
                                     and h2: ‹p2 # l2 = xs' @ concat xss2›
        using List.concat_eq_appendD [of ‹map (λi. map ((#) i) (preorder_positions (f_args ! i))) [0..<length f_args]› ‹l1' @ [p1]› ‹[p2] @ l2›] by fastforce
      then consider (a) ‹xs = [] ∧ xs' = []›
        | (b) ‹xs = [] ∧ xs' ≠ []›
        | (c) ‹xs ≠ [] ∧ xs' = []›
        | (d) ‹xs ≠ [] ∧ xs' ≠ []› by blast
      then show ?thesis
      proof (cases)
        case a
        then show ?thesis
          by (metis (no_types, lifting) Nil_is_map_conv append.right_neutral ex_map_conv h0 hd_preorder_positions in_set_conv_decomp list.distinct(1))
      next
        case b
        then obtain us vs where h3: ‹[0..<length f_args] = us @ vs›
                            and h4: ‹xss1 = map (λi. map ((#) i) (preorder_positions (f_args ! i))) us›
                            and h5: ‹xs' # xss2 = map (λi. map ((#) i) (preorder_positions (f_args ! i))) vs›
          using h0 List.map_eq_append_conv [of _ ‹[0..<length f_args]› xss1 ‹xs' # xss2›] by force
        then obtain j where h6: ‹0 < j ∧ j < length f_args›
                        and h7: ‹us = [0..<j]›
                        and h8: ‹vs = [j..<length f_args]›
          by (metis (lifting) Nil_is_append_conv b concat.simps(1) h1 list.distinct(1) list.simps(8) split_enumeration upt_rec zero_le)
        have ‹p1 = (j - 1) # last (preorder_positions (f_args ! (j - 1)))›
          by (metis (no_types, lifting) Nil_is_map_conv append.right_neutral b h1 h4 h6 h7 hd_preorder_positions last_concat last_map last_upt list.distinct(1) snoc_eq_iff_butlast upt_rec)
        moreover have ‹p2 = [j]›
          by (metis (no_types, lifting) b h2 h5 h6 h8 hd_append2 hd_preorder_positions list.distinct(1) list.map_sel(1) list.sel(1) upt_conv_Cons)
        ultimately show ?thesis
          by (metis Suc_diff_1 arity.simps(2) h6 next_position_arg_after subt_at.simps(1,2))
      next
        case c
        then obtain us vs where h3: ‹[0..<length f_args] = us @ vs›
                            and h4: ‹xss1 @ [xs] = map (λi. map ((#) i) (preorder_positions (f_args ! i))) us›
                            and h5: ‹xss2 = map (λi. map ((#) i) (preorder_positions (f_args ! i))) vs›
          using h0 List.map_eq_append_conv [of _ ‹[0..<length f_args]› ‹xss1 @ [xs]› xss2] by force
        then obtain j where h6: ‹0 < j ∧ j < length f_args›
                        and h7: ‹us = [0..<j]›
                        and h8: ‹vs = [j..<length f_args]›
          by (metis (no_types, lifting) Nil_is_append_conv c concat.simps(1) h2 length_0_conv length_map list.distinct(1) split_enumeration upt_rec zero_le)
        have ‹p1 = (j - 1) # last (preorder_positions (f_args ! (j - 1)))›
          by (metis (no_types, lifting) Suc_le_D Suc_pred' c h1 h4 h6 h7 hd_preorder_positions last_ConsL last_appendR last_map last_upt list.distinct(1) old.nat.distinct(1) upt_eq_Nil_conv)
        moreover have ‹p2 = [j]›
          by (metis (no_types, lifting) Nil_is_map_conv append_Nil c h2 h5 h6 h8 hd_concat hd_preorder_positions hd_upt length_upt less_not_refl list.distinct(1) list.map_sel(1) list.sel(1) list.size(3)
              zero_less_diff)
        ultimately show ?thesis
          by (metis Suc_diff_1 arity.simps(2) h6 next_position_arg_after subt_at.simps(1,2))
      next
        case d
        obtain us vs where h3: ‹[0..<length f_args] = us @ vs›
                       and h4: ‹xss1 = map (λi. map ((#) i) (preorder_positions (f_args ! i))) us›
                       and h5: ‹(xs @ xs') # xss2 = map (λi. map ((#) i) (preorder_positions (f_args ! i))) vs›
          using List.map_eq_append_conv [of ‹(λi. map ((#) i) (preorder_positions (f_args ! i)))› ‹[0..<length f_args]› xss1 ‹(xs @ xs') # xss2›] using h0 by fastforce
        then obtain j where h6: ‹j < length f_args›
                        and h7: ‹us = [0..<j]›
                        and h8: ‹vs = [j..<length f_args]›
          by (metis (no_types, lifting) list.distinct(1) list.simps(8) split_enumeration upt_rec zero_order(1))
        then have h9: ‹map ((#) j) (preorder_positions (f_args ! j)) = xs @ xs'›
          using h5 upt_rec by auto
        then obtain us2 vs2 where h9: ‹preorder_positions (f_args ! j) = us2 @ vs2›
                              and h10: ‹xs = map ((#) j) us2›
                              and h11: ‹xs' = map ((#) j) vs2› using List.map_eq_append_conv by meson
        then obtain l3 p3 p4 l4 where h12: ‹us2 = l3 @ [p3]›
                                  and h13: ‹vs2 = p4 # l4›
          by (metis d Nil_is_map_conv concat_lists.cases rev_exhaust)
        then have ‹next_position (f_args ! j) p3 = Some p4›
          using Fun.IH h9 h6 by auto
        moreover have ‹p1 = j # p3› using h1 h10 h12 by auto
        moreover have ‹p2 = j # p4› using h11 h13 h2 by auto
        ultimately show ?thesis
          by (metis next_position_arg_next subt_at.simps(1,2) Fun.prems preorder_positions_poss in_set_conv_decomp)
      qed
    qed
  qed
qed

lemma after_position_none_superterm:
  assumes ‹after_position t ps = None›
    shows ‹after_position (Fun f (f_args @ [t])) (length f_args # ps) = None›
  using assms
proof (induction ps rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc i ps1)
  then have ‹¬ Suc i < arity (t |_ ps1) ∧ after_position t ps1 = None›
    by (smt (verit, best) after_position.simps(2) after_position.elims option.distinct(1) snoc_eq_iff_butlast)
  then show ?case using snoc.IH by fastforce
qed

lemma after_position_none_subterm:
  assumes ‹after_position t (i # ps) = None›
      and ‹(i # ps) ∈ poss t›
    shows ‹after_position (t |_ [i]) ps = None›
  using assms
proof (induction ps rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc j ps1)
  then have ‹after_position t (i # ps1) = None›
    by (metis after_position_none_butlast append_Cons)
  moreover have ‹i # ps1 ∈ poss t› using snoc.prems(2) by simp
  ultimately have h0: ‹after_position (t |_ [i]) ps1 = None› using snoc.IH by blast
  have ‹¬ Suc j < arity (t |_ (i # ps1))› using after_position.simps(2) snoc.prems(1) option.distinct by auto
  then have h1: ‹¬ Suc j < arity ((t |_ [i]) |_ ps1)›
    using snoc.prems(2) by (simp add: subt_at_Cons_comp)
  show ?case
    using h0 h1 after_position.simps(2) [of ‹t |_ [i]› ‹hd (ps1 @ [j])› ‹tl (ps1 @ [j])›] by auto
qed

lemma preorder_positions_last:
  assumes ‹preorder_positions t = l1 @ [p1]›
  shows ‹next_position t p1 = None›
  using assms
proof (induction p1 arbitrary: t l1)
  case Nil
  then show ?case
    by (metis local.Nil next_position.simps after_position.simps(1) arity_last_preorder_position snoc_eq_iff_butlast)
next
  case (Cons i ps)
  then obtain f f_args where h0: ‹t = Fun f f_args›
    by (metis last_ConsL list.distinct(1) preorder_positions.cases preorder_positions.simps(1) snoc_eq_iff_butlast)
  then have ‹f_args ≠ []› using Cons.prems
    by auto
  then obtain f_args' t1 where h1: ‹f_args = f_args' @ [t1]› by (metis rev_exhaust)
  then obtain l2 where ‹preorder_positions t1 = l2 @ [ps]› using h0 preorder_positions.simps(2) [of f ‹f_args' @ [t1]›]
    by (metis Cons.prems hd_preorder_positions last_preorder_position length_butlast list.distinct(1) list.inject snoc_eq_iff_butlast)
  then have ‹next_position t1 ps = None› using Cons.IH by auto
  then have h2: ‹arity (t1 |_ ps) = 0 ∧ after_position t1 ps = None› 
    by (metis next_position.simps option.distinct(1))
  have h3: ‹i = length f_args'›
    by (metis Cons.prems append_Cons_nth_middle h0 h1 last_preorder_position length_butlast snoc_eq_iff_butlast)
  then have ‹t1 = f_args ! i› using h1 by force
  then have ‹arity (t |_ (i # ps)) = 0› using subt_at.simps(2) h0 h2 by auto
  moreover have ‹after_position t (i # ps) = None› using h0 h1 h2 h3 after_position_none_superterm [of t1 ps f f_args'] by fast
  ultimately show ?case by auto
qed

lemma preorder_positions_last2:
  assumes ‹next_position t p1 = None›
      and ‹p1 ∈ poss t›
    shows ‹last (preorder_positions t) = p1›
  using assms
proof (induction p1 arbitrary: t)
  case Nil
  then show ?case
  proof (cases t)
    case (Var x)
    then show ?thesis by auto
  next
    case (Fun f f_args)
    then show ?thesis
      by (metis (lifting) Nil.prems(1,2) append_butlast_last_id last_in_set list.distinct(1) preorder_positions.simps(2) preorder_positions_last preorder_positions_poss
          previous_position_injective)
  qed
next
  case (Cons i ps)
  then have h0: ‹arity (t |_ (i # ps)) = 0 ∧ after_position t (i # ps) = None›
    by (metis next_position.simps option.distinct(1))
  then have ‹after_position (t |_ [i]) ps = None›
    using after_position_none_subterm Cons.prems(2) by blast
  then have ‹next_position (t |_ [i]) ps = None›
    by (metis Cons.prems(2) h0 next_position.elims subt_at_Cons_comp)
  then have ‹last (preorder_positions (t |_ [i])) = ps› using Cons.IH [of ‹t |_ [i]›]
    by (metis Cons.prems(2) h0 after_position.simps(1) args_subt_at before_position_unique_leaf
        bot_nat_0.not_eq_extremum empty_pos_in_poss list.distinct(1) poss_Cons_poss subt_at.simps(1))
  then show ?case
    by (metis Cons.prems(1,2) hd_preorder_positions last_in_set list.distinct(1) preorder_positions_last preorder_positions_poss previous_position_injective
        snoc_eq_iff_butlast)
qed

lemma poss_induct [case_names empty next_pos in_poss]:
  assumes ‹P t []›
      and ‹⋀p1 p2. p1 ∈ poss t ⟹ P t p1 ⟹ next_position t p1 = Some p2 ⟹ P t p2›
      and ‹p ∈ poss t›
    shows ‹P t p›
proof -
  have ‹p ∈ poss t ⟹ P t p›
  proof (induction p rule: wf_induct [of ‹lexord {(i, j) | i j. i < j} ∩ {(p1, p2) | p1 p2. p1 ∈ poss t ∧ p2 ∈ poss t}›])
    case 1
    show ‹wf (lexord {(i, j) | i j. i < j} ∩ {(p1, p2) |p1 p2. p1 ∈ poss t ∧ p2 ∈ poss t})›
    proof (intro wf_finite_segments)
      show ‹irrefl (lexord {(i, j) | i j. i < j} ∩ {(p1, p2) |p1 p2. p1 ∈ poss t ∧ p2 ∈ poss t})›
        by (simp add: irreflI lexord_irreflexive)
    next
      show ‹trans (lexord {(i, j) | i j. i < j} ∩ {(p1, p2) |p1 p2. p1 ∈ poss t ∧ p2 ∈ poss t})›
        unfolding trans_def 
        by (smt (verit) Int_Collect less_than_iff lexord_partial_trans mem_Collect_eq prod.inject transE trans_less_than)
    next
      show ‹⋀x. finite {y. (y, x) ∈ lexord {(i, j) | i j. i < j} ∩ {(p1, p2) |p1 p2. p1 ∈ poss t ∧ p2 ∈ poss t}}› by auto
    qed
  next
    case (2 p)
    show ?case
    proof (cases p rule: rev_exhaust)
      case Nil
      then show ?thesis using 2 assms(1) by force
    next
      case (snoc ps i)
      then show ?thesis
      proof (cases i)
        case 0
        then have ‹next_position t ps = Some p›
          using 2 arity.elims snoc by force
        moreover have ‹P t ps› using 2 snoc
          by (simp add: lexord_append_rightI)
        ultimately show ?thesis using assms(2) [of ps p] 2 snoc by auto
      next
        case (Suc j)
        let ?ps2 = ‹last (preorder_positions (t |_ (ps @ [j])))›
        have h0: ‹i < arity (t |_ ps) ∧ j < arity (t |_ ps) ∧ ps @ [j] ∈ poss t› using 2 snoc Suc
          by (cases ‹t |_ ps›; auto)
        then have ‹after_position t (ps @ j # last (preorder_positions (t |_ (ps @ [j])))) = Some (ps @ [Suc j])›
          by (metis Suc after_position_arg_after after_position_subterm poss_append_poss subt_at_append)
        moreover have h1: ‹ps @ j # ?ps2 ∈ poss t› using h0 2 poss_append_poss [of ‹ps @ [j]› ‹last (preorder_positions (t |_ (ps @ [j])))› t]
          by (metis append.assoc append_Cons hd_preorder_positions last_in_set list.distinct(1) preorder_positions_poss self_append_conv2)
        moreover have ‹arity (t |_ (ps @ j # ?ps2)) = 0›
          by (metis h0 arity_last_preorder_position [of ‹t |_ (ps @ [j])›] poss_append_poss subt_at_append trans_subt)
        ultimately have ‹next_position t (ps @ j # ?ps2) = Some p› using snoc Suc by auto
        moreover have ‹P t (ps @ j # ?ps2)› using 2 h1 Suc snoc
          by (simp add: lexord_append_left_rightI)
        ultimately show ?thesis using assms(2) [of ‹ps @ j # ?ps2› p] h1 by fast
      qed
    qed
  qed
  then show ?thesis using assms(3) by auto
qed

lemma eposs_induct [case_names empty next_pos in_eposs]:
  assumes ‹P t (Some [])›
      and ‹⋀p. p ∈ poss t ⟹ P t (Some p) ⟹ P t (next_position t p)›
      and ‹ep ∈ eposs t›
    shows ‹P t ep›
proof -
  have h0: ‹∀p ∈ poss t. P t (Some p)›
    using poss_induct [of ‹λt p. P t (Some p)› t] assms by metis
  show ?thesis
  proof (cases ep)
    case None
    have ‹P t (Some (last (preorder_positions t)))›
      by (metis h0 list.distinct(1) preorder_positions_poss hd_preorder_positions last_in_set)
    moreover have ‹next_position t (last (preorder_positions t)) = None›
      by (metis hd_preorder_positions preorder_positions_last list.distinct(1) snoc_eq_iff_butlast)
    moreover have ‹last (preorder_positions t) ∈ poss t›
      by (metis last_in_set preorder_positions_poss hd_preorder_positions list.simps(3))
    ultimately show ?thesis using assms(2) None by force
  next
    case (Some p)
    then show ?thesis using h0 assms(3) by auto
  qed
qed

fun linear_generalization_preorder_strings :: ‹('f, 'v) term ⇒ 'f symbol list set›
  where
  ‹linear_generalization_preorder_strings (Var x) = { [Star] }›
| ‹linear_generalization_preorder_strings (Fun f f_args) = {[Star]} ∪
(#) (F f (length f_args)) ` concat ` listset (map linear_generalization_preorder_strings f_args)›

lemma linear_generalization_preorder_strings_alt_def:
  ‹linear_generalization_preorder_strings t = { [Star] } ∪ 
   (#) (root_symbol t) ` concat ` listset (map linear_generalization_preorder_strings (args t))›
  by (induction t ; auto)

lemma linear_generalization_preorder_strings_non_empty: ‹[] ∉ linear_generalization_preorder_strings t›
  by (simp add: image_iff linear_generalization_preorder_strings_alt_def)

lemma linear_generalization_preorder_strings_exists_term:
  ‹s ∈ linear_generalization_preorder_strings t ⟹ ∃t2. preorder_string t2 = s›
proof (induction t arbitrary: s)
  case (Var x)
  then have ‹s = [Star]› by auto
  then show ?case
    by (meson preorder_string.simps(1))
next
  case (Fun f f_args)
  then consider ‹s = [Star]›
              | ‹s ∈ (#) (F f (length f_args)) ` concat ` listset (map linear_generalization_preorder_strings f_args)›
    by fastforce
  then show ?case
  proof cases
    case 1
    then show ?thesis
      by (meson preorder_string.simps(1))
  next
    case 2
    then obtain l where h1: ‹s = (F f (length f_args)) # concat l›
                    and h2: ‹l ∈ listset (map linear_generalization_preorder_strings f_args)› by blast
    then have h3: ‹length l = length f_args ∧ (∀i < length f_args. (l ! i) ∈ linear_generalization_preorder_strings (f_args ! i))›
      by (simp add: listset)
    then have h4: ‹∀i < length l. ∃t2 :: ('a, 'c) term. preorder_string t2 = l ! i›
      using Fun.IH nth_mem by metis
    then have ‹∃l_args :: ('a, 'c) term list. length l = length l_args ∧ (∀i < length l. preorder_string (l_args ! i) = l ! i)›
    proof (induction l)
      case Nil
      then show ?case by auto
    next
      case (Cons s ss)
      obtain t :: ‹('a, 'c) term› where ‹preorder_string t = s› using Cons.prems by fastforce
      moreover obtain ts :: ‹('a, 'c) term list› where ‹length ss = length ts ∧ (∀i<length ss. preorder_string (ts ! i) = ss ! i)›
        by (metis Cons.IH Cons.prems Suc_less_eq length_Cons nth_Cons_Suc)
      ultimately have ‹length (s # ss) = length (t # ts) ∧ (∀i<length (s # ss). preorder_string ((t # ts) ! i) = (s # ss) ! i)›
        using less_Suc_eq_0_disj by force
      then show ?case by blast
    qed
    then obtain l_args :: ‹('a, 'c) term list› where ‹l = map preorder_string l_args› and ‹length f_args = length l_args›
      by (metis h3 map_nth_eq_conv)
    then have ‹preorder_string (Fun f l_args) = s› using h1 by auto
    then show ?thesis by blast
  qed
qed

lemma concat_linear_generalization_preorder_strings_decompose:
  assumes ‹l ∈ concat ` listset (map linear_generalization_preorder_strings f_args)›
  shows ‹∃ts :: ('a, 'b) term list. length ts = length f_args
                                  ∧ l = concat (map preorder_string ts)
                                  ∧ (∀i < length f_args. preorder_string (ts ! i) ∈ linear_generalization_preorder_strings (f_args ! i))›
  using assms
proof (induction f_args arbitrary: l)
  case Nil
  then show ?case by auto
next
  case (Cons t f_args')
  then obtain s1 s2 where h0: ‹l = s1 @ s2›
                      and h1: ‹s1 ∈ linear_generalization_preorder_strings t›
                      and h2: ‹s2 ∈ concat ` listset (map linear_generalization_preorder_strings f_args')›
    using set_Cons_def [of ‹linear_generalization_preorder_strings t› ‹listset (map linear_generalization_preorder_strings f_args')›]
    by auto
  obtain ts :: ‹('a, 'b) term list› where h3: ‹s2 = concat (map preorder_string ts)›
                                      and h4: ‹∀i<length f_args'. preorder_string (ts ! i) ∈ linear_generalization_preorder_strings (f_args' ! i)›
                                      and h5: ‹length ts = length f_args'›
    using Cons.IH [of s2] h2 by blast
  obtain t0 :: ‹('a, 'b) term› where h6: ‹preorder_string t0 = s1›
    using h1 linear_generalization_preorder_strings_exists_term by blast
  have ‹∀i<length (t # f_args'). preorder_string ((t0 # ts) ! i) ∈ linear_generalization_preorder_strings ((t # f_args') ! i)›
    by (simp add: h1 h4 h6 nth_Cons')
  moreover have ‹l = concat (map preorder_string (t0 # ts))› using h0 h3 h6 by auto
  ultimately show ?case
    by (metis length_Cons h5)
qed

lemma linear_generalization_preorder_strings_complete: ‹linear_instance t2 t1 ⟹ preorder_string t1 ∈ linear_generalization_preorder_strings t2›
proof (induction t1 arbitrary: t2)
  case (Var x)
  show ?case
    by (cases t2 ; auto)
next
  case f1: (Fun f f_args)
  show ?case
  proof (cases t2)
    case (Var y)
    then show ?thesis using f1
      using linear_instance.cases by blast
  next
    case f2: (Fun g g_args)
    then have h1: ‹g = f›
          and h2: ‹length g_args = length f_args›
          and ‹∀i<length f_args. linear_instance (g_args ! i) (f_args ! i)›
      using linear_instance.cases [of ‹Fun g g_args› ‹Fun f f_args›] f1 f2 by auto
    then have ‹∀i<length f_args. preorder_string (f_args ! i) ∈ linear_generalization_preorder_strings (g_args ! i)›
      using f1.IH by simp
    then have ‹concat (map preorder_string f_args) ∈ concat ` listset (map linear_generalization_preorder_strings g_args)›
      using h2
    proof (induction g_args arbitrary: f_args)
      case Nil
      then show ?case using h2 by auto
    next
      case (Cons t ts)
      then obtain u us where h3: ‹f_args = Cons u us ∧ length ts = length us›
        by (metis length_Suc_conv)
      then have ‹∀i<length us. preorder_string (us ! i) ∈ linear_generalization_preorder_strings (ts ! i)›
        using Cons.prems(1) by auto
      then have ‹concat (map preorder_string us) ∈ concat ` listset (map linear_generalization_preorder_strings ts)›
        using Cons.IH [of us] h3 by fastforce
      then obtain x where h4: ‹x ∈ listset (map linear_generalization_preorder_strings ts)›
                      and h5: ‹concat x = concat (map preorder_string us)›
        by auto
      have ‹preorder_string u ∈ linear_generalization_preorder_strings t› using Cons h3 by auto
      then have ‹preorder_string u @ concat (map preorder_string us)
                ∈ concat ` set_Cons (linear_generalization_preorder_strings t) (listset (map linear_generalization_preorder_strings ts))›
        unfolding set_Cons_def using h4 h5 image_iff by fastforce
      then show ?case using h3 by force
    qed
    then show ?thesis
      by (simp add: h1 h2 f2)
  qed
qed

lemma linear_generalization_preorder_strings_congruence: ‹concat (map preorder_string l1) ∈ concat ` listset (map linear_generalization_preorder_strings l2) ⟹ ∀i < length l2. preorder_string (l1 ! i) ∈ linear_generalization_preorder_strings (l2 ! i)›
proof (induction l2 arbitrary: l1)
  case Nil
  then show ?case by auto
next
  case (Cons t ts)
  then show ?case
  proof (cases l1)
    case Nil
    then show ?thesis using Cons.prems linear_generalization_preorder_strings_exists_term
      by (smt (verit, del_insts) concat.simps(1) concat_eq_Nil_conv imageE length_greater_0_conv length_map list.distinct(1) listset mem_Collect_eq non_empty_preorder_string nth_map nth_mem)
  next
    case (Cons u us)
    then have ‹preorder_string u @ concat (map preorder_string us) ∈ concat ` listset (map linear_generalization_preorder_strings (t # ts))› using Cons.prems by auto
    then obtain x xs where h1: ‹concat (x # xs) = preorder_string u @ concat (map preorder_string us)›
                       and h2: ‹x ∈ linear_generalization_preorder_strings t›
                       and h3: ‹xs ∈ listset (map linear_generalization_preorder_strings ts)›
      by (smt (verit, del_insts) set_Cons_def imageE list.simps(9) listset.simps(2) mem_Collect_eq)
    then have ‹x = preorder_string u› using linear_generalization_preorder_strings_exists_term
      by (smt (verit, ccfv_SIG) append_eq_append_conv2 concat.simps(2) preorder_string_prefix)
    then show ?thesis
      by (smt (verit) h1 h2 h3 Cons.IH One_nat_def Suc_pred append_eq_append_conv concat.simps(2) image_eqI length_Cons less_Suc_eq_0_disj local.Cons not_less_eq nth_Cons')
  qed
qed

lemma linear_generalization_preorder_strings_sound:
 ‹preorder_string t1 ∈ linear_generalization_preorder_strings t2 ⟹ linear_instance t2 t1›
proof (induction t2 arbitrary: t1)
  case (Var x)
  then have ‹preorder_string t1 = [Star]› by auto
  then obtain y where ‹t1 = Var y›
    by (metis list.sel(1) preorder_string.elims symbol.distinct(1))
  then show ?case using li_var by auto
next
  case (Fun f f_args)
  then consider ‹preorder_string t1 = [Star]›
    | ‹preorder_string t1 ∈ (Cons (F f (length f_args))) ` concat ` listset (map linear_generalization_preorder_strings f_args)›
    by fastforce
  then show ?case
  proof cases
    case 1
    then obtain y where ‹t1 = Var y›
      by (metis list.sel(1) preorder_string.elims symbol.distinct(1))
    then show ?thesis using li_var by auto
  next
    case 2
    then have h1: ‹preorder_string t1 = F f (length f_args) # concat (map preorder_string (args t1))
                 ∧ concat (map preorder_string (args t1)) ∈ concat ` listset (map linear_generalization_preorder_strings f_args)›
      by (simp add: image_iff preorder_string_alt_def)
    then have ‹⋀i. i < length f_args ⟹ preorder_string (args t1 ! i) ∈ linear_generalization_preorder_strings (f_args ! i)›
      using linear_generalization_preorder_strings_congruence by blast
    then have ‹⋀i. i < length f_args ⟹ linear_instance (f_args ! i) (args t1 ! i)›
      using Fun.IH by auto
    then show ?thesis
      using li_func [of f_args ‹args t1› f] h1 preorder_string.elims
      by (smt (verit, ccfv_threshold) linear_instance.simps list.inject symbol.inject term.sel(4))
  qed
qed

inductive preorder_string_upto :: ‹('f, 'v) term ⇒ epos ⇒ 'f symbol list ⇒ bool› where
  ‹preorder_string_upto t (Some []) []›
| ‹preorder_string_upto t (Some p) l ⟹ preorder_string_upto t (next_position t p) (l @ [root_symbol (t |_ p)])›

lemma preorder_string_upto_eposs:
  assumes ‹preorder_string_upto t ep l›
    shows ‹ep ∈ eposs t›
  using assms
proof (induction)
  case (1 t)
  then show ?case by auto
next
  case (2 t p l)
  then show ?case
    using next_position_in_eposs by fastforce
qed

lemma preorder_string_upto_poss: ‹preorder_string_upto t (Some p) l ⟹ p ∈ poss t›
  using preorder_string_upto_eposs by fastforce

lemma poss_exists_preorder_string_upto: ‹p ∈ poss t ⟹ ∃s. preorder_string_upto t (Some p) s›
proof -
  assume h: ‹p ∈ poss t›
  show ‹∃s. preorder_string_upto t (Some p) s›
  proof (induction p rule: poss_induct)
    case empty
    then show ?case
      using preorder_string_upto.intros(1) by auto
  next
    case (next_pos p1 p2)
    then show ?case using preorder_string_upto.intros(2) by force
  next
    case in_poss
    show ‹p ∈ poss t› using h by auto
  qed
qed

lemma eposs_exists_preorder_string_upto: ‹ep ∈ eposs t ⟹ ∃s. preorder_string_upto t ep s›
proof -
  assume h: ‹ep ∈ eposs t›
  then consider (a) ‹ep = None›
              | (b) ‹∃p. p ∈ poss t ∧ ep = Some p› by auto
  then show ‹∃s. preorder_string_upto t ep s›
  proof (cases)
    case a
    obtain p where ‹p ∈ poss t ∧ next_position t p = None›
      by (metis append_butlast_last_id bot_nat_0.extremum_strict empty_pos_in_poss in_set_conv_nth last_in_set list.size(3) preorder_positions_last
          preorder_positions_poss)
  then show ?thesis
    by (metis a poss_exists_preorder_string_upto preorder_string_upto.intros(2))
  next
    case b
    then show ?thesis
      using poss_exists_preorder_string_upto by auto
  qed
qed

lemma preorder_string_upto_func:
  assumes ‹preorder_string_upto t ep s1›
      and ‹preorder_string_upto t ep s2›
    shows ‹s1 = s2›
  using assms
proof (induction s1 arbitrary: s2 ep rule: rev_induct)
  case Nil
  then have ‹ep = Some []›
    using preorder_string_upto.cases by auto
  then show ?case
    by (metis Nil.prems(2) next_position_non_empty preorder_string_upto.cases)
next
  case (snoc i ps)
  then obtain p where h0: ‹preorder_string_upto t (Some p) ps›
                  and h1: ‹next_position t p = ep›
                  and h2: ‹i = root_symbol (t |_ p)›
    using preorder_string_upto.cases by blast
  then obtain j ps2 where h3: ‹s2 = ps2 @ [j]›
    by (metis next_position_non_empty preorder_string_upto.cases snoc.prems(2))
  then obtain p2 where h4: ‹preorder_string_upto t (Some p2) ps2›
                   and h5: ‹next_position t p2 = ep›
                   and h6: ‹j = root_symbol (t |_ p2)›
    using preorder_string_upto.cases snoc.prems(2) by blast
  then have ‹p = p2› using previous_position_injective h0 h1 h5 preorder_string_upto_poss by blast
  then show ?case
    using h0 h2 h3 h4 h6 snoc.IH by blast
qed

lemma preorder_string_upto_Some:
  assumes ‹preorder_string_upto t ep s›
      and ‹ep = Some p›
    shows ‹length s < length (preorder_positions t) ∧ preorder_positions t ! length s = p ∧ (∀j < length s. s ! j = preorder_string t ! j)›
  using assms
proof (induction arbitrary: p)
  case (1 t)
  then show ?case
    by (metis bot_nat_0.extremum_strict hd_preorder_positions length_Cons list.size(3) nth_Cons_0 option.sel zero_less_Suc)
next
  case (2 t p0 s)
  then have h0: ‹length s < length (preorder_positions t)› by blast
  from 2 have h1: ‹preorder_positions t ! length s = p0› by blast
  from 2 have h2: ‹∀j < length s. s ! j = preorder_string t ! j› by blast
  obtain l1 l2 where h3: ‹preorder_positions t = l1 @ p0 # l2›
                      and h4: ‹length l1 = length s›
    by (metis h0 h1 diff_zero length_map length_upt list_update_id take_upt_idx upd_conv_take_nth_drop)
  then have h5: ‹l2 ≠ []›
    using 2 preorder_positions_last by fastforce
  then obtain l2' where ‹preorder_positions t = l1 @ p0 # p # l2'›
    by (smt (verit, ccfv_SIG) 2 h3 option.inject preorder_positions_ordered_by_next remove_prefix.elims)
  then have ‹preorder_positions t ! Suc (length s) = p› by (simp add: h4 nth_via_drop)
  moreover have ‹Suc (length s) < length (preorder_positions t)›
    by (simp add: h3 h4 h5)
  moreover have ‹⋀j. j < Suc (length s) ⟹ (s @ [root_symbol (t |_ p0)]) ! j = preorder_string t ! j›
    by (metis h0 h2 h3 h4 nat_neq_iff not_less_eq nth_append_left nth_append_length nth_map preorder_string_preorder_positions)
  ultimately show ?case by auto
qed

lemma preorder_string_upto_None:
  assumes ‹preorder_string_upto t None s›
    shows ‹s = preorder_string t›
proof -
  from assms obtain p s1 where h0: ‹next_position t p = None›
                           and h1: ‹preorder_string_upto t (Some p) s1›
                           and h2: ‹s = s1 @ [root_symbol (t |_ p)]›
    by (metis option.distinct(1) preorder_string_upto.cases)
  then have ‹preorder_positions t ! length s1 = p ∧ (∀j < length s1. s1 ! j = preorder_string t ! j)›
    by (simp add: preorder_string_preorder_positions preorder_string_upto_Some)
  then have ‹Suc (length s1) = length (preorder_positions t)› using preorder_positions_last2 preorder_positions_distinct_nth [of _ t]
    by (metis lessI preorder_string_upto_Some diff_Suc_1 h0 h1 hd_preorder_positions last_conv_nth length_Cons list.distinct(1) preorder_string_upto_poss)
  then show ?thesis
    by (smt (verit, best) append_butlast_last_id append_eq_conv_conj bot_nat_0.extremum_strict diff_Suc_1 h1 h2 last_conv_nth le_add_same_cancel2 length_butlast length_map linorder_not_le
        map_nth_eq_conv non_empty_preorder_string nth_take_prefix plus_1_eq_Suc preorder_string_preorder_positions preorder_string_upto_Some)
qed

lemma preorder_string_upto_None2: ‹preorder_string_upto t None (preorder_string t)›
  using eposs_exists_preorder_string_upto preorder_string_upto_None by auto

lemma preorder_string_upto_next_symbol:
  assumes ‹preorder_string t = s1 @ s2›
      and ‹preorder_string_upto t (Some p) s1›
    shows ‹s2 = root_symbol (t |_ p) # tl s2›
proof -
  obtain s1' s2' where ‹preorder_positions t = s1' @ s2'›
                   and ‹s1 = map (λp. root_symbol (t |_ p)) s1'›
                   and h: ‹s2 = map (λp. root_symbol (t |_ p)) s2'›
    by (metis (no_types, lifting) ext append_eq_map_conv assms(1) preorder_string_preorder_positions)
  then have ‹s2' = p # tl s2'›
    by (metis (no_types, lifting) append_Cons_nth_middle append_Nil2 assms(2) length_map list.exhaust_sel nat_less_le
        preorder_string_upto_Some)
  then show ?thesis using h
    by (metis (no_types, lifting) list.simps(9) map_tl)
qed

lemma preorder_string_subterm:
  ‹p ∈ poss t ⟹ (∃s1 s2. preorder_string t = s1 @ preorder_string (t |_ p) @ s2)›
proof (induction p arbitrary: t)
  case Nil
  then show ?case
    by (metis subt_at.simps(1) self_append_conv2 self_append_conv)
next
  case (Cons i ps)
  then obtain f f_args where h0: ‹t = Fun f f_args ∧ i < length f_args›
    by (meson args_poss)
  then have h1: ‹ps ∈ poss (f_args ! i)› using Cons by auto
  then obtain s1 s2 where h2: ‹preorder_string (f_args ! i) = s1 @ preorder_string (f_args ! i |_ ps) @ s2› using Cons.IH by blast
  from h0 obtain f_args1 f_args2 where h3: ‹f_args = f_args1 @ (f_args ! i) # f_args2›
    using append_take_drop_id id_take_nth_drop by auto
  then have ‹concat (map preorder_string f_args) = concat (map preorder_string f_args1) @ preorder_string (f_args ! i) @ concat (map preorder_string f_args2)›
    by (metis h3 concat_append map_append concat.simps(2) list.simps(9))
  then have ‹preorder_string t = (root_symbol t # concat (map preorder_string f_args1) @ s1) @ preorder_string (f_args ! i |_ ps) @ (s2 @ concat (map preorder_string f_args2))›
    using h0 h2 by simp
  then show ?case
    by (metis h0 subt_at.simps(2))
qed

lemma preorder_string_subterm_length:
  ‹p ∈ poss t ⟹ length (preorder_string (t |_ p)) ≤ length (preorder_string t)›
  using preorder_string_subterm by force

lemma preorder_string_strict_subterm_length:
  ‹p ∈ poss t ⟹ p ≠ [] ⟹ length (preorder_string (t |_ p)) < length (preorder_string t)›
proof (induction p arbitrary: t)
  case Nil
  then show ?case by auto
next
  case (Cons i ps)
  then obtain f f_args where h0: ‹t = Fun f f_args ∧ i < length f_args›
    by (meson args_poss)
  then have ‹length (preorder_string (f_args ! i)) ≤ sum_list (map (length ∘ preorder_string) f_args)›
    by (metis comp_apply elem_le_sum_list length_map map_nth_eq_conv)
  also have ‹... < Suc (length (concat (map preorder_string f_args)))›
    using length_concat [of ‹map preorder_string f_args›] by auto
  finally show ?case
    using Cons.prems(1) h0 preorder_string_subterm_length by fastforce
qed

lemma preorder_string_upto_after_position:
  ‹preorder_string_upto t (Some p) l ⟹ preorder_string_upto t (after_position t p) (l @ preorder_string (t |_ p))›
proof (induction ‹length (preorder_string (t |_ p))› arbitrary: l p rule: less_induct)
  case less
  show ?case
  proof (cases ‹t |_ p›)
    case (Var x)
    then show ?thesis
      using less.prems preorder_string_upto.simps by fastforce
  next
    case (Fun f f_args)
    then have h0: ‹p ∈ poss t›
        by (metis less.prems preorder_string_upto_poss)
    have h1: ‹⋀i l1. i < length f_args ⟹ preorder_string_upto t (Some (p @ [i])) l1 ⟹ preorder_string_upto t (after_position t (p @ [i])) (l1 @ preorder_string (t |_ (p @ [i])))›
      by (metis list.distinct(1) preorder_string_upto_poss subterm_poss_conv preorder_string_strict_subterm_length preorder_string_upto_poss subterm_poss_conv less(1))
    have h2: ‹⋀i. i < length f_args ⟹ preorder_string_upto t (Some (p @ [i])) (l @ root_symbol (t |_ p) # concat (map preorder_string (take i f_args)))›
    proof -
      fix i
      show ‹i < length f_args ⟹ preorder_string_upto t (Some (p @ [i])) (l @ root_symbol (t |_ p) # concat (map preorder_string (take i f_args)))›
      proof (induction i)
        case 0
        then have ‹next_position t p = Some (p @ [0])› using Fun by auto
        then show ?case using less.prems preorder_string_upto.simps by fastforce
      next
        case (Suc i)
        then have ‹concat (map preorder_string (take i f_args @ [t |_ (p @ [i])])) = concat (map preorder_string (take (Suc i) f_args))›
          by (simp add: Fun h0 Suc_lessD take_Suc_conv_app_nth)
        then have ‹concat (map preorder_string (take i f_args)) @ preorder_string (t |_ (p @ [i])) = concat (map preorder_string (take (Suc i) f_args))›
          by auto
        then have ‹preorder_string_upto t (after_position t (p @ [i])) ((l @ [root_symbol (t |_ p)] @ concat (map preorder_string (take (Suc i) f_args))))›
          using h1 [of i] Suc by force
        then show ?case
          using after_position.simps(2) [of t ‹hd (p @ [i])› ‹tl (p @ [i])›] Fun Suc by auto
      qed
    qed
    show ?thesis
    proof (cases f_args rule: rev_exhaust)
      case Nil
      then have ‹p ∈ poss t›
        by (metis less.prems preorder_string_upto_poss)
      then show ?thesis
        using less.prems preorder_string_upto.simps local.Nil Fun less.hyps by fastforce
    next
      case (snoc f_args' a)
      then have ‹preorder_string_upto t (Some (p @ [length f_args'])) (l @ root_symbol (t |_ p) # concat (map preorder_string f_args'))›
        using h2 by force
      then have ‹preorder_string_upto t (after_position t (p @ [length f_args'])) (l @ root_symbol (t |_ p) # concat (map preorder_string f_args') @ preorder_string (t |_ (p @ [length f_args'])))›
        using h1 snoc by fastforce
      moreover have ‹after_position t (p @ [length f_args']) = after_position t p›
        using after_position.simps(2) [of t ‹hd (p @ [length f_args'])› ‹tl (p @ [length f_args'])›] Fun snoc by auto
      moreover have ‹t |_ (p @ [length f_args']) = a› using Fun snoc less.prems h0 by fastforce
      ultimately show ?thesis
        using Fun snoc by simp
    qed
  qed
qed

lemma preorder_string_upto_prefix:
  assumes ‹preorder_string_upto t ep s1›
  shows ‹∃s2. preorder_string t = s1 @ s2›
  using assms
proof (induction)
  case (1 t)
  then show ?case by auto
next
  case (2 t p s1)
  then obtain s2 where ‹preorder_string t = s1 @ root_symbol (t |_ p) # s2›
    using preorder_string_upto_next_symbol by metis
  then show ?case by auto
qed

lemma preorder_string_upto_next_term:
  assumes ‹preorder_string_upto t ep s1›
      and ‹preorder_string t = s1 @ s2›
      and ‹ep = Some p›
    shows ‹∃s3. s2 = preorder_string (t |_ p) @ s3›
  using assms
proof (induction arbitrary: p s2)
  case (1 t)
  then show ?case by auto
next
  case (2 t1 p1 s1')
  then obtain s3 where h0: ‹root_symbol (t1 |_ p1) # s2 = preorder_string (t1 |_ p1) @ s3› by auto
  then show ?case
  proof (cases ‹arity (t1 |_ p1)›)
    case 0
    then have ‹s2 = s3› using h0
      by (cases ‹t1 |_ p1›; auto)
    have h1: ‹after_position t1 p1 = Some p› using 0 2 by auto
    then have ‹preorder_string_upto t1 (Some p) (s1' @ preorder_string (t1 |_ p1))›
      using preorder_string_upto_after_position [of t1 p1 s1'] 2 by auto
    then have ‹preorder_string_upto t1 (after_position t1 p) (s1' @ preorder_string (t1 |_ p1) @ preorder_string (t1 |_ p))›
      using preorder_string_upto_after_position [of t1 p ‹s1' @ preorder_string (t1 |_ p1)›] by auto
    then obtain s3' where ‹preorder_string t1 = s1' @ preorder_string (t1 |_ p1) @ preorder_string (t1 |_ p) @ s3'›
      using preorder_string_upto_prefix by fastforce
    then show ?thesis
      by (metis 2(1,3,4) ‹preorder_string_upto t1 (Some p) (s1' @ preorder_string (t1 |_ p1))› append.assoc preorder_string_upto.intros(2) preorder_string_upto_func same_append_eq)
  next
    case (Suc m)
    then obtain f a f_args where h1: ‹t1 |_ p1 = Fun f (a # f_args)›
      by (metis arity.simps(1,2) length_Suc_conv nat.distinct(1) preorder_string.elims)
    then have h2: ‹s2 = preorder_string a @ concat (map preorder_string f_args) @ s3› using h0 by simp
    have ‹p = p1 @ [0]›
      using 2 by (simp add: Suc)
    then have ‹t1 |_ p = a› using 2 preorder_string_upto_poss
      using h1 by fastforce
    then show ?thesis using h2 by auto
  qed
qed

lemma concat_map_preorder_string_subterm_decompose:
  assumes ‹concat (map preorder_string (f_args :: ('a, 'b) term list)) = s1 @ preorder_string (t :: ('a, 'b) term) @ s2›
  shows ‹∃f_args1 t2 f_args2 s1' s2' s1'' s2''. f_args = f_args1 @ t2 # f_args2
                                         ∧ preorder_string t2 = s1' @ preorder_string t @ s2'
                                         ∧ s1 = s1'' @ s1'
                                         ∧ s2 = s2' @ s2''
                                         ∧ concat (map preorder_string f_args1) = s1''
                                         ∧ concat (map preorder_string f_args2) = s2''›
  using assms
proof (induction f_args arbitrary: s1)
  case Nil
  then show ?case by auto
next
  case (Cons a f_args')
  show ?case
  proof (cases ‹length (s1 @ preorder_string t) ≤ length (preorder_string a)›)
    case True
    then have ‹preorder_string a = s1 @ preorder_string t @ take (length (preorder_string a) - length (s1 @ preorder_string t)) s2›
      by (metis Cons.prems append.assoc append_eq_conv_conj concat.simps(2) list.simps(9) take_all_iff take_append)
    moreover have ‹s2 = take (length (preorder_string a) - length (s1 @ preorder_string t)) s2 @ drop (length (preorder_string a) - length (s1 @ preorder_string t)) s2› by auto
    moreover have ‹concat (map preorder_string []) = []› by auto
    moreover have ‹concat (map preorder_string f_args') = drop (length (preorder_string a) - length (s1 @ preorder_string t)) s2›
      using True Cons.prems
      by (simp add: append_eq_conv_conj)
    ultimately show ?thesis by blast
  next
    case False
    show ?thesis
    proof (cases ‹length s1 ≥ length (preorder_string a)›)
      case True
      then have ‹concat (map preorder_string f_args') = drop (length (preorder_string a)) s1 @ preorder_string t @ s2›
        by (metis True Cons.prems list.simps(9) concat.simps(2) append_eq_append_conv_if)
      then obtain f_args1 t2 f_args2 s1' s2' s1'' s2'' where h: ‹f_args' = f_args1 @ t2 # f_args2
                                                               ∧ preorder_string t2 = s1' @ preorder_string t @ s2'
                                                               ∧ drop (length (preorder_string a)) s1 = s1'' @ s1'
                                                               ∧ s2 = s2' @ s2''
                                                               ∧ concat (map preorder_string f_args1) = s1''
                                                               ∧ concat (map preorder_string f_args2) = s2''›
        using Cons.IH [of ‹drop (length (preorder_string a)) s1›] by auto
      then have ‹s1 = take (length (preorder_string a)) s1 @ s1'' @ s1'›
        by (metis append_take_drop_id)
      moreover have ‹concat (map preorder_string (a # f_args1)) = take (length (preorder_string a)) s1 @ s1''›
        using Cons.prems ‹concat (map preorder_string f_args') = drop (length (preorder_string a)) s1 @ preorder_string t @ s2› h by auto
      ultimately show ?thesis by (metis h append.assoc append_Cons)
    next
      case False
      then have ‹preorder_string a = take (length (preorder_string a)) (s1 @ preorder_string t)›
        using Cons.prems ‹¬ length (s1 @ preorder_string t) ≤ length (preorder_string a)›
        by (metis (no_types, lifting) append.assoc append_eq_append_conv_if concat.simps(2) list.simps(9))
      then have ‹preorder_string a = s1 @ take (length (preorder_string a) - length s1) (preorder_string t)›
        using False by auto
      then have False
        using False ‹¬ length (s1 @ preorder_string t) ≤ length (preorder_string a)› preorder_string_suffix [of a s1 _ t] by force
      then show ?thesis by auto
    qed
  qed
qed
  
lemma preorder_substring_subterm:
  assumes ‹preorder_string (t :: ('a, 'b) term) = s1 @ preorder_string (t2 :: ('a, 'b) term) @ s2›
  shows ‹∃p. p ∈ poss t ∧ preorder_string (t |_ p) = preorder_string t2›
  using assms
proof (induction t arbitrary: s1 s2)
  case (Var x)
  then have ‹s1 = [] ∧ s2 = []›
    by (simp add: Cons_eq_append_conv)
  then show ?case
    using Var append.left_neutral append.right_neutral subt_at.simps(1) by force
next
  case (Fun f f_args)
  show ?case
  proof (cases s1)
    case Nil
    then have ‹s2 = []›
      by (metis Fun.prems append.left_neutral preorder_string_prefix)
    then show ?thesis
      using Fun append.left_neutral append.right_neutral local.Nil subt_at.simps(1) by force
  next
    case (Cons a s1')
    then have ‹s1' @ preorder_string t2 @ s2 = concat (map preorder_string f_args)›
      using Fun by auto
    then obtain f_args1 t0 f_args2 s1'' s2' where h0: ‹f_args = f_args1 @ t0 # f_args2›
                                              and h1: ‹preorder_string t0 = s1'' @ preorder_string t2 @ s2'›
      using concat_map_preorder_string_subterm_decompose [of f_args s1' t2 s2] by auto
    then obtain i where h2: ‹i < length f_args›
                    and h3: ‹f_args ! i = t0›
      by (metis append.right_neutral append_Cons_nth_middle append_eq_conv_conj length_append linorder_neqE_nat list.distinct(1) not_add_less1)
    obtain p where ‹p ∈ poss t0 ∧ preorder_string (t0 |_ p) = preorder_string t2›
      using h0 h1 Fun.IH [of t0 s1'' s2'] by auto
    then show ?thesis by (metis h2 h3 poss_Cons_poss subt_at.simps(2) term.sel(4))
  qed
qed

lemma subterm_preorder_substring:
  assumes ‹p ∈ poss t›
  shows ‹∃s1 s2. preorder_string t = s1 @ preorder_string (t |_ p) @ s2›
  using assms
proof (induction t arbitrary: p)
  case (Var x)
  then show ?case by auto
next
  case (Fun f f_args)
  show ?case
  proof (cases p)
    case Nil
    then show ?thesis
      by (metis append.left_neutral append.right_neutral subt_at.simps(1))
  next
    case (Cons i ps)
    then have h: ‹i < length f_args ∧ ps ∈ poss (f_args ! i)›
      using Fun.prems by auto
    then obtain s1 s2 where ‹preorder_string (f_args ! i) = s1 @ preorder_string (f_args ! i |_ ps) @ s2› using Fun.IH by force
    moreover have ‹concat (map preorder_string f_args) = concat (map preorder_string (take i f_args)) @ preorder_string (f_args ! i) @ concat (map preorder_string (drop (Suc i) f_args))› 
      by (metis Cons_nth_drop_Suc h append_take_drop_id concat.simps(2) concat_append list.simps(9) map_append)
    ultimately show ?thesis
      by (metis append.assoc append_Cons local.Cons preorder_string.simps(2) subt_at.simps(2))
  qed
qed

lemma listset_map:
  assumes ‹length xs = length ys›
      and ‹⋀i. i < length ys ⟹ f (xs ! i) ∈ g (ys ! i)›
    shows ‹map f xs ∈ listset (map g ys)›
  using assms
proof (induction ys arbitrary: xs)
  case Nil
  then show ?case by auto 
next
  case (Cons y ys')
  then obtain x xs' where ‹xs = x # xs'›
    by (metis length_Suc_conv)
  then have ‹f x ∈ g y›
    using Cons by force
  moreover have ‹map f xs' ∈ listset (map g ys')›
    using Cons ‹xs = x # xs'› by force
  ultimately have ‹f x # (map f xs') ∈ set_Cons (g y) (listset (map g ys'))›
    by (simp add: set_Cons_def)
  then show ?case
    using ‹xs = x # xs'› by auto
qed

lemma linear_generalization_star:
  assumes ‹preorder_string (t :: ('a, 'b) term) = s2 @ preorder_string (t2 :: ('a, 'b) term) @ s3›
      and ‹s1 @ preorder_string t2 @ s3 ∈ linear_generalization_preorder_strings t›
    shows ‹s1 @ [Star] @ s3 ∈ linear_generalization_preorder_strings t›
  using assms
proof (induction ‹length (preorder_string t)› arbitrary: t t2 s1 s2 s3 rule: less_induct)
  case less
  show ?case
  proof (cases t)
    case (Var x)
    then have ‹s2 = [] ∧ s3 = []›
      using less(2) by (simp add: Cons_eq_append_conv)
    then show ?thesis
      using Var less(2,3) by auto
    next
    case (Fun f f_args)
    then consider ‹s1 @ preorder_string t2 @ s3 = [Star]›
                | ‹s1 @ preorder_string t2 @ s3 ∈ (#) (F f (length f_args)) ` concat ` listset (map linear_generalization_preorder_strings f_args)›
    using less(3) by fastforce
    then show ?thesis
    proof cases
      case 1
      then have ‹s1 = [] ∧ s3 = []›
        by (simp add: append_eq_Cons_conv)
      then show ?thesis
        using Fun by auto
    next
      case 2
      then show ?thesis
      proof (cases s1)
        case Nil
        then have ‹s3 = []›
          by (metis less(3) append_Nil linear_generalization_preorder_strings_exists_term preorder_string_prefix)
        then show ?thesis
          using Nil Fun by auto
      next
        case (Cons s ss)
        then have h0: ‹s = F f (length f_args)›
                  and ‹ss @ preorder_string t2 @ s3 ∈ concat ` listset (map linear_generalization_preorder_strings f_args)›
          using 2 by auto
        then obtain ts :: ‹('a, 'b) term list› where ‹ss @ preorder_string t2 @ s3 = concat (map preorder_string ts)›
                                                 and ‹length ts = length f_args›
                                                 and ‹⋀i. i < length f_args ⟹ preorder_string (ts ! i) ∈ linear_generalization_preorder_strings (f_args ! i)›
          using concat_linear_generalization_preorder_strings_decompose [of ‹ss @ preorder_string t2 @ s3› f_args] by auto
        then obtain ts1 t3 ts2 s1' s1'' s2' s2'' where ‹ts = ts1 @ t3 # ts2›
                                                   and ‹preorder_string t3 = s1' @ preorder_string t2 @ s2'›
                                                   and ‹concat (map preorder_string ts1) = s1''›
                                                   and ‹concat (map preorder_string ts2) = s2''›
                                                   and ‹ss = s1'' @ s1'›
                                                   and ‹s3 = s2' @ s2''›
          using concat_map_preorder_string_subterm_decompose [of ts ss t2 s3] by metis
        then have ‹preorder_string t3 ∈ linear_generalization_preorder_strings (f_args ! length ts1)›
          using ‹⋀i. i < length f_args ⟹ preorder_string (ts ! i) ∈ linear_generalization_preorder_strings (f_args ! i)› [of ‹length ts1›]
                ‹length ts = length f_args› by force
        have ‹length (preorder_string t3) < length (preorder_string t)›
        proof -
          have ‹length (preorder_string t3) ≤ length (preorder_string (f_args ! length ts1))›
            using ‹preorder_string t3 ∈ linear_generalization_preorder_strings (f_args ! length ts1)›
            by (simp add: linear_generalization_preorder_strings_sound linear_instance_length)
          also have ‹... ≤ length (concat (map preorder_string f_args))›
            using ‹ts = ts1 @ t3 # ts2› ‹length ts = length f_args› length_concat [of ‹map preorder_string f_args›]
                  elem_le_sum_list [of ‹length ts1› ‹map (length ∘ preorder_string) f_args›] by auto
          ultimately show ?thesis by (simp add: Fun)
        qed
        then have ‹s1' @ [Star] @ s2' ∈ linear_generalization_preorder_strings t3›
          using less(1) [of t3 s1' t2 s2' s1'] linear_generalization_preorder_strings_complete linear_instance_refl
          by (metis ‹preorder_string t3 = s1' @ preorder_string t2 @ s2'›)
        then obtain t4 :: ‹('a,'b) term› where ‹preorder_string t4 = s1' @ [Star] @ s2'›
                                           and ‹preorder_string t4 ∈ linear_generalization_preorder_strings t3›
          using linear_generalization_preorder_strings_exists_term by auto
        then have ‹preorder_string t4 ∈ linear_generalization_preorder_strings (f_args ! length ts1)›
          using ‹preorder_string t3 ∈ linear_generalization_preorder_strings (f_args ! length ts1)›
                linear_instance_trans linear_generalization_preorder_strings_complete linear_generalization_preorder_strings_sound by blast
        have ‹concat (map preorder_string ts1) @ s1' @ preorder_string t2 @ s2' @ concat (map preorder_string ts2) = s1'' @ s1' @ preorder_string t2 @ s2' @ s2''›
          using ‹ss @ preorder_string t2 @ s3 = concat (map preorder_string ts)› ‹ss = s1'' @ s1'› ‹s3 = s2' @ s2''› ‹ts = ts1 @ t3 # ts2› ‹preorder_string t3 = s1' @ preorder_string t2 @ s2'› by auto
        then have ‹concat (map preorder_string (ts1 @ t4 # ts2)) = ss @ [Star] @ s3›
          using ‹concat (map preorder_string ts2) = s2''› ‹concat (map preorder_string ts1) = s1''› ‹s3 = s2' @ s2''› ‹ss = s1'' @ s1'› ‹preorder_string t4 = s1' @ [symbol.Star] @ s2'› by fastforce
        have ‹⋀i. i < length f_args ⟹ preorder_string ((ts1 @ t4 # ts2) ! i) ∈ linear_generalization_preorder_strings (f_args ! i)›
          using ‹ts = ts1 @ t3 # ts2›
                ‹preorder_string t4 ∈ linear_generalization_preorder_strings (f_args ! length ts1)›
                ‹⋀i. i < length f_args ⟹ preorder_string (ts ! i) ∈ linear_generalization_preorder_strings (f_args ! i)›
          by (metis append_Cons_nth_middle append_Cons_nth_not_middle)
        then have ‹map preorder_string (ts1 @ t4 # ts2) ∈ listset (map linear_generalization_preorder_strings f_args)›
          using ‹ts = ts1 @ t3 # ts2› ‹length ts = length f_args› listset_map
          by (metis length_Cons length_append)
        then have ‹ss @ [Star] @ s3 ∈ concat ` listset (map linear_generalization_preorder_strings f_args)›
          using ‹concat (map preorder_string (ts1 @ t4 # ts2)) = ss @ [Star] @ s3› by force
        then show ?thesis
          using h0 Fun local.Cons by force
      qed
    qed
  qed
qed

subsection ‹Invariants›

definition sound_storage :: ‹('f, 'v) dt_trie ⇒ bool› where
  ‹sound_storage tr = (∀t p s. subdt_trie_at_path tr p (DTLeaf (insert t s)) ⟶ p = preorder_string t)›

lemma sound_storage_empty_trie [simp]: ‹sound_storage empty_dt_trie›
  using sound_storage_def subdt_trie_at_path.cases by fastforce

inductive sound_storage_from_position :: ‹('f, 'v) dt_trie ⇒ 'f symbol list ⇒ bool› where
  ssfp_leaf: ‹(∀t ∈ ts. preorder_string t = p) ⟹ sound_storage_from_position (DTLeaf ts) p›
| ssfp_node: ‹(∀s ∈ fmdom' m. sound_storage_from_position (m $$! s) (p @ [s])) ⟹ sound_storage_from_position (DTNode m) p›

lemma sound_storage_from_position_alt_def:
  ‹sound_storage_from_position tr s1 = (∀t s2 ts. subdt_trie_at_path tr s2 (DTLeaf (insert t ts)) ⟶ preorder_string t = s1 @ s2)›
proof
  show ‹sound_storage_from_position tr s1 ⟹ ∀t s2 ts. subdt_trie_at_path tr s2 (DTLeaf (insert t ts)) ⟶ preorder_string t = s1 @ s2›
  proof (induction tr arbitrary: s1)
    case (DTLeaf ts)
    then show ?case
      by (metis append_self_conv dt_trie.distinct(1) dt_trie.sel(1) insertI1 sound_storage_from_position.simps subdt_trie_at_path.cases)
  next
    case (DTNode m)
    then show ?case
      by (smt (verit, del_insts) append.assoc append_Cons append_self_conv2 dt_trie.distinct(1) dt_trie.sel(2) fmdom'I fmran'I option.sel sound_storage_from_position.simps subdt_trie_at_path.simps)
  qed
next
  show ‹∀t s2 ts. subdt_trie_at_path tr s2 (DTLeaf (insert t ts)) ⟶ preorder_string t = s1 @ s2 ⟹ sound_storage_from_position tr s1›
  proof (induction tr arbitrary: s1)
    case (DTLeaf ts)
    then show ?case
      by (metis append.right_neutral insert_absorb ssfp_leaf subdt_trie_at_path_empty)
  next
    case (DTNode m)
    then show ?case
      by (smt (verit, best) append.assoc append.left_neutral append_Cons fmlookup_dom'_iff fmran'I option.sel sound_storage_from_position.intros(2) subdt_trie_at_path_step)
  qed
qed

lemma sound_storage_from_empty_position:
  ‹sound_storage tr = sound_storage_from_position tr []›
  using sound_storage_def sound_storage_from_position_alt_def by fastforce

inductive minimal_storage :: ‹('f, 'v) dt_trie ⇒ bool› where
  minimal_storage_leaf: ‹s ≠ {} ⟹ minimal_storage (DTLeaf s)›
| minimal_storage_node: ‹(∀tr ∈ fmran' m. minimal_storage tr ∧ tr ≠ empty_dt_trie) ⟹ minimal_storage (DTNode m)›

lemma minimal_storage_subdt_trie: ‹minimal_storage tr1 ⟹ subdt_trie_at_path tr1 p tr2 ⟹ minimal_storage tr2›
proof (induction tr1 arbitrary: p)
  case (DTLeaf ts)
  then show ?case
    using subdt_trie_at_path.cases by auto
next
  case (DTNode m)
  then show ?case
    by (metis dt_trie.distinct(1) dt_trie.inject(2) fmran'I minimal_storage.cases subdt_trie_at_path.simps)
qed

lemma minimal_storage_no_empty_subtrie: ‹minimal_storage tr1 ⟹ subdt_trie_at_path tr1 p tr2 ⟹ p ≠ [] ⟹ tr2 ≠ empty_dt_trie›
proof (induction tr1 arbitrary: p)
  case (DTLeaf ts)
  then show ?case
    using subdt_trie_at_path.simps by blast
next
  case (DTNode m)
  then show ?case
    by (metis dt_trie.distinct(1) dt_trie.inject(2) fmran'I list.distinct(1) minimal_storage.cases subdt_trie_at_path.simps)
qed

lemma empty_trie_minimal [simp]: ‹minimal_storage empty_dt_trie› 
  by (metis fmdom'I fmdom'_notI fmempty_lookup fmran'E minimal_storage_node)

lemma minimal_storage_members: ‹minimal_storage tr ⟹ tr = empty_dt_trie ∨ (∃t. t ∈ to_set tr)›
proof (induction tr)
  case (DTLeaf ts)
  then show ?case
    using minimal_storage.cases by fastforce
next
  case (DTNode m)
  then show ?case
  proof (cases m)
    case fmempty
    then show ?thesis by auto
  next
    case (fmupd s tr2 m')
    then have h: ‹minimal_storage tr2 ∧ tr2 ∈ fmran' m›
      by (metis DTNode.prems dt_trie.inject(2) dt_trie.simps(4) fmlookup_ran'_iff fmupd_lookup minimal_storage.cases)
    then obtain t where ‹t ∈ to_set tr2› using DTNode
      by (metis dt_trie.distinct(1) dt_trie.inject(2) minimal_storage.cases)
    then show ?thesis using h by force
  qed
qed

subsection ‹Term insertion›

fun insert_aux :: ‹('f, 'v) dt_trie ⇒ ('f symbol) list ⇒ ('f, 'v) term ⇒ ('f, 'v) dt_trie› where
  ‹insert_aux (DTLeaf s) []  t     = DTLeaf (insert t s)›
| ‹insert_aux (DTLeaf s) p   t     = DTLeaf s› (* not reached, but this definition makes preservation proofs easier than 'undefined' *)
| ‹insert_aux (DTNode m) []  t     = DTNode m› (* same *)
| ‹insert_aux (DTNode m) [f] t     = DTNode (update_entry m f (λtr. insert_aux tr [] t) (DTLeaf {t}))›
| ‹insert_aux (DTNode m) (f # p) t = DTNode (update_entry m f (λtr. insert_aux tr p t) empty_dt_trie)›

lemma to_set_path: ‹t ∈ to_set tr ⟹ ∃ts s. subdt_trie_at_path tr s (DTLeaf (insert t ts))›
proof (induction tr)
  case (DTLeaf ts)
  then show ?case
    by (metis insert_absorb subdt_trie_at_path_empty to_set.simps(1))
next
  case (DTNode m) then show ?case
    using fmlookup_ran'_iff subdt_trie_at_path_step by fastforce
qed

lemma to_set_sound_from: ‹sound_storage_from_position tr s1 ⟹
  preorder_string t = s1 @ s2 ⟹ t ∈ to_set tr ⟹ ∃ts. subdt_trie_at_path tr s2 (DTLeaf (insert t ts))›
  using sound_storage_from_position_alt_def to_set_path by fastforce
  
lemma insert_aux_keeps_elements: 
  assumes ‹x ∈ to_set tr› 
  shows ‹x ∈ to_set (insert_aux tr p t)›
  using assms
proof (induction tr p t rule: insert_aux.induct)
  case (1 s t)
  then show ?case
    by simp 
next
  case (2 s v va t)
  then show ?case
    by simp 
next
  case (3 m t)
  then show ?case
    by simp 
next
  case (4 m f t)
  then show ?case by (auto, metis fmlookup_ran'_iff fmupd_lookup option.simps(5))
next
  case (5 m f v va t)
  then show ?case by (auto, metis fmlookup_ran'_iff fmupd_lookup option.simps(5))
qed 

lemma insert_aux_subset:  
  assumes ‹x ≠ t›
      and ‹x ∈ to_set (insert_aux tr p t)› 
    shows ‹x ∈ to_set tr›
  using assms
proof (induction tr p t rule: insert_aux.induct)
  case (1 s t)
  then show ?case by auto
next
  case (2 s v va t)
  then show ?case by auto
next
  case (3 m t)
  then show ?case  by auto
next
  case (4 m f t)
  then show ?case
  proof (cases ‹m $$ f›)
    case None
    then show ?thesis using 4 by (auto, metis fmlookup_ran'_iff fmupd_lookup option.sel singletonD to_set.simps(1))
  next
    case (Some a)
    then show ?thesis using 4 by (auto, metis fmlookup_ran'_iff fmupd_lookup option.sel)
  qed
next
  case (5 m f v va t)
  then show ?case
  proof (cases ‹m $$ f›)
    case None
    then show ?thesis
      using 5
      by (auto simp add: fmlookup_ran'_iff, metis UN_E fmempty.rep_eq fmran'E fmran'I option.inject to_set.simps(2))
  next
    case (Some a)
    then show ?thesis
      using 5
      by (auto simp add: fmlookup_ran'_iff, metis fmlookup_ran'_iff option.sel)
  qed
qed

lemma insert_aux_empty_trie: ‹t ∈ to_set (insert_aux empty_dt_trie (f # p) t)›
proof (induction p arbitrary: f)
  case Nil
  have ‹DTLeaf {t} ∈ fmran' {f $$:= DTLeaf {t}}›
    by (simp add: fmlookup_ran'_iff)
  then show ?case by force
next
  case (Cons f2 p2)
  have ‹insert_aux empty_dt_trie (f2 # p2) t ∈ fmran' {f $$:= insert_aux empty_dt_trie (f2 # p2) t}›
    by (simp add: fmlookup_ran'_iff)
  then show ?case using Cons by force
qed

lemma insert_aux_adds_element:
  assumes ‹preorder_string t = s1 @ s2›
      and ‹sound_storage tr_root›
      and ‹subdt_trie_at_path tr_root s1 tr›
      and ‹minimal_storage tr_root›
    shows ‹t ∈ to_set (insert_aux tr s2 t)›
 using assms
proof (induction tr s2 t arbitrary: s1 rule: insert_aux.induct)
  case (1 s t)
  then show ?case by auto
next
  case (2 s v va t)
  then obtain t2 where ‹t2 ∈ s›
    using minimal_storage_members minimal_storage_subdt_trie to_set.simps(1) by blast
  then have ‹preorder_string t2 = s1›
    by (metis 2(3) assms(2) insert_absorb sound_storage_def)
  then have False using 2(1)
    by (metis neq_Nil_conv preorder_string_prefix)
  then show ?case by auto
next
  case (3 m t)
  then have h0: ‹minimal_storage (DTNode m)›
    using assms(4) minimal_storage_subdt_trie by blast
  moreover have ‹m ≠ {$$}›
    using 3(1,3) assms(4) minimal_storage_no_empty_subtrie by fastforce
  ultimately obtain ts s2 where h1: ‹subdt_trie_at_path (DTNode m) s2 (DTLeaf ts)›
                            and h2: ‹s2 ≠ []›
    by (metis dt_trie.distinct(1) dt_trie.inject(2) list.discI minimal_storage_members subdt_trie_at_path.cases to_set_path)
  then obtain t2 where ‹t2 ∈ ts›
    using h0 minimal_storage_members minimal_storage_subdt_trie to_set.simps(1) by blast
  then have ‹preorder_string t2 = s1 @ s2›
    using 3(3) h1 assms(2) mk_disjoint_insert sound_storage_def subdt_trie_at_path_trans by fastforce
  then show ?case
    by (metis 3(1) append.right_neutral h2 preorder_string_prefix)
next
  case (4 m f t)
  then show ?case
  proof (cases ‹m $$ f›)
    case None
    have ‹t ∈ to_set (DTNode (m(f $$:= DTLeaf {t})))›
      by (meson fmupd_lookup subdt_toset subdt_trie_at_path_empty subdt_trie_at_path_step)
    then show ?thesis using None by auto
  next
    case (Some tr2)
    then have ‹subdt_trie_at_path tr_root (s1 @ [f]) tr2›
      using 4 subdt_trie_at_path_empty subdt_trie_at_path_step subdt_trie_at_path_trans by blast
    then have ‹t ∈ to_set (insert_aux tr2 [] t)›
      using 4 assms(2,4) by auto
    then have ‹t ∈ to_set (DTNode (m(f $$:= insert_aux tr2 [] t)))›
      by (meson fmupd_lookup subdt_toset subdt_trie_at_path_step to_set_path)
    then show ?thesis using Some by auto
  qed
next
  case (5 m f v va t)
  then show ?case
  proof (cases ‹m $$ f›)
    case None
    have ‹t ∈ to_set (insert_aux empty_dt_trie (v # va) t)› using insert_aux_empty_trie by auto
    then have ‹t ∈ to_set (DTNode (m(f $$:= insert_aux empty_dt_trie (v # va) t)))›
      by (meson fmupd_lookup subdt_toset subdt_trie_at_path_step to_set_path)
    then show ?thesis using None by auto
  next
    case (Some tr2)
    have ‹subdt_trie_at_path tr_root (s1 @ [f]) tr2›
      using 5(4) Some subdt_trie_at_path_empty subdt_trie_at_path_step subdt_trie_at_path_trans by blast
    then have ‹t ∈ to_set (insert_aux tr2 (v # va) t)›
      using 5 assms(2,4) by auto
    then have ‹t ∈ to_set (DTNode (m(f $$:= insert_aux tr2 (v # va) t)))›
      by (meson fmupd_lookup subdt_toset subdt_trie_at_path_step to_set_path)
    then show ?thesis using Some by auto
  qed
qed

lemma insert_spec:
  assumes ‹sound_storage tr›
      and ‹minimal_storage tr›
    shows ‹to_set (insert_aux tr (preorder_string t) t) = insert t (to_set tr)›
proof
  show ‹to_set (insert_aux tr (preorder_string t) t) ⊆ insert t (to_set tr)›
    using insert_aux_subset by blast
next
  show ‹insert t (to_set tr) ⊆ to_set (insert_aux tr (preorder_string t) t)›
    using assms(1,2) insert_aux_adds_element insert_aux_keeps_elements subdt_trie_at_path_empty by fastforce
qed

lemma insert_aux_preserves_sound:
  assumes ‹preorder_string t = p1 @ p2›
      and ‹sound_storage_from_position tr p1›
    shows ‹sound_storage_from_position (insert_aux tr p2 t) p1›
  using assms
proof  (induction tr p2 t arbitrary: p1 rule: insert_aux.induct)
  case (1 s t)
  then have ‹∀x ∈ s. preorder_string x = p1›
    using sound_storage_from_position.cases by auto
  then show ?case
    by (simp add: 1 sound_storage_from_position.intros(1))
next
  case (2 s v va t)
  then show ?case by auto
next
  case (3 m t)
  then show ?case by auto
next
  case (4 m f t)
  then show ?case 
  proof (cases ‹m $$ f›)
    case None
    have ‹sound_storage_from_position (DTNode {f $$:= DTLeaf {t}}) p1›
      by (simp add: 4 sound_storage_from_position.intros)
    then show ?thesis
      by (smt (verit, del_insts) 4 None append.right_neutral dt_trie.distinct(1) dt_trie.sel(2) fmdom'_empty fmdom'_fmupd fmupd_lookup insertE insert_aux.simps(4) list.set(1,2) list.set_intros(1) option.case_eq_if option.sel sound_storage_from_position.simps update_entry.simps)
  next
    case (Some a)
    let ?m = ‹m(f $$:= insert_aux (case m $$ f of None ⇒ DTLeaf {t} | Some v0 ⇒ v0) [] t)›
    have ‹∀s ∈ fmdom' ?m. sound_storage_from_position (?m $$! s) (p1 @ [s])›
      by (metis 4 Some append.right_neutral dt_trie.distinct(1) dt_trie.sel(2) fmdom'I fmdom'_fmupd fmupd_lookup insert_absorb option.sel option.simps(5) sound_storage_from_position.simps)
    then show ?thesis
      using sound_storage_from_position.simps by fastforce
  qed
next
  case (5 m f v va t)
  then show ?case
  proof (cases ‹m $$ f›)
    case None
    let ?m = ‹m(f $$:= insert_aux (case m $$ f of None ⇒ empty_dt_trie | Some v0 ⇒ v0) (v # va) t)›
    have ‹sound_storage_from_position (DTNode {f $$:= insert_aux (DTNode {$$}) (v # va) t }) p1›
      by (simp add: 5 sound_storage_from_position.intros)
    then have ‹∀s ∈ fmdom' ?m. sound_storage_from_position (?m $$! s) (p1 @ [s])›
      by (metis 5(3) None dt_trie.distinct(1) dt_trie.sel(2) fmdom'_fmupd fmupd_lookup insert_iff option.simps(4) sound_storage_from_position.simps)
    then show ?thesis
      using sound_storage_from_position.simps by fastforce
  next
    case (Some a)
    let ?m = ‹m(f $$:= insert_aux (case m $$ f of None ⇒ empty_dt_trie | Some v0 ⇒ v0) (v # va) t)›
    have ‹sound_storage_from_position (DTNode {f $$:= insert_aux a (v # va) t }) p1›
      by (metis (no_types, lifting) 5 Some append.assoc append.simps(2) append_self_conv2 dt_trie.distinct(1) dt_trie.sel(2) fmdom'I fmdom'_empty fmdom'_fmupd fmupd_lookup option.sel singletonD sound_storage_from_position.simps)
    then have h2: ‹∀s ∈ fmdom' ?m. sound_storage_from_position (?m $$! s) (p1 @ [s])›
      by (metis 5(3) Some dt_trie.distinct(1) dt_trie.sel(2) fmdom'_fmupd fmupd_lookup insert_iff option.simps(5) sound_storage_from_position.simps)
    then show ?thesis
      using sound_storage_from_position.simps by fastforce
  qed
qed

lemma insert_aux_nonempty: ‹insert_aux tr (s # p) t ≠ empty_dt_trie›
proof (cases tr)
  case (DTLeaf ts)
  then show ?thesis
    using insert_aux.elims by blast
next
  case (DTNode tr2)
  then show ?thesis
    by (cases p ; simp)
qed

lemma insert_aux_empty_minimal: ‹minimal_storage (insert_aux empty_dt_trie (s # p) t)›
proof (induction p arbitrary: s)
  case Nil
  have ‹minimal_storage (DTLeaf {t})›
    using minimal_storage_leaf by auto
  then show ?case
    using minimal_storage_node
    by (simp add: fmran'_alt_def fmran_singleton insert_aux_nonempty minimal_storage_node)
next
  case (Cons s2 ss)
  then show ?case
    using minimal_storage_leaf
    by (simp add: fmran'_alt_def fmran_singleton insert_aux_nonempty minimal_storage_node)
qed

lemma insert_aux_preserves_minimal:
  ‹minimal_storage tr ⟹ minimal_storage (insert_aux tr p t)›
proof (induction tr arbitrary: p)
  case (DTLeaf ts)
  then show ?case
  proof (cases p)
    case Nil
    then show ?thesis
      by (simp add: minimal_storage_leaf)
  next
    case (Cons _ _)
    then show ?thesis
      by (simp add: DTLeaf)
  qed
next
  case (DTNode m)
  then show ?case
  proof (cases p)
    case Nil
    then show ?thesis
      by (simp add: DTNode)
  next
    case c1: (Cons s1 ss1)
    then show ?thesis
    proof (cases ss1)
      case Nil
      have ‹∀x ∈ fmran' (update_entry m s1 (λtr. insert_aux tr [] t) (DTLeaf {t})). minimal_storage x ∧ x ≠ empty_dt_trie›
      proof (rule update_entry_preservation)
        show ‹∀x∈fmran' m. minimal_storage x ∧ x ≠ empty_dt_trie›
          by (metis DTNode.prems dt_trie.distinct(1) dt_trie.sel(2) minimal_storage.cases)
      next
        show ‹∀v0. m $$ s1 = Some v0 ⟶ minimal_storage (insert_aux v0 [] t) ∧ insert_aux v0 [] t ≠ empty_dt_trie›
          by (metis DTNode.IH DTNode.prems dt_trie.distinct(1) dt_trie.sel(2) fmlookup_ran'_iff insert_aux.simps(1) insert_aux.simps(3) minimal_storage.simps)
      next
        show ‹minimal_storage (insert_aux (DTLeaf {t}) [] t) ∧ insert_aux (DTLeaf {t}) [] t ≠ empty_dt_trie›
          by (simp add: minimal_storage_leaf)
      qed
      then show ?thesis using insert_aux.simps(4) [of m s1 t] minimal_storage.minimal_storage_node c1 Nil by auto
    next
      case c2: (Cons s2 ss2)
      have ‹∀x ∈ fmran' (update_entry m s1 (λtr. insert_aux tr (s2 # ss2) t) empty_dt_trie). minimal_storage x ∧ x ≠ empty_dt_trie›
      proof (rule update_entry_preservation)
        show ‹∀x∈fmran' m. minimal_storage x ∧ x ≠ empty_dt_trie›
          by (metis DTNode.prems dt_trie.distinct(1) dt_trie.sel(2) minimal_storage.cases)
      next
        show ‹∀v0. m $$ s1 = Some v0 ⟶ minimal_storage (insert_aux v0 (s2 # ss2) t) ∧ insert_aux v0 (s2 # ss2) t ≠ empty_dt_trie›
          using DTNode insert_aux_nonempty
          by (metis dt_trie.distinct(1) dt_trie.sel(2) fmran'I minimal_storage.simps)
      next
        show ‹minimal_storage (insert_aux empty_dt_trie (s2 # ss2) t) ∧ insert_aux empty_dt_trie (s2 # ss2) t ≠ empty_dt_trie›
          by (simp add: insert_aux_empty_minimal insert_aux_nonempty)
      qed
      then show ?thesis using insert_aux.simps(5) minimal_storage.minimal_storage_node c1 c2 by auto
    qed
  qed
qed

subsection ‹Term removal›

fun remove_aux :: ‹('f, 'v) dt_trie ⇒ ('f symbol) list ⇒ ('f, 'v) term ⇒ ('f, 'v) dt_trie option› where
  ‹remove_aux (DTLeaf ts) [] t     = (if ts = {t} then None else Some (DTLeaf (ts - {t})))›
| ‹remove_aux (DTLeaf ts) p t      = None› (* not reached, but this definition makes preservation proofs easier than 'undefined' *)
| ‹remove_aux (DTNode m) [] t      = None› (* same *)
| ‹remove_aux (DTNode m) (f # p) t = (let nm = update_or_remove_entry m f (λtr. remove_aux tr p t)
                                      in if nm = {$$} then None else Some (DTNode nm))›

lemma remove_aux_empty_trie: ‹remove_aux empty_dt_trie p t = None›
  by (smt (verit, best) fmempty_lookup neq_Nil_conv option.simps(4) remove_aux.simps(3,4) update_or_remove_entry.simps)

lemma remove_yields_none:
  assumes ‹preorder_string t = s1 @ s2› 
      and ‹sound_storage tr_root›
      and ‹minimal_storage tr_root›
      and ‹subdt_trie_at_path tr_root s1 tr›
      and ‹remove_aux tr s2 t = None›
    shows ‹to_set tr ⊆ { t }›
 using assms
proof (induction tr s2 t arbitrary: s1 rule: remove_aux.induct)
  case (1 ts t)
  then show ?case
    by (metis option.distinct(1) remove_aux.simps(1) subset_refl to_set.simps(1))
next
  case (2 ts v va t)
  then obtain t2 where ‹t2 ∈ ts›
    using minimal_storage_members minimal_storage_subdt_trie to_set.simps(1) by blast
  then have ‹preorder_string t2 = s1›
    by (metis 2(4) assms(2) insert_absorb sound_storage_def)
  then show ?case
    by (metis 2(1) list.discI preorder_string_prefix)
next
  case (3 m t)
  have h0: ‹minimal_storage (DTNode m)›
    using 3(4) assms(3) minimal_storage_subdt_trie by blast
  moreover have ‹m ≠ {$$}›
    using 3(1,4) assms(3) minimal_storage_no_empty_subtrie by fastforce
  ultimately obtain ts s2 where h1: ‹subdt_trie_at_path (DTNode m) s2 (DTLeaf ts)›
                            and h2: ‹s2 ≠ []›
    by (metis dt_trie.distinct(1) dt_trie.inject(2) list.discI minimal_storage_members subdt_trie_at_path.cases to_set_path)
  then obtain t2 where ‹t2 ∈ ts›
    using h0 minimal_storage_members minimal_storage_subdt_trie to_set.simps(1) by blast
  then have ‹preorder_string t2 = s1 @ s2›
    using 3(4) h1 assms(2) mk_disjoint_insert sound_storage_def subdt_trie_at_path_trans by fastforce
  then show ?case
    by (metis 3(1) append.right_neutral h2 preorder_string_prefix)
next
  case (4 m f p t)
  then have h0: ‹update_or_remove_entry m f (λtr. remove_aux tr p t) = {$$}›
    by (smt (verit, ccfv_threshold) option.case_eq_if option.distinct(1) remove_aux.simps(4) update_or_remove_entry.simps)
  then have ‹⋀tr2. tr2 ∈ fmran' m ⟹ to_set tr2 ⊆ {t}›
  proof -
    fix tr2
    assume ‹tr2 ∈ fmran' m›
    then obtain s where h1: ‹m $$ s = Some tr2› by auto
    then have ‹s = f›
      by (smt (verit, ccfv_threshold) h0 fmdom'I fmdom'_notI fmempty_lookup fmlookup_drop fmupd_lookup
          option.case_eq_if update_or_remove_entry.simps)
    then have ‹subdt_trie_at_path tr_root (s1 @ [f]) tr2›
      using 4(5) h1 subdt_trie_at_path_empty subdt_trie_at_path_step subdt_trie_at_path_trans by blast
    moreover have ‹remove_aux tr2 p t = None›
      using ‹s = f› h0 h1 option.sel by fastforce
    ultimately show ‹to_set tr2 ⊆ {t}› using 4(1) [of ‹s1 @ [f]› tr2]
      using 4(2) assms(2,3) by auto
  qed
  then show ?case by auto
qed

lemma remove_aux_removes_element:
  assumes ‹preorder_string t = s1 @ s2› 
      and ‹sound_storage tr_root›
      and ‹minimal_storage tr_root›
      and ‹subdt_trie_at_path tr_root s1 tr›
      and ‹remove_aux tr s2 t = Some tr2›
    shows ‹t ∉ to_set tr2›
  using assms
proof (induction tr s2 t arbitrary: s1 tr2 rule: remove_aux.induct)
  case (1 ts t)
  then show ?case
    by (metis Diff_iff insertCI option.distinct(1) option.sel remove_aux.simps(1) to_set.simps(1))
next
  case (2 ts v va t)
  then show ?case by auto
next
  case (3 m t)
  then show ?case by auto
next
  case (4 m f p t)
  let ?nm = ‹update_or_remove_entry m f (λtr. remove_aux tr p t)›
  have ‹tr2 = DTNode ?nm›
    by (smt (verit) 4 option.case_eq_if option.distinct(1) option.inject remove_aux.simps(4) update_or_remove_entry.simps)
  moreover have ‹⋀tr3. tr3 ∈ fmran' ?nm ⟹ t ∉ to_set tr3›
  proof -
    fix tr3
    assume ‹tr3 ∈ fmran' ?nm›
    then obtain s where h0: ‹?nm $$ s = Some tr3› by auto
    show ‹t ∉ to_set tr3›
    proof (cases ‹s = f›)
      case True
      from h0 obtain tr3' where h1: ‹m $$ s = Some tr3'›
        by (metis fmlookup_dom'_iff insert_absorb insert_subset update_or_remove_entry_dom)
      then have ‹subdt_trie_at_path tr_root (s1 @ [f]) tr3'›
        using 4(5) True subdt_trie_at_path_empty subdt_trie_at_path_step subdt_trie_at_path_trans by blast
      moreover have ‹remove_aux tr3' p t = Some tr3›
        by (smt (verit, ccfv_SIG) True h1 fmlookup_drop fmupd_lookup h0 option.case_eq_if option.collapse option.simps(5)
            update_or_remove_entry.simps)
      ultimately show ?thesis using 4 assms(2,3) by auto
    next
      case False
      then have ‹m $$ s = Some tr3›
        by (smt (verit) h0 fmlookup_drop fmupd_lookup option.case_eq_if update_or_remove_entry.simps)
      then have ‹sound_storage_from_position tr3 (s1 @ [s])›
        by (smt (verit, del_insts) 4(5) assms(2) calculation sound_storage_def sound_storage_from_position_alt_def subdt_trie_at_path_empty
            subdt_trie_at_path_step subdt_trie_at_path_trans)
      then show ?thesis
        by (smt (verit, ccfv_threshold) 4(2) Cons_eq_appendI False append.assoc list.inject same_append_eq sound_storage_from_position_alt_def
            to_set_path)
    qed
  qed
  ultimately show ?case by simp
qed

lemma remove_aux_keeps_elements:
  assumes ‹preorder_string t = s1 @ s2›
      and ‹sound_storage tr_root›
      and ‹minimal_storage tr_root›
      and ‹subdt_trie_at_path tr_root s1 tr›
      and ‹remove_aux tr s2 t = Some tr2›
      and ‹x ≠ t›
      and ‹x ∈ to_set tr›
    shows ‹x ∈ to_set tr2›
  using assms
proof (induction tr s2 t arbitrary: s1 tr2 rule: remove_aux.induct)
  case (1 ts t)
  then show ?case
    by (metis Diff_iff empty_iff insertE option.sel remove_aux.simps(1) to_set.simps(1))
next
  case (2 ts v va t)
  then show ?case by auto
next
  case (3 m t)
  then show ?case by auto
next
  case (4 m f p t)
  let ?nm = ‹update_or_remove_entry m f (λtr. remove_aux tr p t)›
  have h0: ‹tr2 = DTNode ?nm›
    by (smt (verit) 4 option.case_eq_if option.distinct(1) option.inject remove_aux.simps(4) update_or_remove_entry.simps)
  obtain s tr3 where h1: ‹m $$ s = Some tr3›
                 and h2: ‹x ∈ to_set tr3›
    using 4(8) by auto
  show ?case
  proof (cases ‹s = f›)
    case True
    have h3: ‹subdt_trie_at_path tr_root (s1 @ [f]) tr3›
      using 4(5) True h1 subdt_trie_at_path_empty subdt_trie_at_path_step subdt_trie_at_path_trans by blast
    have h4: ‹remove_aux tr3 p t = ?nm $$ s›
      by (smt (verit, best) True fmdrop_lookup fmupd_lookup h1 option.case_eq_if option.exhaust_sel option.simps(5) update_or_remove_entry.simps)
    then have h5: ‹remove_aux tr3 p t = Some (?nm $$! s)›
      by (metis 4(2,7) h3 append_Cons append_Nil append_assoc assms(2,3) emptyE h2 insertE insert_absorb
          insert_subset option.collapse remove_yields_none)
    then have ‹x ∈ to_set (?nm $$! s)›
      using 4(1,2,7) assms(2,3) h2 h3 h5 by force
    then show ?thesis
      by (metis h0 h4 h5 subdt_toset subdt_trie_at_path_step to_set_path)
  next
    case False
    then have ‹?nm $$ s = Some tr3›
      by (simp add: h1 option.case_eq_if)
    then show ?thesis
      using h0 h2 subdt_toset subdt_trie_at_path_step to_set_path by blast
  qed
qed

lemma remove_aux_subset:
  assumes ‹preorder_string t = s1 @ s2› 
      and ‹sound_storage tr_root›
      and ‹minimal_storage tr_root›
      and ‹subdt_trie_at_path tr_root s1 tr›
      and ‹remove_aux tr s2 t = Some tr2›
      and ‹x ∈ to_set tr2›
    shows ‹x ∈ to_set tr›
  using assms
proof (induction tr s2 t arbitrary: s1 tr2 rule: remove_aux.induct)
  case (1 ts t)
  then show ?case
    by (metis Diff_iff option.distinct(1) option.sel remove_aux.simps(1) to_set.simps(1))
next
  case (2 ts v va t)
  then show ?case by auto
next
  case (3 m t)
  then show ?case by auto
next
  case (4 m f p t)
  let ?nm = ‹update_or_remove_entry m f (λtr. remove_aux tr p t)›
  have h0: ‹tr2 = DTNode ?nm›
    by (smt (verit) 4 option.case_eq_if option.distinct(1) option.inject remove_aux.simps(4) update_or_remove_entry.simps)
  then obtain s tr3 where h1: ‹?nm $$ s = Some tr3›
                      and h2: ‹x ∈ to_set tr3›
    using 4(7) by auto
  show ?case
  proof (cases ‹s = f›)
    case True
    have ‹subdt_trie_at_path tr_root (s1 @ [f]) (m $$! s)›
      by (metis (no_types, lifting) 4(5) True h1 not_Some_eq option.case_eq_if option.collapse subdt_trie_at_path.simps subdt_trie_at_path_trans
          update_or_remove_entry.simps)
    moreover have ‹remove_aux (m $$! s) p t = Some tr3›
      by (smt (verit, ccfv_threshold) True fmlookup_drop fmupd_lookup h1 option.case_eq_if option.collapse option.distinct(1) update_or_remove_entry.simps)
    ultimately show ?thesis
      by (metis (lifting) 4(1,2,7) True append.left_neutral append_Cons append_assoc assms(2,3) h0 h2 option.case_eq_if option.collapse subdt_toset
          subdt_trie_at_path_step to_set_path update_or_remove_entry.simps)
  next
    case False
    then have ‹m $$ s = Some tr3›
      by (smt (verit) fmlookup_drop fmupd_lookup h1 option.case_eq_if update_or_remove_entry.simps)
    then show ?thesis
      using h2 subdt_toset subdt_trie_at_path_step to_set_path by blast
  qed
qed

lemma remove_spec:
  assumes ‹sound_storage tr›
      and ‹minimal_storage tr›
      and ‹remove_aux tr (preorder_string t) t = Some tr2›
    shows ‹to_set tr2 = to_set tr - {t}›
proof
  show ‹to_set tr2 ⊆ to_set tr - {t}›
    using assms(1,2,3) remove_aux_removes_element remove_aux_subset subdt_trie_at_path_empty by fastforce
next
  show ‹to_set tr - {t} ⊆ to_set tr2›
    using assms(1,2,3) remove_aux_keeps_elements subdt_trie_at_path_empty by fastforce
qed

lemma remove_aux_preserves_sound:
  assumes ‹sound_storage_from_position tr p›
      and ‹remove_aux tr p2 t = Some tr2›
    shows ‹sound_storage_from_position tr2 p›
  using assms
proof (induction tr p2 t arbitrary: p tr2 rule: remove_aux.induct)
  case (1 ts t)
  then show ?case
    by (smt (verit, best) Diff_iff dt_trie.simps(4) option.distinct(1) option.sel remove_aux.simps(1) sound_storage_from_position.simps)
next
  case (2 ts v va t)
  then show ?case by auto
next
  case (3 m t)
  then show ?case by auto
next
  case (4 m f p2 t)
  let ?nm = ‹update_or_remove_entry m f (λtr. remove_aux tr p2 t)›
  have ‹Some tr2 = (if ?nm = {$$} then None else Some (DTNode ?nm))›
    using 4(3) by auto
  then have ‹tr2 = DTNode ?nm›
    by (meson option.discI option.inject)
  moreover have ‹sound_storage_from_position (DTNode ?nm) p›
  proof (rule ssfp_node)
    show ‹∀s∈fmdom' ?nm. sound_storage_from_position (?nm $$! s) (p @ [s])›
    proof
      fix s
      assume h0: ‹s ∈ fmdom' ?nm›
      then have ‹s ∈ fmdom' m›
        using update_or_remove_entry_dom by fast
      then have h1: ‹sound_storage_from_position (m $$! s) (p @ [s])›
        using 4(2) sound_storage_from_position.simps by force
      show ‹sound_storage_from_position (?nm $$! s) (p @ [s])›
      proof (cases ‹f = s›)
        case True
        then show ?thesis
          by (smt (verit, del_insts) 4(1) h0 h1 fmdom'_notI fmlookup_drop fmupd_lookup
              option.case_eq_if option.collapse update_or_remove_entry.simps)
      next
        case False
        then have ‹?nm $$! s = m $$! s›
          by (simp add: option.case_eq_if)
        then show ?thesis using h1 by auto
      qed
    qed
  qed
  ultimately show ?case by auto
qed

lemma remove_aux_preserves_minimal:
  ‹tr ≠ empty_dt_trie ⟹ minimal_storage tr ⟹ remove_aux tr p t = Some tr2 ⟹ minimal_storage tr2 ∧ tr2 ≠ empty_dt_trie›
proof (induction tr arbitrary: p tr2)
  case (DTLeaf ts)
  then show ?case
  proof (cases p)
    case Nil
    then have ‹ts ≠ { t }›
      using DTLeaf.prems(3) local.Nil by auto
    then show ?thesis
      by (metis DTLeaf.prems(2,3) Diff_empty Diff_insert0 dt_trie.simps(4) insert_Diff local.Nil minimal_storage.simps option.sel remove_aux.simps(1))
  next
    case (Cons _ _)
    then show ?thesis
      using DTLeaf.prems(2,3) by auto
  qed
next
  case (DTNode m)
  then show ?case
  proof (cases p)
    case Nil
    then show ?thesis
      using DTNode.prems(1,2,3) by auto
  next
    case (Cons f p2)
    let ?nm = ‹update_or_remove_entry m f (λtr. remove_aux tr p2 t)›
    have ‹Some tr2 = (if ?nm = {$$} then None else Some (DTNode ?nm))›
      using DTNode.prems(3) local.Cons by auto
    then have ‹?nm ≠ {$$} ∧ tr2 = DTNode ?nm›
      by (meson not_None_eq option.inject)
    moreover have ‹∀tr3 ∈ fmran' ?nm. minimal_storage tr3 ∧ tr3 ≠ empty_dt_trie›
    proof (rule update_or_remove_entry_preservation)
      show ‹∀tr3∈fmran' m. minimal_storage tr3 ∧ tr3 ≠ empty_dt_trie›
        by (metis DTNode.prems(2) dt_trie.sel(2) dt_trie.simps(4) minimal_storage.cases)
    next
      show ‹∀v0 y. m $$ f = Some v0 ∧ remove_aux v0 p2 t = Some y ⟶ minimal_storage y ∧ y ≠ empty_dt_trie›
        by (metis DTNode.IH DTNode.prems(2) dt_trie.sel(2) dt_trie.simps(4) fmran'I minimal_storage.cases)
    qed
    ultimately show ?thesis
      using minimal_storage_node by auto
  qed
qed

subsection ‹Retrieval operations›

fun retrieve_variants_aux :: ‹('f, 'v) dt_trie ⇒ 'f symbol list ⇒ ('f, 'v) term set› where
  ‹retrieve_variants_aux (DTLeaf ts) [] = ts›
| ‹retrieve_variants_aux (DTLeaf _) _ = {}›
| ‹retrieve_variants_aux (DTNode m) [] = {}›
| ‹retrieve_variants_aux (DTNode m) (s # l) = (case m $$ s of
                                                 None ⇒ {}
                                               | Some tr ⇒ retrieve_variants_aux tr l)›


function retrieve_generalizations_aux :: ‹('f, 'v) dt_trie ⇒ ('f, 'v) term ⇒ epos ⇒ ('f, 'v) term set› where
  ‹retrieve_generalizations_aux (DTLeaf s) t None = s›
| ‹retrieve_generalizations_aux (DTLeaf s) t (Some p) = {}›
| ‹retrieve_generalizations_aux (DTNode m) t None = {}›
| ‹retrieve_generalizations_aux (DTNode m) t (Some p) = (let var_terms = (case m $$ Star of
                                                           None ⇒ {}
                                                         | Some tr ⇒ retrieve_generalizations_aux tr t (after_position t p)) in
                                                         var_terms ∪ (case m $$ (root_symbol (t |_ p)) of
                                                                        None ⇒ {}
                                                                      | Some tr2 ⇒ retrieve_generalizations_aux tr2 t (next_position t p)))›
  by pat_completeness auto
termination 
  by (relation ‹measure (λ(p, q, t). size p)›) (auto simp add: fmran'I)

lemma retrieve_variants_aux_in_set:
  ‹e ∈ retrieve_variants_aux tr l ⟹ e ∈ to_set tr›
proof (induction tr arbitrary:l )
  case (DTLeaf ts)
  then show ?case
  proof (cases l)
    case Nil
    then show ?thesis using DTLeaf by auto
  next
    case (Cons _ _)
    then show ?thesis using DTLeaf by auto
  qed
next
  case (DTNode m)
  then show ?case
  proof (cases l)
    case Nil
    then show ?thesis using DTNode by auto
  next
    case (Cons s l2)
    then show ?thesis
    proof (cases ‹m $$ s›)
      case None
      then show ?thesis using DTNode Cons by auto
    next
      case (Some n)
      then show ?thesis
        using DTNode.IH DTNode.prems fmran'I local.Cons by fastforce
    qed
  qed
qed

lemma retrieve_variants_aux_sound:
  ‹sound_storage_from_position tr p ⟹ t ∈ retrieve_variants_aux tr l ⟹ preorder_string t = p @ l›
proof (induction tr arbitrary: l p)
  case (DTLeaf ts)
  then show ?case
  proof (cases l)
    case Nil
    then have ‹t ∈ ts› using DTLeaf by auto
    then show ?thesis
      using DTLeaf.prems(1) local.Nil sound_storage_from_position.simps by fastforce
  next
    case (Cons _ _)
    then show ?thesis using DTLeaf by auto
  qed
next
  case (DTNode m)
  then show ?case
  proof (cases l)
    case Nil
    then show ?thesis using DTNode by auto
  next
    case (Cons s _)
    then show ?thesis
    proof (cases ‹m $$ s›)
      case None
      then show ?thesis using DTNode Cons by auto
    next
      case (Some tr2)
      then have ‹sound_storage_from_position tr2 (p @ [s])›
        by (metis DTNode.prems(1) dt_trie.distinct(1) dt_trie.sel(2) fmdom'I option.sel sound_storage_from_position.simps)
      then show ?thesis
        using DTNode Some fmran'I local.Cons by fastforce
    qed
  qed
qed

lemma retrieve_variants_aux_complete:
  ‹sound_storage_from_position tr p ⟹ t ∈ to_set tr ⟹ preorder_string t = p @ l ⟹ t ∈ retrieve_variants_aux tr l›
proof (induction tr arbitrary: p l)
  case (DTLeaf ts)
  then have ‹l = []›
    by (metis append_self_conv retrieve_variants_aux.simps(1) retrieve_variants_aux_sound to_set.simps(1))
  then show ?case
    using DTLeaf.prems(2) by force
next
  case (DTNode m)
  then show ?case
  proof (cases l)
    case Nil
    then show ?thesis
      using DTNode.prems(1-3) subdt_trie_at_path.cases to_set_sound_from by blast
  next
    case (Cons s ss)
    then show ?thesis
    proof (cases ‹m $$ s›)
      case None
      then show ?thesis
        by (smt (verit, best) DTNode.prems(1-3) dt_trie.distinct(1) dt_trie.sel(2) fmdom'I fmdom'_notI list.sel(1) local.Cons subdt_trie_at_path.simps to_set_sound_from)
    next
      case (Some tr2)
      then have ‹tr2 ∈ fmran' m ∧ sound_storage_from_position tr2 (p @ [s])›
        by (metis DTNode.prems(1) dt_trie.distinct(1) dt_trie.sel(2) fmdom'I fmran'I option.sel sound_storage_from_position.simps)
      moreover have ‹t ∈ to_set tr2›
        by (smt (verit, best) DTNode.prems(1-3) Some dt_trie.sel(2) list.distinct(1) list.sel(1) local.Cons option.sel subdt_toset subdt_trie_at_path.simps to_set_sound_from)
      ultimately show ?thesis
        using DTNode.IH [of tr2 ‹p @ [s]› ss]
        by (simp add: DTNode.prems(3) Some local.Cons)
    qed
  qed
qed

theorem retrieve_variants_spec: ‹sound_storage tr ⟹ retrieve_variants_aux tr (preorder_string t) = {t2. t2 ∈ to_set tr ∧ linear_variant t2 t}›
proof -
  assume h: ‹sound_storage tr›
  show ‹retrieve_variants_aux tr (preorder_string t) = {t2. t2 ∈ to_set tr ∧ linear_variant t2 t}›
  proof
    show ‹retrieve_variants_aux tr (preorder_string t) ⊆ {t2 ∈ to_set tr. linear_variant t2 t}›
      by (metis (no_types, lifting) append_Nil h mem_Collect_eq retrieve_variants_aux_in_set retrieve_variants_aux_sound same_preorder_string_linear_variant
          sound_storage_from_empty_position subsetI)
  next
    show ‹{t2 ∈ to_set tr. linear_variant t2 t} ⊆ retrieve_variants_aux tr (preorder_string t)›
      using h linear_variant_same_preorder_string retrieve_variants_aux_complete sound_storage_from_empty_position by fastforce
  qed
qed
  
lemma retrieve_generalizations_in_set: 
  assumes ‹e ∈ retrieve_generalizations_aux tr t ep›
    shows ‹e ∈ to_set tr›
  using assms
proof (induction tr arbitrary: ep)
  case (DTLeaf ts)
  then show ?case  
    by (metis empty_iff option.exhaust_sel retrieve_generalizations_aux.simps(1,2) to_set.simps(1))
next
  case (DTNode m)
  then show ?case
  proof (cases ep)
    case None
    then show ?thesis 
      using DTNode.prems by force
  next
    case (Some p)
    then show ?thesis 
      by (smt (verit, del_insts) DTNode.IH DTNode.prems UN_I UnE empty_iff fmran'I option.case_eq_if option.collapse retrieve_generalizations_aux.simps(4) to_set.simps(2))
  qed
qed


lemma retrieve_generalizations_sound_aux:
  assumes ‹sound_storage_from_position tr s1›
      and ‹preorder_string t = s2 @ s3›
      and ‹preorder_string_upto t ep s2›
      and ‹x ∈ retrieve_generalizations_aux tr t ep›
      and ‹s1 @ s3 ∈ linear_generalization_preorder_strings t›
    shows ‹preorder_string x ∈ linear_generalization_preorder_strings t›
  using assms
proof (induction tr arbitrary: ep s1 s2 s3)
  case (DTLeaf ts)
  then have ‹ep = None›
    by (metis empty_iff option.exhaust retrieve_generalizations_aux.simps(2))
  then have ‹s3 = []›
    using DTLeaf.prems(2) DTLeaf.prems(3) preorder_string_upto_None by blast
  moreover from DTLeaf have ‹preorder_string x = s1›
    by (metis dt_trie.distinct(1) retrieve_generalizations_in_set sound_storage_from_position.cases to_set.simps(1))
  ultimately show ?case
    using DTLeaf.prems(5) by force
next
  case (DTNode m)
  then obtain p where h1: ‹ep = Some p› by fastforce
  then consider (a) ‹∃tr2. m $$ Star = Some tr2 ∧ x ∈ retrieve_generalizations_aux tr2 t (after_position t p)›
              | (b) ‹∃tr2. m $$ (root_symbol (t |_ p)) = Some tr2 ∧ x ∈ retrieve_generalizations_aux tr2 t (next_position t p)›
    by (metis (no_types, lifting) DTNode.prems(4) UnE empty_iff option.case_eq_if option.collapse retrieve_generalizations_aux.simps(4))
  then show ?case
  proof cases
    case a
    then obtain tr2 where h2: ‹m $$ Star = Some tr2› and h3: ‹x ∈ retrieve_generalizations_aux tr2 t (after_position t p)› by auto
    then have ‹sound_storage_from_position tr2 (s1 @ [Star])›
      by (metis DTNode.prems(1) dt_trie.distinct(1) dt_trie.sel(2) fmdom'I option.sel sound_storage_from_position.simps)
    moreover obtain s4 where ‹preorder_string t = s2 @ preorder_string (t |_ p) @ s4›
      using DTNode.prems(2,3) h1 preorder_string_upto_next_term by blast
    moreover have ‹preorder_string_upto t (after_position t p) (s2 @ preorder_string (t |_ p))›
      using DTNode.prems(3) h1 preorder_string_upto_after_position by blast
    moreover have ‹s1 @ [Star] @ s4 ∈ linear_generalization_preorder_strings t› 
      using linear_generalization_star DTNode.prems(2,5) calculation(2) by fastforce
    ultimately show ?thesis
      by (metis DTNode.IH append.assoc fmran'I h2 h3)
  next
    case b
    then obtain tr2 where h2: ‹m $$ (root_symbol (t |_ p)) = Some tr2› and h3: ‹x ∈ retrieve_generalizations_aux tr2 t (next_position t p)› by auto
    then have ‹sound_storage_from_position tr2 (s1 @ [root_symbol (t |_ p)])›
      by (metis DTNode.prems(1) dt_trie.distinct(1) dt_trie.sel(2) fmdom'I option.sel sound_storage_from_position.simps)
    moreover have ‹preorder_string t = (s2 @ [root_symbol (t |_ p)]) @ tl s3›
      using DTNode.prems(2,3) h1 preorder_string_upto_next_symbol preorder_string_upto.intros(2) preorder_string_upto_None by fastforce
    moreover have ‹preorder_string_upto t (next_position t p) (s2 @ [root_symbol (t |_ p)])›
      using DTNode.prems(3) h1 preorder_string_upto.intros(2) by blast
    ultimately show ?thesis
      by (smt (verit, best) DTNode.IH DTNode.prems(2,5) append_assoc fmran'I h2 h3 same_append_eq)
  qed
qed

lemma trie_element_symbol_at_position:
  assumes ‹sound_storage_from_position (DTNode m) s1›
      and ‹m $$ s = Some tr›
      and ‹x ∈ to_set tr›
      and ‹preorder_string_upto x (Some p) s1›
    shows ‹root_symbol (x |_ p) = s›
proof -
  obtain ts s2 where ‹x ∈ ts›
                 and ‹subdt_trie_at_path tr s2 (DTLeaf ts)›
    by (meson assms(3) insertI1 to_set_path)
  then have ‹preorder_string x = s1 @ s # s2›
    by (metis assms(1,2) insert_Diff sound_storage_from_position_alt_def subdt_trie_at_path_step)
  then show ?thesis
    using assms(4) preorder_string_upto_next_symbol by auto
qed


lemma linear_generalization_non_var_same_symbol:
  assumes ‹linear_generalization x t›
      and ‹root_symbol (x |_ p) = F f n›
      and ‹p ∈ poss x›
    shows ‹root_symbol (t |_ p) = F f n›
  using assms
  unfolding linear_generalization_def
  by (induction arbitrary: p f n; force)

lemma linear_generalization_after_position:
  assumes ‹linear_generalization t1 t2›
      and ‹p ∈ poss t1›
    shows ‹after_position t1 p = after_position t2 p›
  using assms
proof (induction p rule: rev_induct)
  case Nil
  then show ?case by auto
next
  case (snoc i ps)
  then obtain f f_args where ‹t1 |_ ps = Fun f f_args›
    using fun_poss_append_poss fun_poss_fun_conv by blast
  then show ?case
    by (smt (verit, best) snoc after_position.elims append_is_Nil_conv butlast_snoc linear_generalization_non_var_same_symbol poss_append_poss root_symbol.simps(2) root_symbol_arity)
qed

lemma retrieve_generalizations_complete_aux:
  assumes ‹sound_storage_from_position tr s1›
      and ‹preorder_string x = s1 @ s2›
      and ‹preorder_string_upto x ep s1›
      and ‹s1 @ s2 ∈ linear_generalization_preorder_strings t›
      and ‹x ∈ to_set tr›
    shows ‹x ∈ retrieve_generalizations_aux tr t ep›
  using assms
proof (induction tr arbitrary: ep s1 s2)
  case (DTLeaf ts)
  then show ?case
    by (metis Nil_is_append_conv non_empty_preorder_string option.exhaust preorder_string_upto_next_term retrieve_generalizations_aux.simps(1) retrieve_variants_aux.simps(1) retrieve_variants_aux_sound to_set.simps(1))
next
  case (DTNode m)
  then obtain p where h0: ‹ep = Some p›
    by (metis append.right_neutral empty_iff option.exhaust preorder_string_upto_None retrieve_variants_aux.simps(3)
        retrieve_variants_aux_complete)
  then have h1: ‹p ∈ poss x› using DTNode.prems(3) preorder_string_upto_poss by auto
  from DTNode obtain s tr2 where h2: ‹m $$ s = Some tr2 ∧ x ∈ to_set tr2› by auto
  then have h3: ‹sound_storage_from_position tr2 (s1 @ [s])›
    by (metis DTNode.prems(1) dt_trie.distinct(1) dt_trie.sel(2) fmdom'I option.sel sound_storage_from_position.simps)
  then have h4: ‹root_symbol (x |_ p) = s›
      using DTNode.prems(1,3) h0 h2 trie_element_symbol_at_position by blast
  show ?case
  proof (cases s)
    case Star
    then have ‹after_position t p = next_position x p›
      by (metis assms(2,4) h1 h4 linear_generalization_def linear_generalization_preorder_strings_sound arity.simps(1) assms(2,4) linear_generalization_after_position next_position.simps root_symbol.simps(1) root_symbol_arity)
    then have ‹preorder_string_upto x (after_position t p) (s1 @ [Star])›
      by (metis DTNode.prems(3) Star h0 h4 preorder_string_upto.intros(2))
    moreover have ‹s1 @ [Star] @ tl s2 ∈ linear_generalization_preorder_strings t›
      by (metis DTNode.prems(2,3) Star append_Cons append_Nil assms(2,4) h0 h4 preorder_string_upto_next_symbol)
    ultimately have ‹x ∈ retrieve_generalizations_aux tr2 t (after_position t p)›
      using DTNode Star fmran'I h0 h2 h3 h4 preorder_string_upto_next_symbol by fastforce
    then show ?thesis
      using Star h0 h2 by force
  next
    case (F f n)
    then have ‹next_position t p = next_position x p›
      by (metis DTNode.prems(2,4) h1 h4 linear_generalization_def linear_generalization_preorder_strings_sound linear_generalization_after_position linear_generalization_non_var_same_symbol next_position.simps root_symbol_arity)
    then have ‹x ∈ retrieve_generalizations_aux tr2 t (next_position t p)›
      using DTNode assms(2,4) fmlookup_ran'_iff h0 h2 h3 h4 preorder_string_upto.intros(2) preorder_string_upto_next_symbol by fastforce
    moreover have ‹root_symbol (t |_ p) = s› 
      by (metis assms(2,4) h1 h4 linear_generalization_non_var_same_symbol F linear_generalization_def linear_generalization_preorder_strings_sound)
    ultimately show ?thesis
      by (simp add: h0 h2)
  qed
qed

theorem retrieve_generalizations_spec: ‹sound_storage tr ⟹ retrieve_generalizations_aux tr t (Some []) = {t2. t2 ∈ to_set tr ∧ linear_generalization t2 t}›
proof -
  assume h: ‹sound_storage tr›
  show ‹retrieve_generalizations_aux tr t (Some []) = {t2. t2 ∈ to_set tr ∧ linear_generalization t2 t}›
  proof
    show ‹retrieve_generalizations_aux tr t (Some []) ⊆ {t2 ∈ to_set tr. linear_generalization t2 t}›
      by (smt (verit, best) Ball_Collect append.left_neutral h linear_generalization_def linear_generalization_preorder_strings_complete linear_generalization_preorder_strings_sound linear_instance_refl preorder_string_upto.intros(1) retrieve_generalizations_in_set retrieve_generalizations_sound_aux sound_storage_from_empty_position)
  next
    show ‹{t2 ∈ to_set tr. linear_generalization t2 t} ⊆ retrieve_generalizations_aux tr t (Some [])›
      using h linear_generalization_def linear_generalization_preorder_strings_complete preorder_string_upto.intros(1) retrieve_generalizations_complete_aux sound_storage_from_empty_position by fastforce
  qed
qed

subsection ‹Index type and main theorems›

typedef ('f, 'v) discrimination_tree =
  ‹{ t :: ('f, 'v) dt_trie. sound_storage t ∧ minimal_storage t }›
  by (rule exI [of _ ‹empty_dt_trie›]) auto

setup_lifting type_definition_discrimination_tree

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

lift_definition discrimination_tree_insert :: ‹('f, 'v) discrimination_tree ⇒ ('f, 'v) term ⇒ ('f, 'v) discrimination_tree› is ‹λtr t. insert_aux tr (preorder_string t) t›
  by (simp add: insert_aux_preserves_minimal insert_aux_preserves_sound sound_storage_from_empty_position)

theorem discrimination_tree_insert_spec: ‹discrimination_tree_to_set (discrimination_tree_insert tr t) = insert t (discrimination_tree_to_set tr)›
  using insert_spec
  by (metis Rep_discrimination_tree discrimination_tree_insert.rep_eq discrimination_tree_to_set.rep_eq mem_Collect_eq)

lift_definition discrimination_tree_remove :: ‹('f, 'v) discrimination_tree ⇒ ('f, 'v) term ⇒ ('f, 'v) discrimination_tree› is ‹λtr t. case remove_aux tr (preorder_string t) t of
                                                                                                                                           None ⇒ empty_dt_trie
                                                                                                                                         | Some tr ⇒ tr›
  by (metis (no_types, lifting) empty_trie_minimal option.case_eq_if option.exhaust_sel remove_aux_empty_trie remove_aux_preserves_minimal
      remove_aux_preserves_sound sound_storage_empty_trie sound_storage_from_empty_position)

theorem discrimination_tree_remove_spec: ‹discrimination_tree_to_set (discrimination_tree_remove dtr t) = discrimination_tree_to_set dtr - {t}›
proof (cases ‹remove_aux (Rep_discrimination_tree dtr) (preorder_string t) t›)
  case None
  then have ‹to_set (Rep_discrimination_tree dtr) ⊆ { t }›
    by (metis (no_types, lifting) Rep_discrimination_tree append.left_neutral mem_Collect_eq remove_yields_none subdt_trie_at_path_empty)
  moreover have ‹discrimination_tree_to_set (discrimination_tree_remove dtr t) = {}›
    by (metis None Union_iff all_not_in_conv discrimination_tree_remove.rep_eq discrimination_tree_to_set.rep_eq fmempty_lookup fmlookup_ran'_iff image_iff
        option.distinct(1) option.simps(4) to_set.simps(2))
  ultimately show ?thesis
    by (simp add: discrimination_tree_to_set.rep_eq)
next
  case (Some tr)
  then show ?thesis
    by (metis Domainp.simps cr_discrimination_tree_def discrimination_tree.domain discrimination_tree_remove.rep_eq discrimination_tree_to_set.rep_eq
        option.simps(5) remove_spec)
qed


lift_definition discrimination_tree_retrieve_variants :: ‹('f, 'v) discrimination_tree ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› is ‹λtr t. retrieve_variants_aux tr (preorder_string t)›.

theorem discrimination_tree_retrieve_variants_spec: ‹discrimination_tree_retrieve_variants tr t1 = {t2. t2 ∈ discrimination_tree_to_set tr ∧ linear_variant t2 t1}›
  using retrieve_variants_spec
  by (metis (no_types, lifting) Collect_cong Rep_discrimination_tree discrimination_tree_retrieve_variants.rep_eq discrimination_tree_to_set.rep_eq mem_Collect_eq)

lift_definition discrimination_tree_retrieve_generalizations :: ‹('f, 'v) discrimination_tree ⇒ ('f, 'v) term ⇒ ('f, 'v) term set› is ‹λtr t. retrieve_generalizations_aux tr t (Some [])›.

theorem discrimination_tree_retrieve_generalizations_spec: ‹discrimination_tree_retrieve_generalizations tr t1 = {t2. t2 ∈ discrimination_tree_to_set tr ∧ linear_generalization t2 t1}›
  using retrieve_generalizations_spec
  by (metis (no_types, lifting) Collect_cong Rep_discrimination_tree discrimination_tree_retrieve_generalizations.rep_eq discrimination_tree_to_set.rep_eq mem_Collect_eq)

end