(*  Title:      HOL/Imperative_HOL/ex/Imperative_Quicksort.thy
    Author:     Lukas Bulwahn, TU Muenchen
*)

section \<open>An imperative implementation of Quicksort on arrays\<close>

theory Imperative_Quicksort
imports
  "~~/src/HOL/Imperative_HOL/Imperative_HOL"
  Subarray
  "HOL-Library.Multiset"
  "HOL-Library.Code_Target_Numeral"
begin

text \<open>We prove QuickSort correct in the Relational Calculus.\<close>

definition swap :: "'a::heap array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> unit Heap"
where
  "swap arr i j =
     do {
       x \<leftarrow> Array.nth arr i;
       y \<leftarrow> Array.nth arr j;
       Array.upd i y arr;
       Array.upd j x arr;
       return ()
     }"

lemma effect_swapI [effect_intros]:
  assumes "i < Array.length h a" "j < Array.length h a"
    "x = Array.get h a ! i" "y = Array.get h a ! j"
    "h' = Array.update a j x (Array.update a i y h)"
  shows "effect (swap a i j) h h' r"
  unfolding swap_def using assms by (auto intro!: effect_intros)

lemma swap_permutes:
  assumes "effect (swap a i j) h h' rs"
  shows "mset (Array.get h' a)
  = mset (Array.get h a)"
  using assms
  unfolding swap_def
  by (auto simp add: Array.length_def mset_swap dest: sym [of _ "h'"] elim!: effect_bindE effect_nthE effect_returnE effect_updE)

function part1 :: "'a::{heap,ord} array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> nat Heap"
where
  "part1 a left right p = (
     if (right \<le> left) then return right
     else do {
       v \<leftarrow> Array.nth a left;
       (if (v \<le> p) then (part1 a (left + 1) right p)
                    else (do { swap a left right;
  part1 a left (right - 1) p }))
     })"
by pat_completeness auto

termination
by (relation "measure (\<lambda>(_,l,r,_). r - l )") auto

declare part1.simps[simp del]

lemma part_permutes:
  assumes "effect (part1 a l r p) h h' rs"
  shows "mset (Array.get h' a)
  = mset (Array.get h a)"
  using assms
proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
  case (1 a l r p h h' rs)
  thus ?case
    unfolding part1.simps [of a l r p]
    by (elim effect_bindE effect_ifE effect_returnE effect_nthE) (auto simp add: swap_permutes)
qed

lemma part_returns_index_in_bounds:
  assumes "effect (part1 a l r p) h h' rs"
  assumes "l \<le> r"
  shows "l \<le> rs \<and> rs \<le> r"
using assms
proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
  case (1 a l r p h h' rs)
  note cr = \<open>effect (part1 a l r p) h h' rs\<close>
  show ?case
  proof (cases "r \<le> l")
    case True (* Terminating case *)
    with cr \<open>l \<le> r\<close> show ?thesis
      unfolding part1.simps[of a l r p]
      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
  next
    case False (* recursive case *)
    note rec_condition = this
    let ?v = "Array.get h a ! l"
    show ?thesis
    proof (cases "?v \<le> p")
      case True
      with cr False
      have rec1: "effect (part1 a (l + 1) r p) h h' rs"
        unfolding part1.simps[of a l r p]
        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
      from rec_condition have "l + 1 \<le> r" by arith
      from 1(1)[OF rec_condition True rec1 \<open>l + 1 \<le> r\<close>]
      show ?thesis by simp
    next
      case False
      with rec_condition cr
      obtain h1 where swp: "effect (swap a l r) h h1 ()"
        and rec2: "effect (part1 a l (r - 1) p) h1 h' rs"
        unfolding part1.simps[of a l r p]
        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
      from rec_condition have "l \<le> r - 1" by arith
      from 1(2) [OF rec_condition False rec2 \<open>l \<le> r - 1\<close>] show ?thesis by fastforce
    qed
  qed
qed

lemma part_length_remains:
  assumes "effect (part1 a l r p) h h' rs"
  shows "Array.length h a = Array.length h' a"
using assms
proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
  case (1 a l r p h h' rs)
  note cr = \<open>effect (part1 a l r p) h h' rs\<close>

  show ?case
  proof (cases "r \<le> l")
    case True (* Terminating case *)
    with cr show ?thesis
      unfolding part1.simps[of a l r p]
      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
  next
    case False (* recursive case *)
    with cr 1 show ?thesis
      unfolding part1.simps [of a l r p] swap_def
      by (auto elim!: effect_bindE effect_ifE effect_nthE effect_returnE effect_updE) fastforce
  qed
qed

lemma part_outer_remains:
  assumes "effect (part1 a l r p) h h' rs"
  shows "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h (a::'a::{heap,linorder} array) ! i = Array.get h' a ! i"
  using assms
proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
  case (1 a l r p h h' rs)
  note cr = \<open>effect (part1 a l r p) h h' rs\<close>

  show ?case
  proof (cases "r \<le> l")
    case True (* Terminating case *)
    with cr show ?thesis
      unfolding part1.simps[of a l r p]
      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
  next
    case False (* recursive case *)
    note rec_condition = this
    let ?v = "Array.get h a ! l"
    show ?thesis
    proof (cases "?v \<le> p")
      case True
      with cr False
      have rec1: "effect (part1 a (l + 1) r p) h h' rs"
        unfolding part1.simps[of a l r p]
        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
      from 1(1)[OF rec_condition True rec1]
      show ?thesis by fastforce
    next
      case False
      with rec_condition cr
      obtain h1 where swp: "effect (swap a l r) h h1 ()"
        and rec2: "effect (part1 a l (r - 1) p) h1 h' rs"
        unfolding part1.simps[of a l r p]
        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
      from swp rec_condition have
        "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h a ! i = Array.get h1 a ! i"
        unfolding swap_def
        by (elim effect_bindE effect_nthE effect_updE effect_returnE) auto
      with 1(2) [OF rec_condition False rec2] show ?thesis by fastforce
    qed
  qed
qed

lemma part_partitions:
  assumes "effect (part1 a l r p) h h' rs"
  shows "(\<forall>i. l \<le> i \<and> i < rs \<longrightarrow> Array.get h' (a::'a::{heap,linorder} array) ! i \<le> p)
  \<and> (\<forall>i. rs < i \<and> i \<le> r \<longrightarrow> Array.get h' a ! i \<ge> p)"
  using assms
proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
  case (1 a l r p h h' rs)
  note cr = \<open>effect (part1 a l r p) h h' rs\<close>

  show ?case
  proof (cases "r \<le> l")
    case True (* Terminating case *)
    with cr have "rs = r"
      unfolding part1.simps[of a l r p]
      by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
    with True
    show ?thesis by auto
  next
    case False (* recursive case *)
    note lr = this
    let ?v = "Array.get h a ! l"
    show ?thesis
    proof (cases "?v \<le> p")
      case True
      with lr cr
      have rec1: "effect (part1 a (l + 1) r p) h h' rs"
        unfolding part1.simps[of a l r p]
        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
      from True part_outer_remains[OF rec1] have a_l: "Array.get h' a ! l \<le> p"
        by fastforce
      have "\<forall>i. (l \<le> i = (l = i \<or> Suc l \<le> i))" by arith
      with 1(1)[OF False True rec1] a_l show ?thesis
        by auto
    next
      case False
      with lr cr
      obtain h1 where swp: "effect (swap a l r) h h1 ()"
        and rec2: "effect (part1 a l (r - 1) p) h1 h' rs"
        unfolding part1.simps[of a l r p]
        by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
      from swp False have "Array.get h1 a ! r \<ge> p"
        unfolding swap_def
        by (auto simp add: Array.length_def elim!: effect_bindE effect_nthE effect_updE effect_returnE)
      with part_outer_remains [OF rec2] lr have a_r: "Array.get h' a ! r \<ge> p"
        by fastforce
      have "\<forall>i. (i \<le> r = (i = r \<or> i \<le> r - 1))" by arith
      with 1(2)[OF lr False rec2] a_r show ?thesis
        by auto
    qed
  qed
qed

fun partition :: "'a::{heap,linorder} array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat Heap"
where
  "partition a left right = do {
     pivot \<leftarrow> Array.nth a right;
     middle \<leftarrow> part1 a left (right - 1) pivot;
     v \<leftarrow> Array.nth a middle;
     m \<leftarrow> return (if (v \<le> pivot) then (middle + 1) else middle);
     swap a m right;
     return m
   }"

declare partition.simps[simp del]

lemma partition_permutes:
  assumes "effect (partition a l r) h h' rs"
  shows "mset (Array.get h' a)
  = mset (Array.get h a)"
proof -
    from assms part_permutes swap_permutes show ?thesis
      unfolding partition.simps
      by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) fastforce
qed

lemma partition_length_remains:
  assumes "effect (partition a l r) h h' rs"
  shows "Array.length h a = Array.length h' a"
proof -
  from assms part_length_remains show ?thesis
    unfolding partition.simps swap_def
    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) auto
qed

lemma partition_outer_remains:
  assumes "effect (partition a l r) h h' rs"
  assumes "l < r"
  shows "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h (a::'a::{heap,linorder} array) ! i = Array.get h' a ! i"
proof -
  from assms part_outer_remains part_returns_index_in_bounds show ?thesis
    unfolding partition.simps swap_def
    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) fastforce
qed

lemma partition_returns_index_in_bounds:
  assumes effect: "effect (partition a l r) h h' rs"
  assumes "l < r"
  shows "l \<le> rs \<and> rs \<le> r"
proof -
  from effect obtain middle h'' p where part: "effect (part1 a l (r - 1) p) h h'' middle"
    and rs_equals: "rs = (if Array.get h'' a ! middle \<le> Array.get h a ! r then middle + 1
         else middle)"
    unfolding partition.simps
    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) simp
  from \<open>l < r\<close> have "l \<le> r - 1" by arith
  from part_returns_index_in_bounds[OF part this] rs_equals \<open>l < r\<close> show ?thesis by auto
qed

lemma partition_partitions:
  assumes effect: "effect (partition a l r) h h' rs"
  assumes "l < r"
  shows "(\<forall>i. l \<le> i \<and> i < rs \<longrightarrow> Array.get h' (a::'a::{heap,linorder} array) ! i \<le> Array.get h' a ! rs) \<and>
  (\<forall>i. rs < i \<and> i \<le> r \<longrightarrow> Array.get h' a ! rs \<le> Array.get h' a ! i)"
proof -
  let ?pivot = "Array.get h a ! r"
  from effect obtain middle h1 where part: "effect (part1 a l (r - 1) ?pivot) h h1 middle"
    and swap: "effect (swap a rs r) h1 h' ()"
    and rs_equals: "rs = (if Array.get h1 a ! middle \<le> ?pivot then middle + 1
         else middle)"
    unfolding partition.simps
    by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) simp
  from swap have h'_def: "h' = Array.update a r (Array.get h1 a ! rs)
    (Array.update a rs (Array.get h1 a ! r) h1)"
    unfolding swap_def
    by (elim effect_bindE effect_returnE effect_nthE effect_updE) simp
  from swap have in_bounds: "r < Array.length h1 a \<and> rs < Array.length h1 a"
    unfolding swap_def
    by (elim effect_bindE effect_returnE effect_nthE effect_updE) simp
  from swap have swap_length_remains: "Array.length h1 a = Array.length h' a"
    unfolding swap_def by (elim effect_bindE effect_returnE effect_nthE effect_updE) auto
  from \<open>l < r\<close> have "l \<le> r - 1" by simp
  note middle_in_bounds = part_returns_index_in_bounds[OF part this]
  from part_outer_remains[OF part] \<open>l < r\<close>
  have "Array.get h a ! r = Array.get h1 a ! r"
    by fastforce
  with swap
  have right_remains: "Array.get h a ! r = Array.get h' a ! rs"
    unfolding swap_def
    by (auto simp add: Array.length_def elim!: effect_bindE effect_returnE effect_nthE effect_updE) (cases "r = rs", auto)
  from part_partitions [OF part]
  show ?thesis
  proof (cases "Array.get h1 a ! middle \<le> ?pivot")
    case True
    with rs_equals have rs_equals: "rs = middle + 1" by simp
    {
      fix i
      assume i_is_left: "l \<le> i \<and> i < rs"
      with swap_length_remains in_bounds middle_in_bounds rs_equals \<open>l < r\<close>
      have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
      from i_is_left rs_equals have "l \<le> i \<and> i < middle \<or> i = middle" by arith
      with part_partitions[OF part] right_remains True
      have "Array.get h1 a ! i \<le> Array.get h' a ! rs" by fastforce
      with i_props h'_def in_bounds have "Array.get h' a ! i \<le> Array.get h' a ! rs"
        unfolding Array.update_def Array.length_def by simp
    }
    moreover
    {
      fix i
      assume "rs < i \<and> i \<le> r"

      hence "(rs < i \<and> i \<le> r - 1) \<or> (rs < i \<and> i = r)" by arith
      hence "Array.get h' a ! rs \<le> Array.get h' a ! i"
      proof
        assume i_is: "rs < i \<and> i \<le> r - 1"
        with swap_length_remains in_bounds middle_in_bounds rs_equals
        have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
        from part_partitions[OF part] rs_equals right_remains i_is
        have "Array.get h' a ! rs \<le> Array.get h1 a ! i"
          by fastforce
        with i_props h'_def show ?thesis by fastforce
      next
        assume i_is: "rs < i \<and> i = r"
        with rs_equals have "Suc middle \<noteq> r" by arith
        with middle_in_bounds \<open>l < r\<close> have "Suc middle \<le> r - 1" by arith
        with part_partitions[OF part] right_remains
        have "Array.get h' a ! rs \<le> Array.get h1 a ! (Suc middle)"
          by fastforce
        with i_is True rs_equals right_remains h'_def
        show ?thesis using in_bounds
          unfolding Array.update_def Array.length_def
          by auto
      qed
    }
    ultimately show ?thesis by auto
  next
    case False
    with rs_equals have rs_equals: "middle = rs" by simp
    {
      fix i
      assume i_is_left: "l \<le> i \<and> i < rs"
      with swap_length_remains in_bounds middle_in_bounds rs_equals
      have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
      from part_partitions[OF part] rs_equals right_remains i_is_left
      have "Array.get h1 a ! i \<le> Array.get h' a ! rs" by fastforce
      with i_props h'_def have "Array.get h' a ! i \<le> Array.get h' a ! rs"
        unfolding Array.update_def by simp
    }
    moreover
    {
      fix i
      assume "rs < i \<and> i \<le> r"
      hence "(rs < i \<and> i \<le> r - 1) \<or> i = r" by arith
      hence "Array.get h' a ! rs \<le> Array.get h' a ! i"
      proof
        assume i_is: "rs < i \<and> i \<le> r - 1"
        with swap_length_remains in_bounds middle_in_bounds rs_equals
        have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
        from part_partitions[OF part] rs_equals right_remains i_is
        have "Array.get h' a ! rs \<le> Array.get h1 a ! i"
          by fastforce
        with i_props h'_def show ?thesis by fastforce
      next
        assume i_is: "i = r"
        from i_is False rs_equals right_remains h'_def
        show ?thesis using in_bounds
          unfolding Array.update_def Array.length_def
          by auto
      qed
    }
    ultimately
    show ?thesis by auto
  qed
qed

function quicksort :: "'a::{heap,linorder} array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> unit Heap"
where
  "quicksort arr left right =
     (if (right > left)  then
        do {
          pivotNewIndex \<leftarrow> partition arr left right;
          pivotNewIndex \<leftarrow> assert (\<lambda>x. left \<le> x \<and> x \<le> right) pivotNewIndex;
          quicksort arr left (pivotNewIndex - 1);
          quicksort arr (pivotNewIndex + 1) right
        }
     else return ())"
by pat_completeness auto

(* For termination, we must show that the pivotNewIndex is between left and right *)
termination
by (relation "measure (\<lambda>(a, l, r). (r - l))") auto

declare quicksort.simps[simp del]

lemma quicksort_permutes:
  assumes "effect (quicksort a l r) h h' rs"
  shows "mset (Array.get h' a)
  = mset (Array.get h a)"
  using assms
proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
  case (1 a l r h h' rs)
  with partition_permutes show ?case
    unfolding quicksort.simps [of a l r]
    by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto
qed

lemma length_remains:
  assumes "effect (quicksort a l r) h h' rs"
  shows "Array.length h a = Array.length h' a"
using assms
proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
  case (1 a l r h h' rs)
  with partition_length_remains show ?case
    unfolding quicksort.simps [of a l r]
    by (elim effect_ifE effect_bindE effect_assertE effect_returnE) fastforce+
qed

lemma quicksort_outer_remains:
  assumes "effect (quicksort a l r) h h' rs"
   shows "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h (a::'a::{heap,linorder} array) ! i = Array.get h' a ! i"
  using assms
proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
  case (1 a l r h h' rs)
  note cr = \<open>effect (quicksort a l r) h h' rs\<close>
  thus ?case
  proof (cases "r > l")
    case False
    with cr have "h' = h"
      unfolding quicksort.simps [of a l r]
      by (elim effect_ifE effect_returnE) auto
    thus ?thesis by simp
  next
  case True
   {
      fix h1 h2 p ret1 ret2 i
      assume part: "effect (partition a l r) h h1 p"
      assume qs1: "effect (quicksort a l (p - 1)) h1 h2 ret1"
      assume qs2: "effect (quicksort a (p + 1) r) h2 h' ret2"
      assume pivot: "l \<le> p \<and> p \<le> r"
      assume i_outer: "i < l \<or> r < i"
      from  partition_outer_remains [OF part True] i_outer
      have 2: "Array.get h a !i = Array.get h1 a ! i" by fastforce
      moreover
      from 1(1) [OF True pivot qs1] pivot i_outer 2
      have 3: "Array.get h1 a ! i = Array.get h2 a ! i" by auto
      moreover
      from qs2 1(2) [of p h2 h' ret2] True pivot i_outer 3
      have "Array.get h2 a ! i = Array.get h' a ! i" by auto
      ultimately have "Array.get h a ! i= Array.get h' a ! i" by simp
    }
    with cr show ?thesis
      unfolding quicksort.simps [of a l r]
      by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto
  qed
qed

lemma quicksort_is_skip:
  assumes "effect (quicksort a l r) h h' rs"
  shows "r \<le> l \<longrightarrow> h = h'"
  using assms
  unfolding quicksort.simps [of a l r]
  by (elim effect_ifE effect_returnE) auto

lemma quicksort_sorts:
  assumes "effect (quicksort a l r) h h' rs"
  assumes l_r_length: "l < Array.length h a" "r < Array.length h a"
  shows "sorted (subarray l (r + 1) a h')"
  using assms
proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
  case (1 a l r h h' rs)
  note cr = \<open>effect (quicksort a l r) h h' rs\<close>
  thus ?case
  proof (cases "r > l")
    case False
    hence "l \<ge> r + 1 \<or> l = r" by arith
    with length_remains[OF cr] 1(5) show ?thesis
      by (auto simp add: subarray_Nil subarray_single)
  next
    case True
    {
      fix h1 h2 p
      assume part: "effect (partition a l r) h h1 p"
      assume qs1: "effect (quicksort a l (p - 1)) h1 h2 ()"
      assume qs2: "effect (quicksort a (p + 1) r) h2 h' ()"
      from partition_returns_index_in_bounds [OF part True]
      have pivot: "l\<le> p \<and> p \<le> r" .
     note length_remains = length_remains[OF qs2] length_remains[OF qs1] partition_length_remains[OF part]
      from quicksort_outer_remains [OF qs2] quicksort_outer_remains [OF qs1] pivot quicksort_is_skip[OF qs1]
      have pivot_unchanged: "Array.get h1 a ! p = Array.get h' a ! p" by (cases p, auto)
        (*-- First of all, by induction hypothesis both sublists are sorted. *)
      from 1(1)[OF True pivot qs1] length_remains pivot 1(5)
      have IH1: "sorted (subarray l p a h2)"  by (cases p, auto simp add: subarray_Nil)
      from quicksort_outer_remains [OF qs2] length_remains
      have left_subarray_remains: "subarray l p a h2 = subarray l p a h'"
        by (simp add: subarray_eq_samelength_iff)
      with IH1 have IH1': "sorted (subarray l p a h')" by simp
      from 1(2)[OF True pivot qs2] pivot 1(5) length_remains
      have IH2: "sorted (subarray (p + 1) (r + 1) a h')"
        by (cases "Suc p \<le> r", auto simp add: subarray_Nil)
           (* -- Secondly, both sublists remain partitioned. *)
      from partition_partitions[OF part True]
      have part_conds1: "\<forall>j. j \<in> set (subarray l p a h1) \<longrightarrow> j \<le> Array.get h1 a ! p "
        and part_conds2: "\<forall>j. j \<in> set (subarray (p + 1) (r + 1) a h1) \<longrightarrow> Array.get h1 a ! p \<le> j"
        by (auto simp add: all_in_set_subarray_conv)
      from quicksort_outer_remains [OF qs1] quicksort_permutes [OF qs1] True
        length_remains 1(5) pivot mset_nths [of l p "Array.get h1 a" "Array.get h2 a"]
      have multiset_partconds1: "mset (subarray l p a h2) = mset (subarray l p a h1)"
        unfolding Array.length_def subarray_def by (cases p, auto)
      with left_subarray_remains part_conds1 pivot_unchanged
      have part_conds2': "\<forall>j. j \<in> set (subarray l p a h') \<longrightarrow> j \<le> Array.get h' a ! p"
        by (simp, subst set_mset_mset[symmetric], simp)
          (* -- These steps are the analogous for the right sublist \<dots> *)
      from quicksort_outer_remains [OF qs1] length_remains
      have right_subarray_remains: "subarray (p + 1) (r + 1) a h1 = subarray (p + 1) (r + 1) a h2"
        by (auto simp add: subarray_eq_samelength_iff)
      from quicksort_outer_remains [OF qs2] quicksort_permutes [OF qs2] True
        length_remains 1(5) pivot mset_nths [of "p + 1" "r + 1" "Array.get h2 a" "Array.get h' a"]
      have multiset_partconds2: "mset (subarray (p + 1) (r + 1) a h') = mset (subarray (p + 1) (r + 1) a h2)"
        unfolding Array.length_def subarray_def by auto
      with right_subarray_remains part_conds2 pivot_unchanged
      have part_conds1': "\<forall>j. j \<in> set (subarray (p + 1) (r + 1) a h') \<longrightarrow> Array.get h' a ! p \<le> j"
        by (simp, subst set_mset_mset[symmetric], simp)
          (* -- Thirdly and finally, we show that the array is sorted
          following from the facts above. *)
      from True pivot 1(5) length_remains have "subarray l (r + 1) a h' = subarray l p a h' @ [Array.get h' a ! p] @ subarray (p + 1) (r + 1) a h'"
        by (simp add: subarray_nth_array_Cons, cases "l < p") (auto simp add: subarray_append subarray_Nil)
      with IH1' IH2 part_conds1' part_conds2' pivot have ?thesis
        unfolding subarray_def
        apply (auto simp add: sorted_append all_in_set_nths'_conv)
        by (auto simp add: set_nths' dest: order.trans [of _ "Array.get h' a ! p"])
    }
    with True cr show ?thesis
      unfolding quicksort.simps [of a l r]
      by (elim effect_ifE effect_returnE effect_bindE effect_assertE) auto
  qed
qed

lemma quicksort_is_sort:
  assumes effect: "effect (quicksort a 0 (Array.length h a - 1)) h h' rs"
  shows "Array.get h' a = sort (Array.get h a)"
proof (cases "Array.get h a = []")
  case True
  with quicksort_is_skip[OF effect] show ?thesis
  unfolding Array.length_def by simp
next
  case False
  from quicksort_sorts [OF effect] False have "sorted (nths' 0 (List.length (Array.get h a)) (Array.get h' a))"
    unfolding Array.length_def subarray_def by auto
  with length_remains[OF effect] have "sorted (Array.get h' a)"
    unfolding Array.length_def by simp
  with quicksort_permutes [OF effect] properties_for_sort show ?thesis by fastforce
qed

subsection \<open>No Errors in quicksort\<close>
text \<open>We have proved that quicksort sorts (if no exceptions occur).
We will now show that exceptions do not occur.\<close>

lemma success_part1I:
  assumes "l < Array.length h a" "r < Array.length h a"
  shows "success (part1 a l r p) h"
  using assms
proof (induct a l r p arbitrary: h rule: part1.induct)
  case (1 a l r p)
  thus ?case unfolding part1.simps [of a l r]
  apply (auto intro!: success_intros simp add: not_le)
  apply (auto intro!: effect_intros)
  done
qed

lemma success_bindI' [success_intros]: (*FIXME move*)
  assumes "success f h"
  assumes "\<And>h' r. effect f h h' r \<Longrightarrow> success (g r) h'"
  shows "success (f \<bind> g) h"
using assms(1) proof (rule success_effectE)
  fix h' r
  assume *: "effect f h h' r"
  with assms(2) have "success (g r) h'" .
  with * show "success (f \<bind> g) h" by (rule success_bind_effectI)
qed

lemma success_partitionI:
  assumes "l < r" "l < Array.length h a" "r < Array.length h a"
  shows "success (partition a l r) h"
using assms unfolding partition.simps swap_def
apply (auto intro!: success_bindI' success_ifI success_returnI success_nthI success_updI success_part1I elim!: effect_bindE effect_updE effect_nthE effect_returnE simp add:)
apply (frule part_length_remains)
apply (frule part_returns_index_in_bounds)
apply auto
apply (frule part_length_remains)
apply (frule part_returns_index_in_bounds)
apply auto
apply (frule part_length_remains)
apply auto
done

lemma success_quicksortI:
  assumes "l < Array.length h a" "r < Array.length h a"
  shows "success (quicksort a l r) h"
using assms
proof (induct a l r arbitrary: h rule: quicksort.induct)
  case (1 a l ri h)
  thus ?case
    unfolding quicksort.simps [of a l ri]
    apply (auto intro!: success_ifI success_bindI' success_returnI success_nthI success_updI success_assertI success_partitionI)
    apply (frule partition_returns_index_in_bounds)
    apply auto
    apply (frule partition_returns_index_in_bounds)
    apply auto
    apply (auto elim!: effect_assertE dest!: partition_length_remains length_remains)
    apply (subgoal_tac "Suc r \<le> ri \<or> r = ri")
    apply (erule disjE)
    apply auto
    unfolding quicksort.simps [of a "Suc ri" ri]
    apply (auto intro!: success_ifI success_returnI)
    done
qed

subsection \<open>Example\<close>

definition "qsort a = do {
    k \<leftarrow> Array.len a;
    quicksort a 0 (k - 1);
    return a
  }"

code_reserved SML upto

definition "example = do {
    a \<leftarrow> Array.of_list ([42, 2, 3, 5, 0, 1705, 8, 3, 15] :: nat list);
    qsort a
  }"

ML_val \<open>@{code example} ()\<close>

export_code qsort checking SML SML_imp OCaml? OCaml_imp? Haskell? Scala Scala_imp

end


theory Transfer_Extras
  imports Main
begin

lemma rtranclp_complete_run_right_unique:
  fixes R :: "'a \<Rightarrow> 'a \<Rightarrow> bool" and x y z :: 'a
  assumes "right_unique R"
  shows "R\<^sup>*\<^sup>* x y \<Longrightarrow> (\<nexists>w. R y w) \<Longrightarrow> R\<^sup>*\<^sup>* x z \<Longrightarrow> (\<nexists>w. R z w) \<Longrightarrow> y = z"
proof (induction x arbitrary: z rule: converse_rtranclp_induct)
  case base
  then show ?case
    by (auto elim: converse_rtranclpE)
next
  case (step x w)
  hence "R\<^sup>*\<^sup>* w z"
    using right_uniqueD[OF \<open>right_unique R\<close>]
    by (metis converse_rtranclpE)
  with step show ?case
    by simp
qed

lemma tranclp_complete_run_right_unique:
  fixes R :: "'a \<Rightarrow> 'a \<Rightarrow> bool" and x y z :: 'a
  assumes "right_unique R"
  shows "R\<^sup>+\<^sup>+ x y \<Longrightarrow> (\<nexists>w. R y w) \<Longrightarrow> R\<^sup>+\<^sup>+ x z \<Longrightarrow> (\<nexists>w. R z w) \<Longrightarrow> y = z"
  using right_uniqueD[OF \<open>right_unique R\<close>, of x]
  by (auto dest!: tranclpD intro!: rtranclp_complete_run_right_unique[OF \<open>right_unique R\<close>, of _ y z])

end


(*
   Title: The Calculus of Communicating Systems
   Author/Maintainer: Jesper Bengtson (jebe@itu.dk), 2012
*)
theory Struct_Cong
  imports Agent
begin

inductive structCong :: "ccs \<Rightarrow> ccs \<Rightarrow> bool" ("_ \<equiv>\<^sub>s _")
  where
  Refl: "P \<equiv>\<^sub>s P"
| Sym: "P \<equiv>\<^sub>s Q \<Longrightarrow> Q \<equiv>\<^sub>s P"
| Trans: "\<lbrakk>P \<equiv>\<^sub>s Q; Q \<equiv>\<^sub>s R\<rbrakk> \<Longrightarrow> P \<equiv>\<^sub>s R"

| ParComm: "P \<parallel> Q \<equiv>\<^sub>s Q \<parallel> P"
| ParAssoc: "(P \<parallel> Q) \<parallel> R \<equiv>\<^sub>s P \<parallel> (Q \<parallel> R)"
| ParId: "P \<parallel> \<zero> \<equiv>\<^sub>s P"

| SumComm: "P \<oplus> Q \<equiv>\<^sub>s Q \<oplus> P"
| SumAssoc: "(P \<oplus> Q) \<oplus> R \<equiv>\<^sub>s P \<oplus> (Q \<oplus> R)"
| SumId: "P \<oplus> \<zero> \<equiv>\<^sub>s P"

| ResNil: "\<lparr>\<nu>x\<rparr>\<zero> \<equiv>\<^sub>s \<zero>"
| ScopeExtPar: "x \<sharp> P \<Longrightarrow> \<lparr>\<nu>x\<rparr>(P \<parallel> Q) \<equiv>\<^sub>s P \<parallel> \<lparr>\<nu>x\<rparr>Q"
| ScopeExtSum: "x \<sharp> P \<Longrightarrow> \<lparr>\<nu>x\<rparr>(P \<oplus> Q) \<equiv>\<^sub>s P \<oplus> \<lparr>\<nu>x\<rparr>Q"
| ScopeAct: "x \<sharp> \<alpha> \<Longrightarrow> \<lparr>\<nu>x\<rparr>(\<alpha>.(P)) \<equiv>\<^sub>s \<alpha>.(\<lparr>\<nu>x\<rparr>P)"
| ScopeCommAux: "x \<noteq> y \<Longrightarrow> \<lparr>\<nu>x\<rparr>(\<lparr>\<nu>y\<rparr>P) \<equiv>\<^sub>s \<lparr>\<nu>y\<rparr>(\<lparr>\<nu>x\<rparr>P)"

| BangUnfold: "!P \<equiv>\<^sub>s P \<parallel> !P"
equivariance structCong
nominal_inductive structCong
by(auto simp add: abs_fresh)

lemma ScopeComm:
  fixes x :: name
  and   y :: name
  and   P :: ccs

  shows "\<lparr>\<nu>x\<rparr>(\<lparr>\<nu>y\<rparr>P) \<equiv>\<^sub>s \<lparr>\<nu>y\<rparr>(\<lparr>\<nu>x\<rparr>P)"
by(cases "x=y") (auto intro: Refl ScopeCommAux)

end


section \<open> Relational Operational Semantics \<close>

theory utp_rel_opsem
  imports
    utp_rel_laws
    utp_hoare
begin

text \<open> This theory uses the laws of relational calculus to create a basic operational semantics.
  It is based on Chapter 10 of the UTP book~\cite{Hoare&98}. \<close>

fun trel :: "'\<alpha> usubst \<times> '\<alpha> hrel \<Rightarrow> '\<alpha> usubst \<times> '\<alpha> hrel \<Rightarrow> bool" (infix "\<rightarrow>\<^sub>u" 85) where
"(\<sigma>, P) \<rightarrow>\<^sub>u (\<rho>, Q) \<longleftrightarrow> (\<langle>\<sigma>\<rangle>\<^sub>a ;; P) \<sqsubseteq> (\<langle>\<rho>\<rangle>\<^sub>a ;; Q)"

lemma trans_trel:
  "\<lbrakk> (\<sigma>, P) \<rightarrow>\<^sub>u (\<rho>, Q); (\<rho>, Q) \<rightarrow>\<^sub>u (\<phi>, R) \<rbrakk> \<Longrightarrow> (\<sigma>, P) \<rightarrow>\<^sub>u (\<phi>, R)"
  by auto

lemma skip_trel: "(\<sigma>, II) \<rightarrow>\<^sub>u (\<sigma>, II)"
  by simp

lemma assigns_trel: "(\<sigma>, \<langle>\<rho>\<rangle>\<^sub>a) \<rightarrow>\<^sub>u (\<rho> \<circ> \<sigma>, II)"
  by (simp add: assigns_comp)

lemma assign_trel:
  "(\<sigma>, x := v) \<rightarrow>\<^sub>u (\<sigma>(&x \<mapsto>\<^sub>s \<sigma> \<dagger> v), II)"
  by (simp add: assigns_comp usubst)

lemma seq_trel:
  assumes "(\<sigma>, P) \<rightarrow>\<^sub>u (\<rho>, Q)"
  shows "(\<sigma>, P ;; R) \<rightarrow>\<^sub>u (\<rho>, Q ;; R)"
  by (metis (no_types, lifting) assms order_refl seqr_assoc seqr_mono trel.simps)

lemma seq_skip_trel:
  "(\<sigma>, II ;; P) \<rightarrow>\<^sub>u (\<sigma>, P)"
  by simp

lemma nondet_left_trel:
  "(\<sigma>, P \<sqinter> Q) \<rightarrow>\<^sub>u (\<sigma>, P)"
  by (metis (no_types, hide_lams) disj_comm disj_upred_def semilattice_sup_class.sup.absorb_iff1 semilattice_sup_class.sup.left_idem seqr_or_distr trel.simps)

lemma nondet_right_trel:
  "(\<sigma>, P \<sqinter> Q) \<rightarrow>\<^sub>u (\<sigma>, Q)"
  by (simp add: seqr_mono)

lemma rcond_true_trel:
  assumes "\<sigma> \<dagger> b = true"
  shows "(\<sigma>, P \<triangleleft> b \<triangleright>\<^sub>r Q) \<rightarrow>\<^sub>u (\<sigma>, P)"
  using assms
  by (simp add: assigns_r_comp usubst alpha cond_unit_T)

lemma rcond_false_trel:
  assumes "\<sigma> \<dagger> b = false"
  shows "(\<sigma>, P \<triangleleft> b \<triangleright>\<^sub>r Q) \<rightarrow>\<^sub>u (\<sigma>, Q)"
  using assms
  by (simp add: assigns_r_comp usubst alpha cond_unit_F)

lemma while_true_trel:
  assumes "\<sigma> \<dagger> b = true"
  shows "(\<sigma>, while b do P od) \<rightarrow>\<^sub>u (\<sigma>, P ;; while b do P od)"
  by (metis assms rcond_true_trel while_unfold)

lemma while_false_trel:
  assumes "\<sigma> \<dagger> b = false"
  shows "(\<sigma>, while b do P od) \<rightarrow>\<^sub>u (\<sigma>, II)"
  by (metis assms rcond_false_trel while_unfold)

text \<open> Theorem linking Hoare calculus and operational semantics. If we start $Q$ in a state $\sigma_0$
  satisfying $p$, and $Q$ reaches final state $\sigma_1$ then $r$ holds in this final state. \<close>

theorem hoare_opsem_link:
  "\<lbrace>p\<rbrace>Q\<lbrace>r\<rbrace>\<^sub>u = (\<forall> \<sigma>\<^sub>0 \<sigma>\<^sub>1. `\<sigma>\<^sub>0 \<dagger> p` \<and> (\<sigma>\<^sub>0, Q) \<rightarrow>\<^sub>u (\<sigma>\<^sub>1, II) \<longrightarrow> `\<sigma>\<^sub>1 \<dagger> r`)"
  apply (rel_auto)
  apply (rename_tac a b)
  apply (drule_tac x="\<lambda> _. a" in spec, simp)
  apply (drule_tac x="\<lambda> _. b" in spec, simp)
  done

declare trel.simps [simp del]

end


theory Desargues_3D
  imports Main Higher_Projective_Space_Rank_Axioms Matroid_Rank_Properties
begin

(* Author: Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk .*)

text \<open>
Contents:
\<^item> We prove Desargues's theorem: if two triangles ABC and A'B'C' are perspective from a point P (ie.
the lines AA', BB' and CC' are concurrent in P), then they are perspective from a line (ie. the points
\<open>\<alpha> = BC \<inter> B'C'\<close>, \<open>\<beta> = AC \<inter> A'C'\<close> and \<open>\<gamma> = AB \<inter> A'B'\<close> are collinear).
In this file we restrict ourself to the case where the two triangles ABC and A'B'C' are not coplanar.
\<close>

section \<open>Desargues's Theorem: The Non-coplanar Case\<close>

definition desargues_config_3D ::
  "[Points, Points, Points, Points, Points, Points, Points, Points, Points, Points] => bool"
  where "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma> \<equiv> rk {A, B, C} = 3 \<and> rk {A', B', C'} = 3 \<and>
rk {A, A', P} = 2 \<and> rk {B, B', P} = 2 \<and> rk {C, C', P} = 2 \<and> rk {A, B, C, A', B', C'} \<ge> 4 \<and>
rk {B, C, \<alpha>} = 2 \<and> rk {B', C', \<alpha>} = 2 \<and> rk {A, C, \<beta>} = 2 \<and> rk {A', C', \<beta>} = 2 \<and> rk {A, B, \<gamma>} = 2 \<and>
rk {A', B', \<gamma>} = 2"

lemma coplanar_4 :
  assumes "rk {A, B, C} = 3" and "rk {B, C, \<alpha>} = 2"
  shows "rk {A, B, C, \<alpha>} = 3"
proof-
  have f1:"rk {A, B, C, \<alpha>} \<ge> 3"
    using matroid_ax_2
    by (metis assms(1) empty_subsetI insert_mono)
  have "rk {A, B, C, \<alpha>} + rk {B, C} \<le> rk {A, B, C} + rk {B, C, \<alpha>}"
    using matroid_ax_3_alt
    by (metis Un_insert_right add_One_commute add_mono assms(1) assms(2) matroid_ax_2_alt
        nat_1_add_1 numeral_plus_one rk_singleton semiring_norm(3) sup_bot.right_neutral)
  then have f2:"rk {A, B, C, \<alpha>} \<le> 3"
    by (metis Un_insert_right add_One_commute assms(2) matroid_ax_2_alt numeral_plus_one
        semiring_norm(3) sup_bot.right_neutral)
  from f1 and f2 show "rk {A, B, C, \<alpha>} = 3"
    by auto
qed

lemma desargues_config_3D_coplanar_4 :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {A, B, C, \<alpha>} = 3" and "rk {A', B', C', \<alpha>} = 3"
proof-
  show "rk {A, B, C, \<alpha>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_4
    by blast
  show "rk {A', B', C', \<alpha>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_4
    by blast
qed

lemma coplanar_4_bis :
  assumes "rk {A, B, C} = 3" and "rk {A, C, \<beta>} = 2"
  shows "rk {A, B, C, \<beta>} = 3"
  by (smt assms(1) assms(2) coplanar_4 insert_commute)

lemma desargues_config_3D_coplanar_4_bis :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {A, B, C, \<beta>} = 3" and "rk {A', B', C', \<beta>} = 3"
proof-
  show "rk {A, B, C, \<beta>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_4_bis
    by auto
  show "rk {A', B', C', \<beta>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_4_bis
    by auto
qed

lemma coplanar_4_ter :
  assumes "rk {A, B, C} = 3" and "rk {A, B, \<gamma>} = 2"
  shows "rk {A, B, C, \<gamma>} = 3"
  by (smt assms(1) assms(2) coplanar_4 insert_commute)

lemma desargues_config_3D_coplanar_4_ter :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {A, B, C, \<gamma>} = 3" and "rk {A', B', C', \<gamma>} = 3"
proof-
  show "rk {A, B, C, \<gamma>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_4_ter
    by auto
  show "rk {A', B', C', \<gamma>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_4_ter
    by auto
qed

lemma coplanar_5 :
  assumes "rk {A, B, C} = 3" and "rk {B, C, \<alpha>} = 2" and "rk {A, C, \<beta>} = 2"
  shows "rk {A, B, C, \<alpha>, \<beta>} = 3"
proof-
  have f1:"rk {A, B, C, \<alpha>} = 3"
    using coplanar_4
    by (smt One_nat_def Un_assoc Un_commute add.commute add_Suc_right assms(1) assms(2) insert_is_Un
        le_antisym matroid_ax_2_alt numeral_2_eq_2 numeral_3_eq_3 one_add_one)
  have f2:"rk {A, B, C, \<beta>} = 3"
    using coplanar_4_bis
    by (smt One_nat_def Un_assoc Un_commute add.commute add_Suc_right assms(1) assms(3) insert_is_Un
        le_antisym matroid_ax_2_alt numeral_2_eq_2 numeral_3_eq_3 one_add_one)
  from f1 and f2 show "rk {A, B, C, \<alpha>, \<beta>} = 3"
    using matroid_ax_3_alt'
    by (metis Un_assoc assms(1) insert_is_Un)
qed

lemma desargues_config_3D_coplanar_5 :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {A, B, C, \<alpha>, \<beta>} = 3" and "rk {A', B', C', \<alpha>, \<beta>} = 3"
proof-
  show "rk {A, B, C, \<alpha>, \<beta>} = 3"
    using assms desargues_config_3D_def coplanar_5
    by auto
  show "rk {A', B', C', \<alpha>, \<beta>} = 3"
    using assms desargues_config_3D_def coplanar_5
    by auto
qed

lemma coplanar_5_bis :
  assumes "rk {A, B, C} = 3" and "rk {B, C, \<alpha>} = 2" and "rk {A, B, \<gamma>} = 2"
  shows "rk {A, B, C, \<alpha>, \<gamma>} = 3"
  by (smt assms coplanar_5 insert_commute)

lemma desargues_config_3D_coplanar_5_bis :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {A, B, C, \<alpha>, \<gamma>} = 3" and "rk {A', B', C', \<alpha>, \<gamma>} = 3"
proof-
  show "rk {A, B, C, \<alpha>, \<gamma>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_5_bis
    by auto
  show "rk {A', B', C', \<alpha>, \<gamma>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_5_bis
    by auto
qed

lemma coplanar_6 :
  assumes "rk {A, B, C} = 3" and "rk {B, C, \<alpha>} = 2" and "rk {A, B, \<gamma>} = 2" and "rk {A, C, \<beta>} = 2"
  shows "rk {A, B, C, \<alpha>, \<beta>, \<gamma>} = 3"
proof-
  have f1:"rk {A, B, C, \<alpha>, \<gamma>} = 3"
    using coplanar_5_bis assms(1) assms(2) assms(3)
    by auto
  have f2:"rk {A, B, C, \<alpha>, \<beta>} = 3"
    using coplanar_5 assms(1) assms(2) assms(4)
    by auto
  have f3:"rk {A, B, C, \<alpha>} = 3"
    using coplanar_4 assms(1) assms(2)
    by auto
  from f1 and f2 and f3 show "rk {A, B, C, \<alpha>, \<beta>, \<gamma>} = 3"
    using matroid_ax_3_alt'[of "{A, B, C, \<alpha>}" "\<beta>" "\<gamma>"]
    by (metis Un_insert_left sup_bot.left_neutral)
qed

lemma desargues_config_3D_coplanar_6 :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {A, B, C, \<alpha>, \<beta>, \<gamma>} = 3" and "rk {A', B', C', \<alpha>, \<beta>, \<gamma>} = 3"
proof-
  show "rk {A, B, C, \<alpha>, \<beta>, \<gamma>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_6
    by auto
  show "rk {A', B', C', \<alpha>, \<beta>, \<gamma>} = 3"
    using assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>] coplanar_6
    by auto
qed

lemma desargues_config_3D_non_coplanar :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {A, B, C, A', B', C', \<alpha>, \<beta>, \<gamma>} \<ge> 4"
proof-
  have "rk {A, B, C, A', B', C'} \<le> rk {A, B, C, A', B', C', \<alpha>, \<beta>, \<gamma>}"
    using matroid_ax_2
    by auto
  thus "4 \<le> rk {A, B, C, A', B', C', \<alpha>, \<beta>, \<gamma>}"
    using matroid_ax_2 assms desargues_config_3D_def[of A B C A' B' C' P \<alpha> \<beta> \<gamma>]
    by linarith
qed

theorem desargues_3D :
  assumes "desargues_config_3D A B C A' B' C' P \<alpha> \<beta> \<gamma>"
  shows "rk {\<alpha>, \<beta>, \<gamma>} \<le> 2"
proof-
  have "rk {A, B, C, A', B', C', \<alpha>, \<beta>, \<gamma>} + rk {\<alpha>, \<beta>, \<gamma>} \<le> rk {A, B, C, \<alpha>, \<beta>, \<gamma>} + rk {A', B', C', \<alpha>, \<beta>, \<gamma>}"
    using matroid_ax_3_alt[of "{\<alpha>, \<beta>, \<gamma>}" "{A, B, C, \<alpha>, \<beta>, \<gamma>}" "{A', B', C', \<alpha>, \<beta>, \<gamma>}"]
    by (simp add: insert_commute)
  then have "rk {\<alpha>, \<beta>, \<gamma>} \<le> rk {A, B, C, \<alpha>, \<beta>, \<gamma>} + rk {A', B', C', \<alpha>, \<beta>, \<gamma>} - rk {A, B, C, A', B', C', \<alpha>, \<beta>, \<gamma>}"
    by linarith
  thus "rk {\<alpha>, \<beta>, \<gamma>} \<le> 2"
    using assms desargues_config_3D_coplanar_6 desargues_config_3D_non_coplanar
    by fastforce
qed

end


(*  Title:       Verification components with Kleene Algebras
    Author:      Jonathan Julián Huerta y Munive, 2020
    Maintainer:  Jonathan Julián Huerta y Munive <jonjulian23@gmail.com>
*)

section \<open> Verification components with KAT  \<close>

text \<open> We use Kleene algebras with tests to derive rules for verification condition generation and
refinement laws. \<close>

theory HS_VC_KAT
  imports KAT_and_DRA.PHL_KAT

begin

subsection \<open> Hoare logic in KAT \<close>

text \<open> Here we derive the rules of Hoare Logic. \<close>

notation t ("\<tt>\<tt>")

hide_const t

no_notation if_then_else ("if _ then _ else _ fi" [64,64,64] 63)
        and HOL.If ("(if (_)/ then (_)/ else (_))" [0, 0, 10] 10)
        and while ("while _ do _ od" [64,64] 63)

context kat (* mostly by Victor Gomes, Georg Struth *)
begin

\<comment> \<open> Definitions of Hoare Triple \<close>

definition Hoare :: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" ("H") where
  "H p x q \<longleftrightarrow> \<tt>\<tt> p \<cdot> x \<le> x \<cdot> \<tt>\<tt> q"

lemma H_consl: "\<tt>\<tt> p \<le> \<tt>\<tt> p' \<Longrightarrow> H p' x q \<Longrightarrow> H p x q"
  using Hoare_def phl_cons1 by blast

lemma H_consr: "\<tt>\<tt> q' \<le> \<tt>\<tt> q \<Longrightarrow> H p x q' \<Longrightarrow> H p x q"
  using Hoare_def phl_cons2 by blast

lemma H_cons: "\<tt>\<tt> p \<le> \<tt>\<tt> p' \<Longrightarrow> \<tt>\<tt> q' \<le> \<tt>\<tt> q \<Longrightarrow> H p' x q' \<Longrightarrow> H p x q"
  by (simp add: H_consl H_consr)

\<comment> \<open> Skip \<close>

lemma H_skip:  "H p 1 p"
  by (simp add: Hoare_def)

\<comment> \<open> Abort \<close>

lemma H_abort: "H p 0 q"
  by (simp add: Hoare_def)

\<comment> \<open> Sequential composition \<close>

lemma H_seq: "H p x r \<Longrightarrow> H r y q \<Longrightarrow> H p (x \<cdot> y) q"
  by (simp add: Hoare_def phl_seq)

\<comment> \<open> Nondeterministic choice \<close>

lemma H_choice: "H p x q \<Longrightarrow> H p y q \<Longrightarrow> H p (x + y) q"
  using local.distrib_left local.join.sup.mono by (auto simp: Hoare_def)

\<comment> \<open> Conditional statement \<close>

definition kat_cond :: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a" ("if _ then _ else _" [64,64,64] 63) where
  "if p then x else y = (\<tt>\<tt> p \<cdot> x + n p \<cdot> y)"

lemma H_var: "H p x q \<longleftrightarrow> \<tt>\<tt> p \<cdot> x \<cdot> n q = 0"
  by (metis Hoare_def n_kat_3 t_n_closed)

lemma H_cond_iff: "H p (if r then x else y) q \<longleftrightarrow> H (\<tt>\<tt> p \<cdot> \<tt>\<tt> r) x q \<and> H (\<tt>\<tt> p \<cdot> n r) y q"
proof -
  have "H p (if r then x else y) q \<longleftrightarrow> \<tt>\<tt> p \<cdot> (\<tt>\<tt> r \<cdot> x + n r \<cdot> y) \<cdot> n q = 0"
    by (simp add: H_var kat_cond_def)
  also have "... \<longleftrightarrow> \<tt>\<tt> p \<cdot> \<tt>\<tt> r \<cdot> x \<cdot> n q + \<tt>\<tt> p \<cdot> n r \<cdot> y \<cdot> n q = 0"
    by (simp add: distrib_left mult_assoc)
  also have "... \<longleftrightarrow> \<tt>\<tt> p \<cdot> \<tt>\<tt> r \<cdot> x \<cdot> n q = 0 \<and> \<tt>\<tt> p \<cdot> n r \<cdot> y \<cdot> n q = 0"
    by (metis add_0_left no_trivial_inverse)
  finally show ?thesis
    by (metis H_var test_mult)
qed

lemma H_cond: "H (\<tt>\<tt> p \<cdot> \<tt>\<tt> r) x q \<Longrightarrow> H (\<tt>\<tt> p \<cdot> n r) y q \<Longrightarrow> H p (if r then x else y) q"
  by (simp add: H_cond_iff)

\<comment> \<open> While loop \<close>

definition kat_while :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" ("while _ do _" [64,64] 63) where
  "while b do x = (\<tt>\<tt> b \<cdot> x)\<^sup>\<star> \<cdot> n b"

definition kat_while_inv :: "'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a" ("while _ inv _ do _" [64,64,64] 63) where
  "while p inv i do x = while p do x"

lemma H_exp1: "H (\<tt>\<tt> p \<cdot> \<tt>\<tt> r) x q \<Longrightarrow> H p (\<tt>\<tt> r \<cdot> x) q"
  using Hoare_def n_de_morgan_var2 phl.ht_at_phl_export1 by auto

lemma H_while: "H (\<tt>\<tt> p \<cdot> \<tt>\<tt> r) x p \<Longrightarrow> H p (while r do x) (\<tt>\<tt> p \<cdot> n r)"
proof -
  assume a1: "H (\<tt>\<tt> p \<cdot> \<tt>\<tt> r) x p"
  have "\<tt>\<tt> (\<tt>\<tt> p \<cdot> n r) = n r \<cdot> \<tt>\<tt> p \<cdot> n r"
    using n_preserve test_mult by presburger
  then show ?thesis
    using a1 Hoare_def H_exp1 conway.phl.it_simr phl_export2 kat_while_def by auto
qed

lemma H_while_inv: "\<tt>\<tt> p \<le> \<tt>\<tt> i \<Longrightarrow> \<tt>\<tt> i \<cdot> n r \<le> \<tt>\<tt> q \<Longrightarrow> H (\<tt>\<tt> i \<cdot> \<tt>\<tt> r) x i \<Longrightarrow> H p (while r inv i do x) q"
  by (metis H_cons H_while test_mult kat_while_inv_def)

\<comment> \<open> Finite iteration \<close>

lemma H_star: "H i x i \<Longrightarrow> H i (x\<^sup>\<star>) i"
  unfolding Hoare_def using star_sim2 by blast

lemma H_star_inv:
  assumes "\<tt>\<tt> p \<le> \<tt>\<tt> i" and "H i x i" and "(\<tt>\<tt> i) \<le> (\<tt>\<tt> q)"
  shows "H p (x\<^sup>\<star>) q"
proof-
  have "H i (x\<^sup>\<star>) i"
    using assms(2) H_star by blast
  hence "H p (x\<^sup>\<star>) i"
    unfolding Hoare_def using assms(1) phl_cons1 by blast
  thus ?thesis
    unfolding Hoare_def using assms(3) phl_cons2 by blast
qed

definition kat_loop_inv :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" ("loop _ inv _ " [64,64] 63)
  where "loop x inv i = x\<^sup>\<star>"

lemma H_loop: "H p x p \<Longrightarrow> H p (loop x inv i) p"
  unfolding kat_loop_inv_def by (rule H_star)

lemma H_loop_inv: "\<tt>\<tt> p \<le> \<tt>\<tt> i \<Longrightarrow> H i x i \<Longrightarrow> \<tt>\<tt> i \<le> \<tt>\<tt> q \<Longrightarrow> H p (loop x inv i) q"
  unfolding kat_loop_inv_def using H_star_inv by blast

\<comment> \<open> Invariants \<close>

lemma H_inv: "\<tt>\<tt> p \<le> \<tt>\<tt> i \<Longrightarrow> \<tt>\<tt> i \<le> \<tt>\<tt> q \<Longrightarrow> H i x i \<Longrightarrow> H p x q"
  by (rule_tac p'=i and q'=i in H_cons)

lemma H_inv_plus: "\<tt>\<tt> i = i \<Longrightarrow> \<tt>\<tt> j = j \<Longrightarrow> H i x i \<Longrightarrow>  H j x j \<Longrightarrow>  H (i + j) x (i + j)"
  unfolding Hoare_def using combine_common_factor
  by (smt add_commute add.left_commute distrib_left join.sup.absorb_iff1 t_add_closed)

lemma H_inv_mult: "\<tt>\<tt> i = i \<Longrightarrow> \<tt>\<tt> j = j \<Longrightarrow> H i x i \<Longrightarrow>  H j x j \<Longrightarrow>  H (i \<cdot> j) x (i \<cdot> j)"
  unfolding Hoare_def by (smt n_kat_2 n_mult_comm t_mult_closure mult_assoc)

end

subsection \<open> refinement KAT \<close>

text \<open> Here we derive the laws of the refinement calculus. \<close>

class rkat = kat +
  fixes Ref :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"
  assumes spec_def:  "x \<le> Ref p q \<longleftrightarrow> H p x q"

begin (* mostly by Victor Gomes, Georg Struth *)

lemma R1: "H p (Ref p q) q"
  using spec_def by blast

lemma R2: "H p x q \<Longrightarrow> x \<le> Ref p q"
  by (simp add: spec_def)

lemma R_cons: "\<tt>\<tt> p \<le> \<tt>\<tt> p' \<Longrightarrow> \<tt>\<tt> q' \<le> \<tt>\<tt> q \<Longrightarrow> Ref p' q' \<le> Ref p q"
proof -
  assume h1: "\<tt>\<tt> p \<le> \<tt>\<tt> p'" and h2: "\<tt>\<tt> q' \<le> \<tt>\<tt> q"
  have "H p' (Ref p' q') q'"
    by (simp add: R1)
  hence "H p (Ref p' q') q"
    using h1 h2 H_consl H_consr by blast
  thus ?thesis
    by (rule R2)
qed

\<comment> \<open> Skip \<close>

lemma R_skip: "1 \<le> Ref p p"
proof -
  have "H p 1 p"
    by (simp add: H_skip)
  thus ?thesis
    by (rule R2)
qed

\<comment> \<open> Abort \<close>

lemma R_zero_one: "x \<le> Ref 0 1"
proof -
  have "H 0 x 1"
    by (simp add: Hoare_def)
  thus ?thesis
    by (rule R2)
qed

lemma R_one_zero: "Ref 1 0 = 0"
proof -
  have "H 1 (Ref 1 0) 0"
    by (simp add: R1)
  thus ?thesis
    by (simp add: Hoare_def join.le_bot)
qed

lemma R_abort: "0 \<le> Ref p q"
  using bot_least by force

\<comment> \<open> Sequential composition \<close>

lemma R_seq: "(Ref p r) \<cdot> (Ref r q) \<le> Ref p q"
proof -
  have "H p (Ref p r) r" and "H r (Ref r q) q"
    by (simp add: R1)+
  hence "H p ((Ref p r) \<cdot> (Ref r q)) q"
    by (rule H_seq)
  thus ?thesis
    by (rule R2)
qed

\<comment> \<open> Nondeterministic choice \<close>

lemma R_choice: "(Ref p q) + (Ref p q) \<le> Ref p q"
  unfolding spec_def by (rule H_choice) (rule R1)+

\<comment> \<open> Conditional statement \<close>

lemma R_cond: "if v then (Ref (\<tt>\<tt> v \<cdot> \<tt>\<tt> p) q) else (Ref (n v \<cdot> \<tt>\<tt> p) q) \<le> Ref p q"
proof -
  have "H (\<tt>\<tt> v \<cdot> \<tt>\<tt> p) (Ref (\<tt>\<tt> v \<cdot> \<tt>\<tt> p) q) q" and "H (n v \<cdot> \<tt>\<tt> p) (Ref (n v \<cdot> \<tt>\<tt> p) q) q"
    by (simp add: R1)+
  hence "H p (if v then (Ref (\<tt>\<tt> v \<cdot> \<tt>\<tt> p) q) else (Ref (n v \<cdot> \<tt>\<tt> p) q)) q"
    by (simp add: H_cond n_mult_comm)
 thus ?thesis
    by (rule R2)
qed

\<comment> \<open> While loop \<close>

lemma R_while: "while q do (Ref (\<tt>\<tt> p \<cdot> \<tt>\<tt> q) p) \<le> Ref p (\<tt>\<tt> p \<cdot> n q)"
proof -
  have "H (\<tt>\<tt> p \<cdot> \<tt>\<tt> q) (Ref (\<tt>\<tt> p \<cdot> \<tt>\<tt> q) p)  p"
    by (simp_all add: R1)
  hence "H p (while q do (Ref (\<tt>\<tt> p \<cdot> \<tt>\<tt> q) p)) (\<tt>\<tt> p \<cdot> n q)"
    by (simp add: H_while)
  thus ?thesis
    by (rule R2)
qed

\<comment> \<open> Finite iteration \<close>

lemma R_star: "(Ref i i)\<^sup>\<star> \<le> Ref i i"
proof -
  have "H i (Ref i i) i"
    using R1 by blast
  hence "H i ((Ref i i)\<^sup>\<star>) i"
    using H_star by blast
  thus "Ref i i\<^sup>\<star> \<le> Ref i i"
    by (rule R2)
qed

lemma R_loop: "loop (Ref p p) inv i \<le> Ref p p"
  unfolding kat_loop_inv_def by (rule R_star)

\<comment> \<open> Invariants \<close>

lemma R_inv: "\<tt>\<tt> p \<le> \<tt>\<tt> i \<Longrightarrow> \<tt>\<tt> i \<le> \<tt>\<tt> q \<Longrightarrow> Ref i i \<le> Ref p q"
  using R_cons by force

end

end