import .lemmas
import .spec

import data.set.basic

import util.data.minimum
import util.data.ordering
import util.data.order
import util.function
import util.logic
import tactic.norm_num

open temporal function predicate nat set

local infix ` ≃ `:75 := v_eq
local prefix `♯ `:0 := cast (by simp)
universes u v

namespace temporal
namespace scheduling
section scheduling

local attribute [instance, priority 0] classical.prop_decidable
local attribute [-simp] add_comm

parameter {evt : Type u}
parameter Γ : cpred
parameter r : tvar (set evt)
parameter Hr : Γ ⊢ ◻-(r ≃ (∅ : set evt))
-- parameter [nonempty evt]

abbreviation SCHED  (s : tvar evt) :=
◻(s ∊ r) ⋀
∀∀ (e : evt),
  ◻◇(↑e ∊ r) ⟶
  ◻◇(s ≃ ↑e ⋀ ↑e ∊ r)

section implementation

parameters (f : ℕ → evt) (Hinj : surjective f)
parameter p : tvar (ℕ → evt)
parameter cur : tvar ℕ
/- consider making select into a state variable instead of a definition -/
variable select : tvar evt

infixl ` |+| `:80 := lifted₂ has_add.add
infixl ` |-| `:80 := lifted₂ has_sub.sub

noncomputable def next_p (p : ℕ → evt) (r' : set evt) (i : ℕ) : ordering → evt
 | ordering.gt := p i
 | ordering.eq := p (↓ i : ℕ, p i ∈ r')
 | ordering.lt :=
   if (↓ i : ℕ, p i ∈ r') ≤ i
          then p (i + 1)
          else p i

noncomputable def next' (r' : set evt) : ℕ × (ℕ → evt) → ℕ × (ℕ → evt)
 | (cur,p) :=
let min := ↓ i : ℕ, p i ∈ r',
    cur' := max min $ cur+1,
    p' : ℕ → evt := λ i : ℕ,
          next_p p r' i (cmp i cur')
in
(cur',p')

section

noncomputable def next : tvar $ ℕ × (ℕ → evt) → ℕ × (ℕ → evt) :=
⟪ ℕ, next' ⟫ (⊙r)
end

@[simp]
lemma next_def (cur cur' : ℕ) (p p' : ℕ → evt) (σ : ℕ)
: (cur', p') = (σ ⊨ next) (cur, p) ↔
   cur' = max (↓ (i : ℕ), p i ∈ succ σ ⊨ r) (cur + 1) ∧
∀ i, p' i =
          next_p p
            (succ σ ⊨ r) i
            (cmp i cur') :=
by { repeat { simp [next,next'] <|> unfold_coes },
     apply and_congr_right,
     intro,
     split, { introv h, subst cur', simp [h], },
     { intro, apply funext,
       intro, subst cur', solve_by_elim } }

section
parameter f

@[predicate]
noncomputable def cur₀ : tvar ℕ :=
[| r , ↓ i : ℕ, f i ∈ r |]

-- noncomputable abbreviation select₀ : tvar evt :=
-- [| r , f (↓ i : ℕ, f i ∈ r) |]

-- noncomputable def nxt_select : tvar (evt → evt) :=
-- [| p , λ (p' : ℕ → ℕ) (r' : set evt) (e : evt),
--   inv q $ ↓ i : ℕ, inv q i ∈ r' |] (⊙q) (⊙r)

end

noncomputable def Spec :=
⦃cur,p⦄ ≃ ⦃cur₀,f⦄ ⋀ ◻(⊙⦃cur,p⦄ ≃ next ⦃cur,p⦄)

parameter Hq : Γ ⊢ Spec

@[predicate]
def select : tvar evt :=
p cur

-- noncomputable def select_Spec :=
-- select ≃ select₀ ⋀ ◻(⊙select ≃ nxt_select select)

-- variables Hs : Γ ⊢ select_Spec select

section q_injective

lemma next_rec (P : ℕ → Prop) (cur cur') (p p' : ℕ → evt) (r' : set evt)
  {i : ℕ} {e : evt}
  (h : p i = e)
  (Hcur' : cur' = max (↓ (i : ℕ), p i ∈ r') (cur + 1))
  (Hq' : ∀ (i : ℕ), p' i =
       next_p p r' i (cmp i cur'))
  (Hcase_lt : (i < ↓ (i : ℕ), p i ∈ r') ∨ (↓ (i : ℕ), p i ∈ r') < i ∧ ¬i ≤ cur' →
               next_p p r' i (cmp i cur') = e →
               P i)
  (Hcase_eq : (i = ↓ (i : ℕ), p i ∈ r') →
               next_p p r' cur' (cmp cur' cur') = e →
               P cur')
  (Hcase_gt : (↓ (i : ℕ), p i ∈ r') < i →
               next_p p r' (i - 1) (cmp (i - 1) cur') = e →
               P (i - 1))
: (∃ j, p' j = e ∧ P j) :=
begin
  ordering_cases cmp i (↓ i, p i ∈ r'),
  { existsi i, rw Hq',
    suffices : cmp i cur' = ordering.lt,
    { rw [this,next_p,if_neg,h] at *,
      { existsi [rfl], apply_assumption,
        left, solve_by_elim, refl, },
      all_goals { apply not_le_of_gt h_1 }, },
    rw [cmp,cmp_using_eq_lt,Hcur'],
    apply lt_max_of_lt_left _ h_1, },
  { existsi cur', rw Hq',
    have : cmp cur' cur' = ordering.eq,
    { rw [cmp_eq_eq], },
    rw and_iff_imp, intro, solve_by_elim,
    rw [this,next_p], cc },
  by_cases h_cur : i ≤ cur',
  { existsi i - 1, rw Hq',
    have h_i_gt_0 : 0 < i,
    { apply lt_of_le_of_lt,
      apply nat.zero_le, assumption, },
    have : cmp (i - 1) cur' = ordering.lt,
    { rw [cmp,cmp_using_eq_lt],
      apply lt_of_lt_of_le _ h_cur,
      show i - 1 < i,
      { apply nat.sub_lt, assumption, norm_num }, },
    rw and_iff_imp, intro, solve_by_elim,
    rw [this,next_p,if_pos,nat.sub_add_cancel,h],
    assumption,
    rw ← add_le_to_le_sub,
    repeat { assumption }, },
  { existsi i, rw Hq',
    have : cmp i cur' = ordering.gt,
    { rw [cmp,cmp_using_eq_gt],
      apply lt_of_not_ge h_cur },
    rw and_iff_imp, intro, apply_assumption,
    right, tauto, solve_by_elim,
    rw [this,next_p,h] at *, }
end

include Hq Hinj

/- TODO: split into lemmas -/
lemma q_injective
: Γ ⊢ ◻(⟨ surjective ⟩ ! p) :=
begin [temporal]
  cases Hq with Hq Hq',
  t_induction!,
  { explicit' with Hq
    { cases_matching* _ ∧ _, subst p, solve_by_elim, } },
  { henceforth at Hq',
    explicit' with ih Hq'
    { simp_intros e, cases ih e with i h,
      cases Hq' with Hcur' Hq',
      ordering_cases cmp i (↓ i, p i ∈ r'),
      { existsi i, rw Hq',
        suffices : cmp i cur' = ordering.lt,
        { rw [this,next_p,if_neg,h],
          apply not_le_of_gt h_1, },
        rw [cmp,cmp_using_eq_lt,Hcur'],
        apply lt_max_of_lt_left _ h_1, },
      { existsi cur', rw Hq',
        have : cmp cur' cur' = ordering.eq,
        { rw [cmp_eq_eq], },
        rw [this,next_p], cc },
      by_cases h_cur : i ≤ cur',
      { existsi i - 1, rw Hq',
        have h_i_gt_0 : 0 < i,
        { apply lt_of_le_of_lt,
          apply nat.zero_le, assumption, },
        have : cmp (i - 1) cur' = ordering.lt,
        { rw [cmp,cmp_using_eq_lt],
          apply lt_of_lt_of_le _ h_cur,
          show i - 1 < i,
          { apply nat.sub_lt, assumption, norm_num }, },
        rw [this,next_p,if_pos,nat.sub_add_cancel,h],
        assumption,
        rw ← add_le_to_le_sub,
        repeat { assumption }, },
      { existsi i, rw Hq',
        have : cmp i cur' = ordering.gt,
        { rw [cmp,cmp_using_eq_gt],
          apply lt_of_not_ge h_cur },
        rw [this,next_p,h], } } },
end

end q_injective

section

-- include Hq
-- lemma select_eq_inv_q_cur'
-- : Γ ⊢ select_Spec select' :=
-- begin [temporal]
--   cases Hq with Hq₀ Hq,
--   split,
--   explicit' { cc },
--   henceforth! at ⊢ Hq,
--   explicit' [nxt_select]
--   { cases Hq with Hcur Hq,
--     rw [inv_eq _ _ _],
--     rw [Hq,← Hcur],
--     ordering_cases cmp (↓ (i : ℕ), inv q i ∈ r') (q (inv q (↓ (i : ℕ), inv q i ∈ r')))
--     ; simp [next_p],
--     ite_cases,
--     { exfalso, apply h_1, clear h_1,
--       rw Hcur, rw le_max_iff_le_or_le, left,
--        } }
--   { verbose := tt }
-- end

-- include Hs Hinj

-- lemma select_eq_inv_q_cur
-- : Γ ⊢ ◻[| q cur select, select = inv q cur |] :=
-- begin [temporal]
--   have Hinj_q := temporal.scheduling.q_injective,
--   have Hinj_q' := henceforth_next _ _ Hinj_q,
--   cases Hq with Hq₀ Hq,
--   cases Hs with Hs₀ Hs,
--   t_induction! using Hq Hs Hinj_q' Hinj_q,
--   explicit' { cc },
--   explicit' [nxt_select]
--   { cases Hq,
--     rw inv_eq _ _ Hinj_q',
--     rw [Hq_right],
--     ordering_cases (cmp (↓ (i : ℕ), inv q i ∈ r') (q select'))
--     ; simp [next_p],
--     ite_cases,
--     { exfalso, apply h_1, clear h_1,
--       rw le_max_iff_le_or_le, left,
--       apply le_of_eq, clear_except Hs, },
--     {  },
--     {  },
--     {  } }
-- end
-- end

open set

-- invariant
--           inv q' cur' = (↓ i, inv q' i ∈ r)
--           inv q' cur' ≤ (↓ i, inv q' i ∈ r)
--           inv q' cur' ≥ (↓ i, inv q' i ∈ r)

section
include Hr Hq Hinj
lemma valid_indices_ne_empty
: Γ ⊢ ◻([| p, λ r : set evt, { i : ℕ | p i ∈ r } ≠ ∅ |] (⊙r)) :=
begin [temporal]
  have Hsur := temporal.scheduling.q_injective,
  replace Hr := henceforth_next _ _ Hr,
  henceforth! at Hr Hsur ⊢,
  explicit' with Hr Hsur
  { rw not_eq_empty_iff_exists at *,
    cases Hr with i Hr,
    existsi inv p i,
    change _ ∈ r',
    rw [inv_is_right_inverse_of_surjective Hsur],
    assumption, }
end
end

noncomputable def rank (e : evt) : tvar ℕ :=
[| p, ↓ i, p i = e |]

include Hr Hq Hinj
lemma sched_inv
: Γ ⊢ ◻(select ∊ r) :=
begin [temporal]
  have Hq_inj := temporal.scheduling.q_injective,
  have hJ := temporal.scheduling.valid_indices_ne_empty,
  cases Hq with Hq₀ Hq,
  have Hq_inj' := henceforth_next _ _ Hq_inj,
  t_induction!,
  henceforth! at Hr Hq_inj,
  { explicit' [select,cur₀] with Hq₀ Hr Hq_inj
    { change cur ∈ { i | p i ∈ r },
      rw [Hq₀.left,Hq₀.right],
      apply minimum_mem,
      intro, apply Hr,
      rw eq_empty_iff_forall_not_mem at *,
      intro x, specialize a (inv p x),
      -- apply Hr,
      intro, apply a,
      show f (inv p x) ∈ r,
      cases Hq₀, subst p,
      rw [inv_is_right_inverse_of_surjective Hq_inj],
      assumption } },
  henceforth! at Hr Hq_inj' Hq_inj Hq hJ,
  explicit' with Hq hJ
  { cases Hq with Hq Hq',
    rw Hq',
    have : cmp cur' cur' = ordering.eq,
    { rw cmp_eq_eq },
    rw [this,next_p],
    change (↓ (i : ℕ), p i ∈ r') ∈ { i | p i ∈ r' },
    apply minimum_mem,
    assumption },
end

lemma cur_lt_cur'
: Γ ⊢ ◻(cur ≺ ⊙cur) :=
begin [temporal]
  cases Hq with Hq₀ Hq,
  henceforth! at Hq ⊢,
  explicit' with Hq
  { simp [Hq],
    apply lt_max_of_lt_right,
    apply lt_add_one, }
end

section sched_queue_safety
variables
  (q₀ : ℕ)
  (e : evt)
  (Hprev : Γ ⊢ rank e |+| (rank e |-| cur) ≃ ↑q₀)
  (H₂ : Γ ⊢ ⊙(-(⟨λ (i : ℕ), (i ⊨ rank e) + ((i ⊨ rank e) - (i ⊨ cur))⟩ ≺≺ q₀) ⋀
                   -(select ≃ e)))
  (Hdec : Γ ⊢ cur ≺ ⊙cur)
  (Hsurj : Γ ⊢ ⊙( ⟨ surjective ⟩ ! p ))
  (this : Γ ⊢ ⊙rank e ≼ rank e ⋁ ⊙(cur ≃ rank e))

omit Hq
include Hdec Hprev Hsurj H₂ this
lemma non_dec_po
: Γ ⊢ ⊙(rank e |+| (rank e |-| cur) ≃ ↑q₀) :=
begin [temporal]
  explicit' [next,next',select,rank]
    with Hprev this H₂ Hdec Hsurj
  { subst q₀,
    cases this with this this,
    cases lt_or_eq_of_le this,
    { exfalso, apply H₂.left,
      change _ + _ < _ + _,
      apply lt_of_lt_of_le,
      { apply add_lt_add_right h, },
      apply add_le_add_left,
      transitivity,
      { apply nat.sub_le_sub_left,
      apply le_of_lt Hdec, },
      { apply nat.sub_le_sub_right this, } },
    { simp [h],
      let rank := (↓ (i : ℕ), p i = e),
      have : rank - cur' ≤ rank - cur,
      { apply nat.sub_le_sub_left, apply le_of_lt Hdec },
      cases lt_or_eq_of_le this,
      { exfalso, apply H₂.left,
        change _ + _ < _ + _, simp [h,h_1], },
      assumption },
    replace H₂ := H₂.right, rw this at H₂,
    have H₀ : { i : ℕ | p' i = e } ≠ ∅,
    { apply ne_empty_of_mem _,
      exact (inv p' e),
      change p' (inv p' e) = e,
      apply inv_is_right_inverse_of_surjective Hsurj, },
    have H₃ := minimum_mem H₀,
    cases H₂ H₃, },
end

end sched_queue_safety

lemma subsumes_requested (e : evt)
: Γ ⊢ ◻( select ≃ ↑e ⋀ ↑e ∊ r
             ≡ select ≃ ↑e ) :=
begin [temporal]
  have Hr' := temporal.scheduling.sched_inv,
  henceforth! at ⊢ Hr',
  explicit' [select] with Hr'
  { split,
    { simp, intros, assumption },
    { intros, cc, } },
end

-- include Hinj
/-- TODO: Pull out lemmas -/
lemma sched_queue_safety (q₀ : ℕ) (e : evt)
: Γ ⊢ ◻(rank e |+| (rank e |-| cur) ≃ ↑q₀ ⟶
    ◻(rank e |+| (rank e |-| cur) ≃ ↑q₀) ⋁
    ◇(rank e |+| (rank e |-| cur) ≺≺ ↑q₀ ⋁ select ≃ ↑e)) :=
begin [temporal]
  have hJ := temporal.scheduling.q_injective,
  have Hinc := temporal.scheduling.cur_lt_cur',
  have p_not_empty := temporal.scheduling.valid_indices_ne_empty,
  have p'_not_empty := henceforth_next _ _ p_not_empty,
  cases Hq with Hq Hq',
  henceforth!, intro H,
  rw [p_or_comm,← p_not_p_imp],
  intros H₁, simp [p_not_p_or,p_not_p_and] at H₁,
  t_induction,
  { assumption },
  { henceforth!, intro Hprev,
    have H₂ := henceforth_next _ _ H₁,
    have hJ' := henceforth_next _ _ hJ,
    henceforth at Hinc Hq' H₁ H₂ hJ hJ' p_not_empty p'_not_empty,
    apply temporal.scheduling.non_dec_po _ _ Hprev H₂ Hinc hJ',
    explicit' [next,next',select,rank] with Hq' hJ hJ' H₂
    { cases Hq' with Hcur Hq,
      replace Hq := congr_fun Hq, simp only at Hq,
      rw [or_comm,or_iff_not_imp], intro Hncur,
      have p_not_empty : { i : ℕ | p i = e } ≠ ∅,
      { rw ne_empty_iff_exists_mem, apply hJ e, },
      have p'_not_empty : { i : ℕ | p' i = e } ≠ ∅,
      { rw ne_empty_iff_exists_mem, apply hJ' e, },
      apply (le_minimum_iff_forall_le p_not_empty (↓ (i : ℕ), p' i = e)).2,
      assume j (Hj : p j = e),
      apply (minimum_le_iff_exists_le p'_not_empty j).2,
      rw ← Hcur at Hq,
      apply next_rec _ cur cur' p p' r' Hj Hcur Hq,
      { intros, refl },
      { intros h h',
        rw ← Hq at h', cases H₂.right h', },
      { intros, apply nat.sub_le, } }, },
end

/- TODO: split into lemmas -/
lemma sched_queue_liveness (q₀ : ℕ) (e : evt)
: Γ ⊢ ⊙(↑e ∊ r) ⋀ rank e |+| (rank e |-| cur) ≃ ↑q₀ ~>
  rank e |+| (rank e |-| cur) ≺≺ ↑q₀ ⋁ select ≃ ↑e ⋀ ↑e ∊ r :=
begin [temporal]
  { have Hq_inj := temporal.scheduling.q_injective,
    have Hinc := temporal.scheduling.cur_lt_cur',
    cases Hq with Hq₀ Hq,
    henceforth! at ⊢ Hq Hq_inj Hinc,
    have Hq_inj' : ⊙(⟨surjective⟩ ! p) := holds_next _ _ Hq_inj,
    simp, intros hreq hq₀,
    apply next_entails_eventually,
    explicit' [select,next,next',rank]
      with Hq hreq hq₀ Hinc  Hq_inj
    { cases Hq with Hq Hq' Hq_inj,
      replace Hq' := congr_fun Hq', simp at Hq',
      rw ← Hq at Hq',
      let rank := ↓ i, p i = e,
      have Hrank : p rank = e := _,
      let P := λ k, k + (k - cur') < q₀ ∨ k = cur',
      have rec := temporal.scheduling.next_rec P cur cur' p p' r' Hrank Hq Hq' _ _ _,
      { cases rec with k Hk, cases Hk with Hpk Hk,
        cases Hk with Hk Hk,
        { left, change _ + _ < _,
          apply @lt_of_le_of_lt _ _ _ (k + (k - cur')),
          have h : (↓ (i : ℕ), p' i = e) ≤ k, apply minimum_le, exact Hpk,
          apply add_le_add, assumption,
          apply nat.sub_le_sub_right,
          assumption, assumption, },
        { right, cc }, },
      { simp [P,rank], intros h₀ h₁,
        rw ← Hq' (↓ (i : ℕ), p i = e) at h₁,
        clear P,
        cases h₀,
        { right, clear hq₀ Hq',
          have : cur + 1 ≤ (↓ (i : ℕ), p i ∈ r'), admit,
          rw max_eq_left this at Hq, clear this,
          admit },
        { left, rw ← hq₀,
          have : ((↓ (i : ℕ), p i = e) ≥ cur'),
          { apply le_of_lt h₀.right },
          monotonicity Hinc }, },
      { intros, rw ← Hq' at a_1,
        right, refl, },
      { intros, rw ← Hq' at a_1,
        left, rw ← hq₀,
        apply lt_of_lt_of_le,
        apply add_lt_add_right,
        apply nat.sub_lt, apply lt_of_le_of_lt (nat.zero_le _) a,
        norm_num, apply nat.sub_le_sub,
        apply nat.sub_le, apply le_of_lt Hinc, },
      { have h : { i | p i = e } ≠ ∅,
        { rw ne_empty_iff_exists_mem, apply Hq_inj, },
        apply minimum_mem h, } } },
end

lemma sched_fairness (e : evt)
: Γ ⊢ ◻◇(↑e ∊ r) ⟶ ◻◇(select ≃ ↑e ⋀ ↑e ∊ r) :=
begin [temporal]
  suffices : ◻◇⊙(↑e ∊ r) ⟶ ◻◇(temporal.scheduling.select ≃ ↑e ⋀ ↑e ∊ r),
  { intro h, apply this,
    rw [← next_eventually_comm], apply henceforth_next _ _ h, },
  apply inf_often_induction' (temporal.scheduling.rank e |+| (temporal.scheduling.rank e |-| cur)) ; intro q₀,
  { rw temporal.scheduling.subsumes_requested e,
    apply temporal.scheduling.sched_queue_safety q₀ e, },
  { apply temporal.scheduling.sched_queue_liveness }
end

def correct_sched
: Γ ⊢ SCHED select :=
begin [temporal]
  split,
  { apply temporal.scheduling.sched_inv, },
  { intro, apply temporal.scheduling.sched_fairness },
end
end
end implementation

-- class schedulable (α : Sort u) :=
--   (f : α → ℕ)
--   (inj : injective f)
open encodable

example (w σ₀ : tvar ℕ)
: ⇑(to_fun_var (λ (w : tvar ℕ), w ≃ σ₀)) w = w ≃ σ₀ :=
begin
  -- rw [v_eq,to_fun_var_lift₂],
  -- dsimp,
  -- dsimp,
  -- unfold_coes,
  -- dsimp with lifted_fn,
  -- unfold_coes,
  simp! only with lifted_fn predicate,
end

lemma scheduler [encodable evt]
  (Hr : Γ ⊢ ◻-(r ≃ (∅ : set evt)))
: Γ ⊢ (∃∃ s, SCHED s) :=
begin [temporal]
  let f' : (evt → ℕ) := @encode evt _,
  let f : tvar (evt → ℕ) := f',
  have Hnemp : ∃∃ x : evt, True,
  { admit },
  nonempty evt,
  let g' : (ℕ → evt) := inv (@encode evt _),
  let g  : tvar (ℕ → evt) := g',
  let σ₀ := ⦃cur₀ r g',g⦄,
  select_witness w : w ≃ σ₀ ⋀ ◻(⊙w ≃ temporal.scheduling.next w),
  have := fwd_witness σ₀ (next r) Γ,
  cases this with cur Hcur,
  cases cur with cur q,
  existsi select p cur,
  note Hsur : surjective (inv f'),
  { apply surjective_of_has_right_inverse,
    existsi f',
    apply inv_is_left_inverse_of_injective,
    apply schedulable.inj },
  type_check @temporal.scheduling.correct_sched,
  apply temporal.scheduling.correct_sched (inv f') Hsur _,
  simp [Spec,σ₀] at ⊢ Hcur,
  exact Hcur,
end

end scheduling

section spec

variables Γ : cpred
variables {α : Type v} (m : mch α)
local notation `evt` := m.evt
variable [encodable evt]
local notation `cs` := m.cs
local notation `fs` := m.fs
local notation `p` := m.init
local notation `A` := m.A

lemma sch_intro (v : tvar α)
: Γ ⊢ m.spec v ⟶ (∃∃ sch, m.spec_sch v sch) :=
begin [temporal]
  intro h,
  let r : tvar (set (option evt)) := ⟪ ℕ, λ s s', { e | m.effect e s s' } ⟫ v ⊙v,
  have hr : ◻-(r ≃ (∅ : set (option evt))),
  { simp [mch.spec] at h,
    casesm* _ ⋀ _,
    select Hact : ◻(p_exists _),
    henceforth! at Hact ⊢,
    explicit' [r] with Hact
    { erw [← not_eq_empty_iff_exists] at Hact, exact Hact }, },
  have h' := temporal.scheduling.scheduler Γ r hr,
  cases h' with sch h',
  existsi sch,
  simp  at ⊢ h,
  casesm* _ ⋀ _,
  split!* ; try { solve_by_elim },
  { select h' : ◻(p_exists _),
    select hJ : ◻(_ ∊ _),
    henceforth! at hJ h' ⊢,
    existsi sch with hh,
    { explicit' [r] with hh hJ h'
      { subst sch, tauto } } },
  { introv, intros h₀ h₁,
    rename a_3 h₂,
    replace h₂ := h₂ x h₀ h₁,
    replace a_1 := a_1 x,
    persistent,
    have H₀ : ↑x ∊ r ≡ cs x ! v ⋀ fs x ! v ⋀ ⟦ v | A x ⟧,
    { explicit' [r]
      { simp [mch.effect,and_assoc] }, },
    have H₁ : sch ≃ ↑x ⋀ ↑x ∊ r ≡ cs x ! v ⋀ fs x ! v ⋀ (sch ≃ ↑x ⋀ ⟦ v | A x ⟧),
    { explicit' [r,mch.effect,and_assoc]
      { apply eq.to_iff, ac_refl }, },
    rw [H₁,H₀] at a_1,
    solve_by_elim, }
end

end spec
end scheduling
export scheduling (schedulable sch_intro)
end temporal


/- Arithmetic and logical operators for the Compcert C and Clight languages -/

import .ctypes .memory

namespace cop
open ast integers floats values memory ctypes word
     ctypes.intsize ctypes.floatsize ctypes.signedness

/- * Syntax of operators. -/

inductive unary_operation : Type
| Onotbool          /- boolean negation ([!] in C) -/
| Onotint           /- integer complement ([~] in C) -/
| Oneg              /- opposite (unary [-]) -/
| Oabsfloat         /- floating-point absolute value -/
open unary_operation

inductive binary_operation : Type
| Oadd              /- addition (binary [+]) -/
| Osub              /- subtraction (binary [-]) -/
| Omul              /- multiplication (binary [*]) -/
| Odiv              /- division ([/]) -/
| Omod              /- remainder ([%]) -/
| Oand              /- bitwise and ([&]) -/
| Oor               /- bitwise or ([|]) -/
| Oxor              /- bitwise xor ([^]) -/
| Oshl              /- left shift ([<<]) -/
| Oshr              /- right shift ([>>]) -/
| Oeq               /- comparison ([==]) -/
| One               /- comparison ([!=]) -/
| Olt               /- comparison ([<]) -/
| Ogt               /- comparison ([>]) -/
| Ole               /- comparison ([<=]) -/
| Oge               /- comparison ([>=]) -/
open binary_operation

inductive incr_or_decr : Type | Incr | Decr
open incr_or_decr

/- * Type classification and semantics of operators. -/

/- Most C operators are overloaded (they apply to arguments of various
  types) and their semantics depend on the types of their arguments.
  The following [classify_*] functions take as arguments the types
  of the arguments of an operation.  They return enough information
  to resolve overloading for this operator applications, such as
  ``both arguments are floats'', or ``the first is a pointer
  and the second is an integer''.  This classification is used in the
  compiler (module [Cshmgen]) to resolve overloading statically.

  The [sem_*] functions below compute the result of an operator
  application.  Since operators are overloaded, the result depends
  both on the static types of the arguments and on their run-time values.
  The corresponding [classify_*] function is first called on the
  types of the arguments to resolve static overloading.  It is then
  followed by a case analysis on the values of the arguments. -/

/- ** Casts and truth values -/

inductive classify_cast_cases : Type
| cast_case_pointer                                /- between pointer types or intptr_t types -/
| cast_case_i2i (sz2 : intsize) (si2 : signedness) /- int -> int -/
| cast_case_f2f                                    /- double -> double -/
| cast_case_s2s                                    /- single -> single -/
| cast_case_f2s                                    /- double -> single -/
| cast_case_s2f                                    /- single -> double -/
| cast_case_i2f (si1 : signedness)                 /- int -> double -/
| cast_case_i2s (si1 : signedness)                 /- int -> single -/
| cast_case_f2i (sz2 : intsize) (si2 : signedness) /- double -> int -/
| cast_case_s2i (sz2 : intsize) (si2 : signedness) /- single -> int -/
| cast_case_l2l                                    /- long -> long -/
| cast_case_i2l (si1 : signedness)                 /- int -> long -/
| cast_case_l2i (sz2 : intsize) (si2 : signedness) /- long -> int -/
| cast_case_l2f (si1 : signedness)                 /- long -> double -/
| cast_case_l2s (si1 : signedness)                 /- long -> single -/
| cast_case_f2l (si2 : signedness)                 /- double -> long -/
| cast_case_s2l (si2 : signedness)                 /- single -> long -/
| cast_case_i2bool                                 /- int -> bool -/
| cast_case_l2bool                                 /- long -> bool -/
| cast_case_f2bool                                 /- double -> bool -/
| cast_case_s2bool                                 /- single -> bool -/
| cast_case_struct (id1 id2 : ident)               /- struct -> struct -/
| cast_case_union  (id1 id2 : ident)               /- union -> union -/
| cast_case_void                                   /- any -> void -/
| cast_case_default
open classify_cast_cases

def classify_cast (tfrom tto : type) : classify_cast_cases :=
match tto, tfrom with
  /- To [void] -/
| Tvoid, _ := cast_case_void
  /- To [_Bool] -/
| Tint IBool _ _, Tint _ _ _ := cast_case_i2bool
| Tint IBool _ _, Tlong _ _ := cast_case_l2bool
| Tint IBool _ _, Tfloat F64 _ := cast_case_f2bool
| Tint IBool _ _, Tfloat F32 _ := cast_case_s2bool
| Tint IBool _ _, Tpointer _ _ := if archi.ptr64 then cast_case_l2bool else cast_case_i2bool
| Tint IBool _ _, Tarray _ _ _ := if archi.ptr64 then cast_case_l2bool else cast_case_i2bool
| Tint IBool _ _, Tfunction _ _ _ := if archi.ptr64 then cast_case_l2bool else cast_case_i2bool
  /- To [int] other than [_Bool] -/
| Tint sz2 si2 _, Tint _ _ _ :=
      if archi.ptr64 then cast_case_i2i sz2 si2
      else if sz2 = I32 then cast_case_pointer
      else cast_case_i2i sz2 si2
| Tint sz2 si2 _, Tlong _ _ := cast_case_l2i sz2 si2
| Tint sz2 si2 _, Tfloat F64 _ := cast_case_f2i sz2 si2
| Tint sz2 si2 _, Tfloat F32 _ := cast_case_s2i sz2 si2
| Tint sz2 si2 _, Tpointer _ _ :=
      if archi.ptr64 then cast_case_l2i sz2 si2
      else if sz2 = I32 then cast_case_pointer
      else cast_case_i2i sz2 si2
| Tint sz2 si2 _, Tarray _ _ _ :=
      if archi.ptr64 then cast_case_l2i sz2 si2
      else if sz2 = I32 then cast_case_pointer
      else cast_case_i2i sz2 si2
| Tint sz2 si2 _, Tfunction _ _ _ :=
      if archi.ptr64 then cast_case_l2i sz2 si2
      else if sz2 = I32 then cast_case_pointer
      else cast_case_i2i sz2 si2
  /- To [long] -/
| Tlong _ _, Tlong _ _ :=
      if archi.ptr64 then cast_case_pointer else cast_case_l2l
| Tlong _ _, Tint sz1 si1 _ := cast_case_i2l si1
| Tlong si2 _, Tfloat F64 _ := cast_case_f2l si2
| Tlong si2 _, Tfloat F32 _ := cast_case_s2l si2
| Tlong si2 _, Tpointer _ _ := if archi.ptr64 then cast_case_pointer else cast_case_i2l si2
| Tlong si2 _, Tarray _ _ _ := if archi.ptr64 then cast_case_pointer else cast_case_i2l si2
| Tlong si2 _, Tfunction _ _ _ := if archi.ptr64 then cast_case_pointer else cast_case_i2l si2
  /- To [float] -/
| Tfloat F64 _, Tint sz1 si1 _ := cast_case_i2f si1
| Tfloat F32 _, Tint sz1 si1 _ := cast_case_i2s si1
| Tfloat F64 _, Tlong si1 _ := cast_case_l2f si1
| Tfloat F32 _, Tlong si1 _ := cast_case_l2s si1
| Tfloat F64 _, Tfloat F64 _ := cast_case_f2f
| Tfloat F32 _, Tfloat F32 _ := cast_case_s2s
| Tfloat F64 _, Tfloat F32 _ := cast_case_s2f
| Tfloat F32 _, Tfloat F64 _ := cast_case_f2s
  /- To pointer types -/
| Tpointer _ _, Tint _ _ _ :=
      if archi.ptr64 then cast_case_i2l Unsigned else cast_case_pointer
| Tpointer _ _, Tlong _ _ :=
      if archi.ptr64 then cast_case_pointer else cast_case_l2i I32 Unsigned
| Tpointer _ _, Tpointer _ _ := cast_case_pointer
| Tpointer _ _, Tarray _ _ _ := cast_case_pointer
| Tpointer _ _, Tfunction _ _ _ := cast_case_pointer
  /- To struct or union types -/
| Tstruct id2 _, Tstruct id1 _ := cast_case_struct id1 id2
| Tunion id2 _, Tunion id1 _ := cast_case_union id1 id2
  /- Catch-all -/
| _, _ := cast_case_default
end

/- Semantics of casts.  [sem_cast v1 t1 t2 m = Some v2] if value [v1],
  viewed with static type [t1], can be converted  to type [t2],
  resulting in value [v2].  -/

def cast_int_int : intsize → signedness → int32 → int32
| I8  Signed   i := sign_ext W8 i
| I8  Unsigned i := zero_ext 8 i
| I16 Signed   i := sign_ext W16 i
| I16 Unsigned i := zero_ext 16 i
| I32 _        i := i
| IBool _      i := if i = 0 then 0 else 1

def cast_int_float : signedness → int32 → float
| Signed   := float.of_int
| Unsigned := float.of_intu

def cast_float_int : signedness → float → option int32
| Signed   := float.to_int
| Unsigned := float.to_intu

def cast_int_single : signedness → int32 → float32
| Signed   := float32.of_int
| Unsigned := float32.of_intu

def cast_single_int : signedness → float32 → option int32
| Signed   := float32.to_int
| Unsigned := float32.to_intu

def cast_int_long : signedness → int32 → int64
| Signed   := scoe
| Unsigned := ucoe

def cast_long_float : signedness → int64 → float
| Signed   := float.of_long
| Unsigned := float.of_longu

def cast_long_single : signedness → int64 → float32
| Signed   := float32.of_long
| Unsigned := float32.of_longu

def cast_float_long : signedness → float → option int64
| Signed   := float.to_long
| Unsigned := float.to_longu

def cast_single_long : signedness → float32 → option int64
| Signed   := float32.to_long
| Unsigned := float32.to_longu

def sem_cast (m : mem) (v : val) (t1 t2 : type) : option val :=
match classify_cast t1 t2, v with
| cast_case_pointer,        Vptr _ _   := some v
| cast_case_pointer,        Vint _     := if archi.ptr64 then none else some v
| cast_case_pointer,        Vlong _    := if archi.ptr64 then some v else none
| cast_case_i2i sz2 si2,    Vint i     := some (Vint (cast_int_int sz2 si2 i))
| cast_case_f2f,            Vfloat f   := some (Vfloat f)
| cast_case_s2s,            Vsingle f  := some (Vsingle f)
| cast_case_s2f,            Vsingle f  := some (Vfloat (float.of_single f))
| cast_case_f2s,            Vfloat f   := some (Vsingle (float.to_single f))
| cast_case_i2f si1,        Vint i     := some (Vfloat (cast_int_float si1 i))
| cast_case_i2s si1,        Vint i     := some (Vsingle (cast_int_single si1 i))
| cast_case_f2i sz2 si2,    Vfloat f   := (λi, Vint (cast_int_int sz2 si2 i)) <$> cast_float_int si2 f
| cast_case_s2i sz2 si2,    Vsingle f  := (λi, Vint (cast_int_int sz2 si2 i)) <$> cast_single_int si2 f
| cast_case_i2bool,         Vint n     := some (Vint (if n = 0 then 0 else 1))
| cast_case_i2bool,         Vptr b ofs := if ¬ archi.ptr64 ∧ weak_valid_pointer m b (unsigned ofs) then some Vone else none
| cast_case_l2bool,         Vlong n    := some (Vint (if n = 0 then 0 else 1))
| cast_case_l2bool,         Vptr b ofs := if archi.ptr64 ∧ weak_valid_pointer m b (unsigned ofs) then some Vone else none
| cast_case_f2bool,         Vfloat f   := some (Vint (if float.cmp Ceq f 0 then 0 else 1))
| cast_case_s2bool,         Vsingle f  := some (Vint (if float32.cmp Ceq f 0 then 0 else 1))
| cast_case_l2l,            Vlong n    := some (Vlong n)
| cast_case_i2l si,         Vint n     := some (Vlong (cast_int_long si n))
| cast_case_l2i sz si,      Vlong n    := some (Vint (cast_int_int sz si (ucoe n)))
| cast_case_l2f si1,        Vlong i    := some (Vfloat (cast_long_float si1 i))
| cast_case_l2s si1,        Vlong i    := some (Vsingle (cast_long_single si1 i))
| cast_case_f2l si2,        Vfloat f   := Vlong <$> cast_float_long si2 f
| cast_case_s2l si2,        Vsingle f  := Vlong <$> cast_single_long si2 f
| cast_case_struct id1 id2, Vptr b ofs := if id1 = id2 then some v else none
| cast_case_union id1 id2,  Vptr b ofs := if id1 = id2 then some v else none
| cast_case_void,           v          := some v
| _,                        _          := none
end

/- The following describes types that can be interpreted as a boolean:
  integers, floats, pointers.  It is used for the semantics of
  the [!] and [?] operators, as well as the [if], [while],
  and [for] statements. -/

inductive classify_bool_cases : Type
| bool_case_i                           /- integer -/
| bool_case_l                           /- long -/
| bool_case_f                           /- double float -/
| bool_case_s                           /- single float -/
| bool_default
open classify_bool_cases

def classify_bool (ty : type) : classify_bool_cases :=
match typeconv ty with
| Tint _ _ _   := bool_case_i
| Tpointer _ _ := if archi.ptr64 then bool_case_l else bool_case_i
| Tfloat F64 _ := bool_case_f
| Tfloat F32 _ := bool_case_s
| Tlong _ _    := bool_case_l
| _            := bool_default
end

/- Interpretation of values as truth values.
  Non-zero integers, non-zero floats and non-null pointers are
  considered as true.  The integer zero (which also represents
  the null pointer) and the float 0.0 are false. -/

def bool_val (m : mem) (v : val) (t : type) : option bool :=
match classify_bool t, v with
| bool_case_i, Vint n := some (n ≠ 0)
| bool_case_i, Vptr b ofs := if archi.ptr64 then none else
          if weak_valid_pointer m b (unsigned ofs) then some tt else none
| bool_case_l, Vlong n := some (n ≠ 0)
| bool_case_l, Vptr b ofs := if ¬ archi.ptr64 then none else
          if weak_valid_pointer m b (unsigned ofs) then some tt else none
| bool_case_f, Vfloat f := some (bnot (float.cmp Ceq f 0))
| bool_case_s, Vsingle f := some (bnot (float32.cmp Ceq f 0))
| _, _ := none
end

/- ** Unary operators -/

/- *** Boolean negation -/

def sem_notbool (m : mem) (v : val) (ty : type) : option val :=
(λ b, val.of_bool (bnot b)) <$> bool_val m v ty

/- *** Opposite and absolute value -/

inductive classify_neg_cases : Type
| neg_case_i (s : signedness)            /- int -/
| neg_case_f                             /- double float -/
| neg_case_s                             /- single float -/
| neg_case_l (s : signedness)            /- long -/
| neg_default
open classify_neg_cases

def classify_neg : type → classify_neg_cases
| (Tint I32 Unsigned _) := neg_case_i Unsigned
| (Tint _ _ _)          := neg_case_i Signed
| (Tfloat F64 _)        := neg_case_f
| (Tfloat F32 _)        := neg_case_s
| (Tlong si _)          := neg_case_l si
| _                     := neg_default

def sem_neg (v : val) (ty : type) : option val :=
match classify_neg ty, v with
| neg_case_i sg, Vint n  := some (Vint (-n))
| neg_case_f, Vfloat f   := some (Vfloat (-f))
| neg_case_s, Vsingle f  := some (Vsingle (-f))
| neg_case_l sg, Vlong n := some (Vlong (-n))
| _, _                   := none
end

def sem_absfloat (v : val) (ty : type) : option val :=
match classify_neg ty, v with
| neg_case_i sg, Vint n  := some (Vfloat (float.abs (cast_int_float sg n)))
| neg_case_f, Vfloat f   := some (Vfloat (float.abs f))
| neg_case_s, Vsingle f  := some (Vfloat (float.abs (float.of_single f)))
| neg_case_l sg, Vlong n := some (Vfloat (float.abs (cast_long_float sg n)))
| _, _                   := none
end

/- *** Bitwise complement -/

inductive classify_notint_cases : Type
| notint_case_i (s : signedness)              /- int -/
| notint_case_l (s : signedness)              /- long -/
| notint_default
open classify_notint_cases

def classify_notint : type → classify_notint_cases
| (Tint I32 Unsigned _) := notint_case_i Unsigned
| (Tint _ _ _) := notint_case_i Signed
| (Tlong si _) := notint_case_l si
| _ := notint_default

def sem_notint (v : val) (ty : type) : option val :=
match classify_notint ty, v with
| notint_case_i sg, Vint n  := some (Vint (word.not n))
| notint_case_l sg, Vlong n := some (Vlong (word.not n))
| _, _                      := none
end

/- ** Binary operators -/

/- For binary operations, the "usual binary conversions" consist in
- determining the type at which the operation is to be performed
  (a form of least upper bound of the types of the two arguments);
- casting the two arguments to this common type;
- performing the operation at that type.
-/

inductive binarith_cases : Type
| bin_case_i (s : signedness)        /- at int type -/
| bin_case_l (s : signedness)        /- at long int type -/
| bin_case_f                         /- at double float type -/
| bin_case_s                         /- at single float type -/
| bin_default                        /- error -/
open binarith_cases

def classify_binarith : type → type → binarith_cases
| (Tint I32 Unsigned _) (Tint _ _ _)          := bin_case_i Unsigned
| (Tint _ _ _)          (Tint I32 Unsigned _) := bin_case_i Unsigned
| (Tint _ _ _)          (Tint _ _ _)          := bin_case_i Signed
| (Tlong Signed _)      (Tlong Signed _)      := bin_case_l Signed
| (Tlong _ _)           (Tlong _ _)           := bin_case_l Unsigned
| (Tlong sg _)          (Tint _ _ _)          := bin_case_l sg
| (Tint _ _ _)          (Tlong sg _)          := bin_case_l sg
| (Tfloat F32 _)        (Tfloat F32 _)        := bin_case_s
| (Tfloat _ _)          (Tfloat _ _)          := bin_case_f
| (Tfloat F64 _)        (Tint _ _ _)          := bin_case_f
| (Tfloat F64 _)        (Tlong _ _)           := bin_case_f
| (Tint _ _ _)          (Tfloat F64 _)        := bin_case_f
| (Tlong _ _)           (Tfloat F64 _)        := bin_case_f
| (Tfloat F32 _)        (Tint _ _ _)          := bin_case_s
| (Tfloat F32 _)        (Tlong _ _)           := bin_case_s
| (Tint _ _ _)          (Tfloat F32 _)        := bin_case_s
| (Tlong _ _)           (Tfloat F32 _)        := bin_case_s
| _                     _                     := bin_default

/- The static type of the result. Both arguments are converted to this type
    before the actual computation. -/

def binarith_type : binarith_cases → type
| (bin_case_i sg) := Tint I32 sg noattr
| (bin_case_l sg) := Tlong sg noattr
| bin_case_f      := Tfloat F64 noattr
| bin_case_s      := Tfloat F32 noattr
| bin_default     := Tvoid

def sem_binarith
    (sem_int : signedness → int32 → int32 → option val)
    (sem_long : signedness → int64 → int64 → option val)
    (sem_float : float → float → option val)
    (sem_single : float32 → float32 → option val)
    (m : mem) (v1 : val) (t1 : type) (v2 : val) (t2 : type) : option val :=
let c := classify_binarith t1 t2, t := binarith_type c in
match sem_cast m v1 t1 t, sem_cast m v2 t2 t, c with
| some (Vint n1),    some (Vint n2),    bin_case_i sg := sem_int sg n1 n2
| some (Vfloat n1),  some (Vfloat n2),  bin_case_f    := sem_float n1 n2
| some (Vsingle n1), some (Vsingle n2), bin_case_s    := sem_single n1 n2
| some (Vlong n1),   some (Vlong n2),   bin_case_l sg := sem_long sg n1 n2
| _,                 _,                 _             := none
end

/- *** Addition -/

inductive classify_add_cases : Type
| add_case_pi (ty : type) (si : signedness)     /- pointer, int -/
| add_case_pl (ty : type)                       /- pointer, long -/
| add_case_ip (si : signedness) (ty : type)     /- int, pointer -/
| add_case_lp (ty : type)                       /- long, pointer -/
| add_default                                   /- numerical type, numerical type -/
open classify_add_cases

def classify_add (ty1 : type) (ty2 : type) :=
match typeconv ty1, typeconv ty2 with
| Tpointer ty _, Tint _ si _   := add_case_pi ty si
| Tpointer ty _, Tlong _ _     := add_case_pl ty
| Tint _ si _,   Tpointer ty _ := add_case_ip si ty
| Tlong _ _,     Tpointer ty _ := add_case_lp ty
| _,             _             := add_default
end

def ptrofs_of_int : signedness → int32 → ptrofs
| Signed := ptrofs.of_ints
| Unsigned := ptrofs.of_intu

def sem_add_ptr_int (cenv : composite_env) (ty : type) (si : signedness) : val → val → option val
| (Vptr b1 ofs1) (Vint n2) := let n2 := ptrofs_of_int si n2 in
                              some (Vptr b1 (ofs1 + repr (sizeof cenv ty) * n2))
| (Vint n1)      (Vint n2) := if archi.ptr64 then none else
                              some (Vint (n1 + repr (sizeof cenv ty) * n2))
| (Vlong n1)     (Vint n2) := let n2 := cast_int_long si n2 in
                              if ¬ archi.ptr64 then none else
                              some (Vlong (n1 + repr (sizeof cenv ty) * n2))
| _              _         := none

def sem_add_ptr_long (cenv : composite_env) (ty : type) : val → val → option val
| (Vptr b1 ofs1) (Vlong n2) := let n2 := ptrofs.of_int64 n2 in
                               some (Vptr b1 (ofs1 + repr (sizeof cenv ty) * n2))
| (Vint n1)      (Vlong n2) := let n2 : int32 := ucoe n2 in
                               if archi.ptr64 then none else
                               some (Vint (n1 + repr (sizeof cenv ty) * n2))
| (Vlong n1)     (Vlong n2) := if ¬ archi.ptr64 then none else
                               some (Vlong (n1 + repr (sizeof cenv ty) * n2))
| _              _          := none

def sem_add (cenv : composite_env) (m : mem) (v1 : val) (t1 : type) (v2 : val) (t2 : type) : option val :=
match classify_add t1 t2 with
| add_case_pi ty si := sem_add_ptr_int cenv ty si v1 v2             /- pointer plus integer -/
| add_case_pl ty    := sem_add_ptr_long cenv ty v1 v2                 /- pointer plus long -/
| add_case_ip si ty := sem_add_ptr_int cenv ty si v2 v1             /- integer plus pointer -/
| add_case_lp ty    := sem_add_ptr_long cenv ty v2 v1                  /- long plus pointer -/
| add_default       := sem_binarith
    (λ sg n1 n2, some (Vint (n1 + n2)))
    (λ sg n1 n2, some (Vlong (n1 + n2)))
    (λ n1 n2, some (Vfloat (n1 + n2)))
    (λ n1 n2, some (Vsingle (n1 + n2)))
    m v1 t1 v2 t2
end

/- *** Subtraction -/

inductive classify_sub_cases : Type
| sub_case_pi (ty : type) (si : signedness)  /- pointer, int -/
| sub_case_pp (ty : type)               /- pointer, pointer -/
| sub_case_pl (ty : type)               /- pointer, long -/
| sub_default                           /- numerical type, numerical type -/
open classify_sub_cases

def classify_sub (ty1 : type) (ty2 : type) :=
match typeconv ty1, typeconv ty2 with
| Tpointer ty _,  Tint _ si _  := sub_case_pi ty si
| Tpointer ty _ , Tpointer _ _ := sub_case_pp ty
| Tpointer ty _,  Tlong _ _    := sub_case_pl ty
| _,              _            := sub_default
end

def sem_sub (cenv : composite_env) (m : mem) (v1 : val) (t1 : type) (v2 : val) (t2 : type) : option val :=
match classify_sub t1 t2, v1, v2 with
| sub_case_pi ty si, Vptr b1 ofs1, Vint n2 :=
    let n2 := ptrofs_of_int si n2 in
    some (Vptr b1 (ofs1 - repr (sizeof cenv ty) * n2))
| sub_case_pi ty si, Vint n1, Vint n2 :=
    if archi.ptr64 then none else some (Vint (n1 - repr (sizeof cenv ty) * n2))
| sub_case_pi ty si, Vlong n1, Vint n2 :=
    let n2 := cast_int_long si n2 in
    if archi.ptr64 then some (Vlong (n1 - repr (sizeof cenv ty) * n2)) else none
| sub_case_pl ty, Vptr b1 ofs1, Vlong n2 :=
    let n2 := ptrofs.of_int64 n2 in
    some (Vptr b1 (ofs1 - repr (sizeof cenv ty) * n2))
| sub_case_pl ty, Vint n1, Vlong n2 :=
    if archi.ptr64 then none else some (Vint (n1 - repr (sizeof cenv ty) * ucoe n2))
| sub_case_pl ty, Vlong n1, Vlong n2 :=
    if archi.ptr64 then some (Vlong (n1 - repr (sizeof cenv ty) * n2)) else none
| sub_case_pp ty, Vptr b1 ofs1, Vptr b2 ofs2 :=
    if b1 = b2 then
      let sz := sizeof cenv ty in
      if 0 < sz ∧ sz ≤ max_signed ptrofs.wordsize
      then some (Vptrofs ((ofs1 - ofs2) / repr sz : word _))
      else none
    else none
| sub_default, _, _ := sem_binarith
      (λ sg n1 n2, some (Vint (n1 - n2)))
      (λ sg n1 n2, some (Vlong (n1 - n2)))
      (λ n1 n2, some (Vfloat (n1 - n2)))
      (λ n1 n2, some (Vsingle (n1 - n2)))
      m v1 t1 v2 t2
| _, _, _ := none
end

/- *** Multiplication, division, modulus -/

def sem_mul : mem → val → type → val → type → option val :=
sem_binarith
  (λ sg n1 n2, some (Vint (n1 * n2)))
  (λ sg n1 n2, some (Vlong (n1 * n2)))
  (λ n1 n2, some (Vfloat (n1 * n2)))
  (λ n1 n2, some (Vsingle (n1 * n2)))

def sem_div : mem → val → type → val → type → option val :=
sem_binarith
  (λ sg n1 n2,
    match sg with
    | Signed   := if n2 = 0 ∨ n1 = repr (min_signed W32) ∧ n2 = -1
                  then none else some (Vint (n1 / n2 : word _))
    | Unsigned := if n2 = 0 then none else some (Vint (n1 / n2 : uword _))
    end)
  (λ sg n1 n2,
    match sg with
    | Signed   := if n2 = 0 ∨ n1 = repr (min_signed W64) ∧ n2 = -1
                  then none else some (Vlong (n1 / n2 : word _))
    | Unsigned := if n2 = 0 then none else some (Vlong (n1 / n2 : uword _))
    end)
  (λ n1 n2, some (Vfloat (n1 / n2)))
  (λ n1 n2, some (Vsingle (n1 / n2)))

def sem_mod : mem → val → type → val → type → option val :=
sem_binarith
  (λ sg n1 n2,
    match sg with
    | Signed   := if n2 = 0 ∨ n1 = repr (min_signed W32) ∧ n2 = -1
                  then none else some (Vint (n1 % n2 : word _))
    | Unsigned := if n2 = 0 then none else some (Vint (n1 % n2 : uword _))
    end)
  (λ sg n1 n2,
    match sg with
    | Signed   := if n2 = 0 ∨ n1 = repr (min_signed W64) ∧ n2 = -1
                  then none else some (Vlong (n1 % n2 : word _))
    | Unsigned := if n2 = 0 then none else some (Vlong (n1 % n2 : uword _))
    end)
  (λ n1 n2, none)
  (λ n1 n2, none)

def sem_and : mem → val → type → val → type → option val :=
sem_binarith
  (λ sg n1 n2, some (Vint (word.and n1 n2)))
  (λ sg n1 n2, some (Vlong (word.and n1 n2)))
  (λ n1 n2, none)
  (λ n1 n2, none)

def sem_or : mem → val → type → val → type → option val :=
sem_binarith
  (λ sg n1 n2, some (Vint (word.or n1 n2)))
  (λ sg n1 n2, some (Vlong (word.or n1 n2)))
  (λ n1 n2, none)
  (λ n1 n2, none)

def sem_xor : mem → val → type → val → type → option val :=
sem_binarith
  (λ sg n1 n2, some (Vint (word.xor n1 n2)))
  (λ sg n1 n2, some (Vlong (word.xor n1 n2)))
  (λ n1 n2, none)
  (λ n1 n2, none)

/- *** Shifts -/

/- Shifts do not perform the usual binary conversions.  Instead,
  each argument is converted independently, and the signedness
  of the result is always that of the first argument. -/

inductive classify_shift_cases : Type
| shift_case_ii (s : signedness)         /- int , int -/
| shift_case_ll (s : signedness)         /- long, long -/
| shift_case_il (s : signedness)         /- int, long -/
| shift_case_li (s : signedness)         /- long, int -/
| shift_default
open classify_shift_cases

def classify_shift (ty1 : type) (ty2 : type) :=
match typeconv ty1, typeconv ty2 with
| Tint I32 Unsigned _, Tint _ _ _ := shift_case_ii Unsigned
| Tint _ _ _,          Tint _ _ _ := shift_case_ii Signed
| Tint I32 Unsigned _, Tlong _ _  := shift_case_il Unsigned
| Tint _ _ _,          Tlong _ _  := shift_case_il Signed
| Tlong s _,           Tint _ _ _ := shift_case_li s
| Tlong s _,           Tlong _ _  := shift_case_ll s
| _,                   _          := shift_default
end

def sem_shift
    (sem_int : signedness → int32 → int32 → int32)
    (sem_long : signedness → int64 → int64 → int64)
    (v1 : val) (t1 : type) (v2 : val) (t2 : type) : option val :=
match classify_shift t1 t2, v1, v2 with
| shift_case_ii sg, Vint n1,  Vint n2  := if ltu n2 iwordsize then some (Vint (sem_int sg n1 n2)) else none
| shift_case_il sg, Vint n1,  Vlong n2 := if ltu n2 (repr 32) then some (Vint (sem_int sg n1 n2.loword)) else none
| shift_case_li sg, Vlong n1, Vint n2  := if ltu n2 (repr 64) then some (Vlong (sem_long sg n1 (ucoe n2))) else none
| shift_case_ll sg, Vlong n1, Vlong n2 := if ltu n2 iwordsize then some (Vlong (sem_long sg n1 n2)) else none
| _,                _,        _        := none
end

def sem_shl : val → type → val → type → option val :=
sem_shift
  (λ sg n1 n2, word.shl n1 n2)
  (λ sg n1 n2, word.shl n1 n2)

def sem_shr : val → type → val → type → option val :=
sem_shift
  (λ sg n1 n2, match sg with Signed := word.shr n1 n2 | Unsigned := word.shru n1 n2 end)
  (λ sg n1 n2, match sg with Signed := word.shr n1 n2 | Unsigned := word.shru n1 n2 end)

/- *** Comparisons -/

inductive classify_cmp_cases : Type
| cmp_case_pp                        /- pointer, pointer -/
| cmp_case_pi (si : signedness)      /- pointer, int -/
| cmp_case_ip (si : signedness)      /- int, pointer -/
| cmp_case_pl                        /- pointer, long -/
| cmp_case_lp                        /- long, pointer -/
| cmp_default                        /- numerical, numerical -/
open classify_cmp_cases

def classify_cmp (ty1 : type) (ty2 : type) :=
match typeconv ty1, typeconv ty2 with
| Tpointer _ _ , Tpointer _ _ := cmp_case_pp
| Tpointer _ _ , Tint _ si _  := cmp_case_pi si
| Tint _ si _,   Tpointer _ _ := cmp_case_ip si
| Tpointer _ _ , Tlong _ _    := cmp_case_pl
| Tlong _ _ ,    Tpointer _ _ := cmp_case_lp
| _,             _            := cmp_default
end

def cmp_ptr (m : mem) (c : comparison) (v1 v2 : val) : option val :=
val.of_bool <$> (if archi.ptr64 then cmplu_bool else cmpu_bool) (valid_pointer m) c v1 v2

def sem_cmp (c : comparison) (m : mem) (v1 : val) (t1 : type) (v2 : val) (t2 : type) : option val :=
match classify_cmp t1 t2, v1, v2 with
| cmp_case_pp,    v1, v2         := cmp_ptr m c v1 v2
| cmp_case_pi si, v1, Vint n2    := cmp_ptr m c v1 (Vptrofs (ptrofs_of_int si n2))
| cmp_case_pi si, v1, Vptr b ofs := if archi.ptr64 then none else cmp_ptr m c v1 v2
| cmp_case_ip si, Vint n1, v2    := cmp_ptr m c (Vptrofs (ptrofs_of_int si n1)) v2
| cmp_case_ip si, Vptr b ofs, v2 := if archi.ptr64 then none else cmp_ptr m c (Vptr b ofs) v2
| cmp_case_pl,    v1, Vlong n2   := cmp_ptr m c v1 (Vptrofs (ptrofs.of_int64 n2))
| cmp_case_pl,    v1, Vptr b ofs := if archi.ptr64 then cmp_ptr m c v1 (Vptr b ofs) else none
| cmp_case_lp,    Vlong n1,   v2 := cmp_ptr m c (Vptrofs (ptrofs.of_int64 n1)) v2
| cmp_case_lp,    Vptr b ofs, v2 := if archi.ptr64 then cmp_ptr m c v1 v2 else none
| cmp_default,    v1, v2         := sem_binarith
    (λ sg n1 n2, some (val.of_bool ((match sg with Signed := word.cmp | Unsigned := word.cmpu end) c n1 n2)))
    (λ sg n1 n2, some (val.of_bool ((match sg with Signed := word.cmp | Unsigned := word.cmpu end) c n1 n2)))
    (λ n1 n2, some (val.of_bool (float.cmp c n1 n2)))
    (λ n1 n2, some (val.of_bool (float32.cmp c n1 n2)))
    m v1 t1 v2 t2
| _,              _, _           := none
end

/- ** Function applications -/

inductive classify_fun_cases : Type
| fun_case_f (targs : list type) (tres : type) (cc : calling_convention) /- (pointer to) function -/
| fun_default
open classify_fun_cases

def classify_fun : type → classify_fun_cases
| (Tfunction args res cc)              := fun_case_f args res cc
| (Tpointer (Tfunction args res cc) _) := fun_case_f args res cc
| _                                    := fun_default

/- ** Argument of a [switch] statement -/

inductive classify_switch_cases : Type
| switch_case_i
| switch_case_l
| switch_default
open classify_switch_cases

def classify_switch : type → classify_switch_cases
| (Tint _ _ _) := switch_case_i
| (Tlong _ _)  := switch_case_l
| _            := switch_default

def sem_switch_arg (v : val) (ty : type) : option ℤ :=
match classify_switch ty, v with
| switch_case_i, Vint n  := some (unsigned n)
| switch_case_l, Vlong n := some (unsigned n)
| _,             _       := none
end

/- * Combined semantics of unary and binary operators -/

def sem_unary_operation : unary_operation → mem → val → type → option val
| Onotbool  := sem_notbool
| Onotint   := λ_, sem_notint
| Oneg      := λ_, sem_neg
| Oabsfloat := λ_, sem_absfloat

def sem_binary_operation (cenv : composite_env) :
  binary_operation → mem → val → type → val → type → option val
| Oadd := sem_add cenv
| Osub := sem_sub cenv
| Omul := sem_mul
| Omod := sem_mod
| Odiv := sem_div
| Oand := sem_and
| Oor  := sem_or
| Oxor := sem_xor
| Oshl := λ_, sem_shl
| Oshr := λ_, sem_shr
| Oeq  := sem_cmp Ceq
| One  := sem_cmp Cne
| Olt  := sem_cmp Clt
| Ogt  := sem_cmp Cgt
| Ole  := sem_cmp Cle
| Oge  := sem_cmp Cge

def sem_incrdecr (cenv : composite_env) (id : incr_or_decr) (m : mem) (v : val) (ty : type) :=
match id with
| Incr := sem_add cenv m v ty 1 type_int32s
| Decr := sem_sub cenv m v ty 1 type_int32s
end

def incrdecr_type (ty : type) :=
match typeconv ty with
| Tpointer ty a := Tpointer ty a
| Tint sz sg a  := Tint sz sg noattr
| Tlong sg a    := Tlong sg noattr
| Tfloat sz a   := Tfloat sz noattr
| _             := Tvoid
end

/- * Compatibility with extensions and injections -/

section generic_injection

parameters {f : meminj} {m m' : mem}

parameter (valid_pointer_inj :
  ∀ b1 (ofs : ptrofs) b2 delta,
  f b1 = some (b2, delta) →
  valid_pointer m b1 (unsigned ofs) →
  valid_pointer m' b2 (unsigned (ofs + repr delta)))

parameter (weak_valid_pointer_inj :
  ∀ b1 (ofs : ptrofs) b2 delta,
  f b1 = some (b2, delta) →
  weak_valid_pointer m b1 (unsigned ofs) →
  weak_valid_pointer m' b2 (unsigned (ofs + repr delta)))

parameter (weak_valid_pointer_no_overflow :
  ∀ b1 (ofs : ptrofs) b2 delta,
  f b1 = some (b2, delta) →
  weak_valid_pointer m b1 (unsigned ofs) →
  unsigned ofs + unsigned (repr delta : ptrofs) ≤ max_unsigned ptrofs.wordsize)

parameter (valid_different_pointers_inj :
  ∀ b1 b2 (ofs1 ofs2 : ptrofs) b1' delta1 b2' delta2,
  b1 ≠ b2 →
  valid_pointer m b1 (unsigned ofs1) →
  valid_pointer m b2 (unsigned ofs2) →
  f b1 = some (b1', delta1) →
  f b2 = some (b2', delta2) →
  b1' = b2' →
  unsigned (ofs1 + repr delta1) ≠ unsigned (ofs2 + repr delta2))

theorem val_inject_vtrue (f) : inject f Vtrue Vtrue := sorry'

theorem val_inject_vfalse (f) : inject f Vfalse Vfalse := sorry'

theorem val_inject_of_bool (f b) : inject f (val.of_bool b) (val.of_bool b) := sorry'

theorem val_inject_vptrofs (n) : inject f (Vptrofs n) (Vptrofs n) := sorry'

lemma sem_cast_inj {v1 ty1 ty v tv1} :
  sem_cast m v1 ty1 ty = some v →
  inject f v1 tv1 →
  ∃ tv, sem_cast m' tv1 ty1 ty = some tv ∧ inject f v tv := sorry'

lemma bool_val_inj {v ty b tv} :
  bool_val m v ty = some b →
  inject f v tv →
  bool_val m' tv ty = some b := sorry'

lemma sem_unary_operation_inj {op v1 ty v tv1} :
  sem_unary_operation op m v1 ty = some v →
  inject f v1 tv1 →
  ∃ tv, sem_unary_operation op m' tv1 ty = some tv ∧ inject f v tv := sorry'

def optval_self_injects : option val → bool
| (some (Vptr b ofs)) := ff
| _                   := tt

theorem sem_binarith_inject {sem_int sem_long sem_float sem_single v1 t1 v2 t2 v v1' v2'} :
  sem_binarith sem_int sem_long sem_float sem_single m v1 t1 v2 t2 = some v →
  inject f v1 v1' → inject f v2 v2' →
  (∀ sg n1 n2, optval_self_injects (sem_int sg n1 n2)) →
  (∀ sg n1 n2, optval_self_injects (sem_long sg n1 n2)) →
  (∀ n1 n2, optval_self_injects (sem_float n1 n2)) →
  (∀ n1 n2, optval_self_injects (sem_single n1 n2)) →
  ∃ v', sem_binarith sem_int sem_long sem_float sem_single m' v1' t1 v2' t2 = some v' ∧ inject f v v' := sorry'

theorem sem_shift_inject {sem_int sem_long v1 t1 v2 t2 v v1' v2'} :
  sem_shift sem_int sem_long v1 t1 v2 t2 = some v →
  inject f v1 v1' → inject f v2 v2' →
  ∃ v', sem_shift sem_int sem_long v1' t1 v2' t2 = some v' ∧ inject f v v' := sorry'

theorem sem_cmp_ptr_inj {c v1 v2 v tv1 tv2} :
  cmp_ptr m c v1 v2 = some v →
  inject f v1 tv1 →
  inject f v2 tv2 →
  ∃ tv, cmp_ptr m' c tv1 tv2 = some tv ∧ inject f v tv := sorry'

theorem sem_cmp_inj {cmp v1 tv1 ty1 v2 tv2 ty2 v} :
  sem_cmp cmp m v1 ty1 v2 ty2 = some v →
  inject f v1 tv1 →
  inject f v2 tv2 →
  ∃ tv, sem_cmp cmp m' tv1 ty1 tv2 ty2 = some tv ∧ inject f v tv := sorry'

lemma sem_binary_operation_inj {cenv op v1 ty1 v2 ty2 v tv1 tv2} :
  sem_binary_operation cenv op m v1 ty1 v2 ty2 = some v →
  inject f v1 tv1 → inject f v2 tv2 →
  ∃ tv, sem_binary_operation cenv op m' tv1 ty1 tv2 ty2 = some tv ∧ inject f v tv := sorry'

end generic_injection

lemma sem_cast_inject {f v1 ty1 ty m v tv1 tm} :
  sem_cast m v1 ty1 ty = some v →
  inject f v1 tv1 →
  inject f m tm →
  ∃ tv, sem_cast tm tv1 ty1 ty = some tv ∧ inject f v tv := sorry'

lemma sem_unary_operation_inject {f m m' op v1 ty1 v tv1} :
  sem_unary_operation op m v1 ty1 = some v →
  inject f v1 tv1 →
  inject f m m' →
  ∃ tv, sem_unary_operation op m' tv1 ty1 = some tv ∧ inject f v tv := sorry'

lemma sem_binary_operation_inject {f m m' cenv op v1 ty1 v2 ty2 v tv1 tv2} :
  sem_binary_operation cenv op m v1 ty1 v2 ty2 = some v →
  inject f v1 tv1 → inject f v2 tv2 →
  inject f m m' →
  ∃ tv, sem_binary_operation cenv op m' tv1 ty1 tv2 ty2 = some tv ∧ inject f v tv := sorry'

lemma bool_val_inject {f m m' v ty b tv} :
  bool_val m v ty = some b →
  inject f v tv →
  inject f m m' →
  bool_val m' tv ty = some b := sorry'

/- * Some properties of operator semantics -/

/- This section collects some common-sense properties about the type
  classification and semantic functions above.  Some properties are used
  in the CompCert semantics preservation proofs.  Others are not, but increase
  confidence in the specification and its relation with the ISO C99 standard. -/

/- Relation between Boolean value and casting to [_Bool] type. -/

lemma cast_bool_bool_val {v t m} :
  sem_cast m v t (Tint IBool Signed noattr) =
  val.of_bool <$> bool_val m v t := sorry'

/- Relation between Boolean value and Boolean negation. -/

lemma notbool_bool_val {v t m} :
  sem_notbool m v t =
  val.of_bool <$> bnot <$> bool_val m v t := sorry'

/- Properties of values obtained by casting to a given type. -/

section val_casted

inductive val_casted : val → type → Prop
| int (sz si attr n)       : cast_int_int sz si n = n → val_casted (Vint n) (Tint sz si attr)
| float (attr n)           : val_casted (Vfloat n) (Tfloat F64 attr)
| single (attr n)          : val_casted (Vsingle n) (Tfloat F32 attr)
| long (si attr n)         : val_casted (Vlong n) (Tlong si attr)
| ptr_ptr (b ofs ty attr)  : val_casted (Vptr b ofs) (Tpointer ty attr)
| int_ptr (n ty attr)      : ¬ archi.ptr64 → val_casted (Vint n) (Tpointer ty attr)
| ptr_int (b ofs si attr)  : ¬ archi.ptr64 → val_casted (Vptr b ofs) (Tint I32 si attr)
| long_ptr (n ty attr)     : archi.ptr64 → val_casted (Vlong n) (Tpointer ty attr)
| ptr_long (b ofs si attr) : archi.ptr64 → val_casted (Vptr b ofs) (Tlong si attr)
| struct (id attr b ofs)   : val_casted (Vptr b ofs) (Tstruct id attr)
| union (id attr b ofs)    : val_casted (Vptr b ofs) (Tunion id attr)
| void (v)                 : val_casted v Tvoid

theorem cast_int_int_idem (sz sg i) :
  cast_int_int sz sg (cast_int_int sz sg i) = cast_int_int sz sg i := sorry'

lemma cast_val_is_casted {v ty ty' v' m} :
  sem_cast v ty ty' m = some v' → val_casted v' ty' := sorry'

end val_casted

/- As a consequence, casting twice is equivalent to casting once. -/

lemma cast_val_casted {m v ty} :
  val_casted v ty → sem_cast m v ty ty = some v := sorry'

lemma cast_idempotent {m v ty ty' v'} :
  sem_cast m v ty ty' = some v' → sem_cast m v' ty' ty' = some v' := sorry'

/- Relation with the arithmetic conversions of ISO C99, section 6.3.1 -/

section arith_conv

/- This is the ISO C algebra of arithmetic types, without qualifiers.
    [S] stands for "signed" and [U] for "unsigned".  -/

inductive int_type : Type
| Bool
| Char | SChar | UChar
| Short | UShort
| Int | UInt
| Long | ULong
| Longlong | ULonglong
open int_type

inductive arith_type : Type
| I (it : int_type)
| Float
| Double
| Longdouble
open arith_type

instance eq_int_type : decidable_eq int_type := by tactic.mk_dec_eq_instance

def is_unsigned : int_type → bool
| Bool      := tt
| UChar     := tt
| UShort    := tt
| UInt      := tt
| ULong     := tt
| ULonglong := tt
| _         := ff

def unsigned_type : int_type → int_type
| Char     := UChar
| SChar    := UChar
| Short    := UShort
| Int      := UInt
| Long     := ULong
| Longlong := ULonglong
| t        := t

def int_sizeof : int_type → ℕ
| Bool      := 1
| Char      := 1
| SChar     := 1
| UChar     := 1
| Short     := 2
| UShort    := 2
| Int       := 4
| UInt      := 4
| Long      := 4
| ULong     := 4
| Longlong  := 8
| ULonglong := 8

/- 6.3.1.1 para 1: integer conversion rank -/

def rank : int_type → ℕ
| Bool      := 1
| Char      := 2
| SChar     := 2
| UChar     := 2
| Short     := 3
| UShort    := 3
| Int       := 4
| UInt      := 4
| Long      := 5
| ULong     := 5
| Longlong  := 6
| ULonglong := 6

/- 6.3.1.1 para 2: integer promotions, a.k.a. usual unary conversions -/

def integer_promotion (t : int_type) : int_type :=
if rank t < rank Int then Int else t

/- 6.3.1.8: Usual arithmetic conversions, a.k.a. binary conversions.
  This function returns the type to which the two operands must be
  converted. -/

def usual_arithmetic_conversion : arith_type → arith_type → arith_type
  /- First, if the corresponding real type of either operand is long
     double, the other operand is converted, without change of type domain,
     to a type whose corresponding real type is long double. -/
| Longdouble _ := Longdouble
| _ Longdouble := Longdouble
  /- Otherwise, if the corresponding real type of either operand is
     double, the other operand is converted, without change of type domain,
     to a type whose corresponding real type is double. -/
| Double _ := Double
| _ Double := Double
  /- Otherwise, if the corresponding real type of either operand is
     float, the other operand is converted, without change of type domain,
     to a type whose corresponding real type is float. -/
| Float _ := Float
| _ Float := Float
  /- Otherwise, the integer promotions are performed on both operands. -/
| (I i1) (I i2) :=
    let j1 := integer_promotion i1, j2 := integer_promotion i2 in
    /- Then the following rules are applied to the promoted operands:
       If both operands have the same type, then no further conversion
       is needed. -/
    if j1 = j2 then I j1 else
    match is_unsigned j1, is_unsigned j2 with
    /- Otherwise, if both operands have signed integer types or both
       have unsigned integer types, the operand with the type of lesser
       integer conversion rank is converted to the type of the operand with
       greater rank. -/
    | tt, tt := if rank j1 < rank j2 then I j2 else I j1
    | ff, ff := if rank j1 < rank j2 then I j2 else I j1
    | tt, ff :=
    /- Otherwise, if the operand that has unsigned integer type has
       rank greater or equal to the rank of the type of the other operand,
       then the operand with signed integer type is converted to the type of
       the operand with unsigned integer type. -/
        if rank j2 ≤ rank j1 then I j1 else
    /- Otherwise, if the type of the operand with signed integer type
       can represent all of the values of the type of the operand with
       unsigned integer type, then the operand with unsigned integer type is
       converted to the type of the operand with signed integer type. -/
        if int_sizeof j1 < int_sizeof j2 then I j2 else
    /- Otherwise, both operands are converted to the unsigned integer type
       corresponding to the type of the operand with signed integer type. -/
        I (unsigned_type j2)
    | ff, tt :=
    /- Same logic as above, swapping the roles of j1 and j2 -/
        if rank j1 ≤ rank j2 then I j2 else
        if int_sizeof j2 < int_sizeof j1 then I j1 else
        I (unsigned_type j1)
    end

/- Mapping ISO arithmetic types to CompCert types -/

def proj_type : arith_type → type
| (I Bool)      := Tint IBool Unsigned noattr
| (I Char)      := Tint I8 Unsigned noattr
| (I SChar)     := Tint I8 Signed noattr
| (I UChar)     := Tint I8 Unsigned noattr
| (I Short)     := Tint I16 Signed noattr
| (I UShort)    := Tint I16 Unsigned noattr
| (I Int)       := Tint I32 Signed noattr
| (I UInt)      := Tint I32 Unsigned noattr
| (I Long)      := Tint I32 Signed noattr
| (I ULong)     := Tint I32 Unsigned noattr
| (I Longlong)  := Tlong Signed noattr
| (I ULonglong) := Tlong Unsigned noattr
| Float         := Tfloat F32 noattr
| Double        := Tfloat F64 noattr
| Longdouble    := Tfloat F64 noattr

/- Relation between [typeconv] and integer promotion. -/

lemma typeconv_integer_promotion (i) :
  typeconv (proj_type (I i)) = proj_type (I (integer_promotion i)) := sorry'

/- Relation between [classify_binarith] and arithmetic conversion. -/

lemma classify_binarith_arithmetic_conversion (t1 t2) :
  binarith_type (classify_binarith (proj_type t1) (proj_type t2)) =
  proj_type (usual_arithmetic_conversion t1 t2) := sorry'

end arith_conv

end cop


/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.list.lemmas
import Mathlib.Lean3Lib.init.wf

universes u_1

namespace Mathlib

namespace list

-- Note: we can't use the equation compiler here because

-- init.meta.well_founded_tactics uses this file

def qsort.F {α : Type u_1} (lt : α → α → Bool) (x : List α) : ((y : List α) → length y < length x → List α) → List α :=
  sorry

/- This is based on the minimalist Haskell "quicksort".

   Remark: this is *not* really quicksort since it doesn't partition the elements in-place -/

def qsort {α : Type u_1} (lt : α → α → Bool) : List α → List α :=
  well_founded.fix sorry sorry

@[simp] theorem qsort_nil {α : Type u_1} (lt : α → α → Bool) : qsort lt [] = [] := sorry

@[simp] theorem qsort_cons {α : Type u_1} (lt : α → α → Bool) (h : α) (t : List α) : qsort lt (h :: t) =
  (fun (_a : List α × List α) =>
      prod.cases_on _a fun (fst snd : List α) => idRhs (List α) (qsort lt snd ++ h :: qsort lt fst))
    (partition (fun (x : α) => lt h x = tt) t) := sorry


example : let x := 0; x + 5 = 5 := by
  dsimp (config := { zeta := false })
  trace_state
  simp

example : let x := 0; x + 5 = 5 := by
  dsimp

example : let x := 0; x + y = y := by
  dsimp
  trace_state
  rw [Nat.zero_add]

example : let x := 0; x + y = y := by
  dsimp (config := { zeta := false })
  trace_state
  conv => zeta
  trace_state
  rw [Nat.zero_add]


import split_cycle

structure election_profile (χ υ : Type*) :=
(cands : finset χ)
(voters : finset υ)
(Q : υ → χ → χ → Prop)

variables {χ υ : Type*}

def profile_without (prof: election_profile χ υ) (b : χ)
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] : election_profile χ υ :=
  ⟨prof.cands.erase b, prof.voters, prof.Q⟩

lemma mem_prof_of_mem_profile_without {a b: χ} {prof : election_profile χ υ}
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] (h : a ∈ (profile_without prof b).cands) :
  a ∈ prof.cands :=
by simp only [profile_without, ne.def, finset.mem_erase] at h; exact h.2

lemma voters_eq_profile_without (prof : election_profile χ υ) (b: χ)
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] :
  (profile_without prof b).voters = prof.voters := by simp only [profile_without]

lemma Q_eq_profile_without (prof : election_profile χ υ) (b: χ)
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] :
  (profile_without prof b).Q = prof.Q := by simp only [profile_without]

lemma cands_erase_eq_profile_without (prof : election_profile χ υ) (b: χ)
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] :
  (profile_without prof b).cands = prof.cands.erase b := by simp only [profile_without]

lemma profile_without_eq_cands_of_not_mem {b : χ} {prof : election_profile χ υ}
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] (hb : b ∉ prof.cands) :
  (profile_without prof b) = prof :=
begin
  tactic.unfreeze_local_instances,
  cases prof,
  simp only [profile_without, and_true, eq_self_iff_true,
    finset.erase_eq_of_not_mem hb] at *,
end

lemma ne_of_mem_profile_without {a b : χ} {prof : election_profile χ υ}
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ]
  (h : a ∈ (profile_without prof b).cands ) : a ≠ b :=
begin
  simp only [cands_erase_eq_profile_without prof b,
     ne.def, finset.mem_erase] at h,
  exact h.1,
end

lemma profile_without_card {b: χ} (prof : election_profile χ υ) (b_in : b ∈ prof.cands)
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] :
  prof.cands.card.pred = (profile_without prof b).cands.card :=
by rw [cands_erase_eq_profile_without prof b, finset.card_erase_of_mem b_in]

lemma profile_without_card' {b: χ} (prof : election_profile χ υ) (b_in : b ∈ prof.cands)
  [∀ v, decidable_rel (prof.Q v)] [decidable_eq χ] :
  prof.cands.card = (profile_without prof b).cands.card.succ :=
begin
  rw ← profile_without_card prof b_in,
  exact (nat.succ_pred_eq_of_pos (finset.card_pos.2 ⟨b, b_in⟩)).symm,
end

lemma restrict_of_subset {q : χ → χ → Prop} {s t : finset χ} {a b : χ}
  (hst : s ⊆ t) (hq : (restrict q s) a b) : (restrict q t) a b :=
⟨hq.1, hst hq.2.1, hst hq.2.2⟩

lemma restrict_restrict_eq_restrict (q : χ → χ → Prop) (s : finset χ) :
  restrict (restrict q s) s = restrict q s :=
begin
  ext x y, split,
  { rintros ⟨⟨hxy, x_in, y_in⟩, -, -⟩,
    exact ⟨hxy, x_in, y_in⟩, },
  { rintros ⟨hxy, x_in, y_in⟩,
    exact ⟨⟨hxy,x_in,y_in⟩,x_in, y_in⟩, },
end

instance {α : Type*} (s : finset α) : decidable s.nonempty :=
begin
  rw ←finset.card_pos,
  apply_instance,
end

def best_margin (voters : finset υ) (s : finset (χ × χ)) (Q : υ → χ → χ → Prop)
  [∀ v, decidable_rel (Q v)] : ℤ :=
  if hn : s.nonempty
    then s.sup' hn (λ p, margin voters Q p.1 p.2)
  else 0

def uniquely_weighted (voters : finset υ) (cands : finset χ) (Q : υ → χ → χ → Prop)
  [∀ v, decidable_rel (Q v)] : Prop :=
∀ a b a' b' ∈ cands, a ≠ b → a' ≠ b' → (a ≠ a' ∨ b ≠ b') →
margin voters Q a b ≠ margin voters Q a' b'

open_locale classical

noncomputable def stable_voting' (voters : finset υ) (Q : υ → χ → χ → Prop) :
  Π (n : ℕ) (cands : finset χ) (hn : cands.card = n), finset χ
| 0 cands _ := cands
| 1 cands _  := cands
| (n+2) cands hn  :=
let
  -- whether c wins when candidate rem is removed
  still_wins (c rem : χ) : Prop :=
    if rem_prop : rem ∈ cands
      then c ∈ stable_voting' (n+1) (cands.erase rem)
          (by { rw [finset.card_erase_of_mem, hn]; simp [rem_prop], })
    else false,
  viable : finset (χ × χ) := (cands.product cands).filter
      (λ p, still_wins p.1 p.2 ∧ ¬ defeats voters cands Q p.2 p.1)
in finset.image prod.fst $ viable.filter (λ p, (margin voters Q p.1 p.2 = best_margin voters viable Q))

noncomputable def stable_voting : election_profile χ υ → finset χ := λ prof,
stable_voting' prof.voters prof.Q prof.cands.card prof.cands rfl

lemma sv_empty (prof : election_profile χ υ) (hcands : prof.cands.card = 0) :
   stable_voting prof = prof.cands :=
  by simp only [stable_voting, stable_voting', hcands]

lemma sv_singleton (prof : election_profile χ υ) (hcands : prof.cands.card = 1) :
  stable_voting prof = prof.cands :=
by simp only [stable_voting, stable_voting', hcands]

lemma exists_best_margin {s : finset (χ × χ)} (voters : finset υ) (Q : υ → χ → χ → Prop)
  (hs : s.nonempty) :
  ∃ p : χ × χ, p ∈ s ∧ margin voters Q p.1 p.2 = best_margin voters s Q :=
begin
  obtain ⟨b, b_in, hb⟩ := finset.exists_mem_eq_sup' hs
    (λ (p : χ × χ), margin voters Q p.fst p.snd),
  unfold best_margin,
  simp only [hs, dif_pos],
  exact ⟨b, b_in, hb.symm⟩,
end

lemma best_margin_pos_of_exists_pos  {s : finset (χ × χ)} {voters : finset υ} {Q : υ → χ → χ → Prop}
  (p : χ × χ) (p_in : p ∈ s) (h : margin_pos voters Q p.1 p.2) :
  0 < best_margin voters s Q :=
begin
  have s_nonempty : s.nonempty := ⟨p, p_in⟩,
  simp only [best_margin, dif_pos, s_nonempty, finset.lt_sup'_iff],
  exact ⟨p, p_in, h⟩,
end

section trans_gen

lemma trans_gen_of_imp {Q R : χ → χ → Prop}
  (hyp : ∀ a b, Q a b → R a b) :
  ∀ {a b}, relation.trans_gen Q a b → relation.trans_gen R a b :=
begin
  intros a b hab,
  refine relation.trans_gen.trans_induction_on hab
    (λ x y hxy, relation.trans_gen.single $ hyp x y hxy) _,
  intros x y z hxy hyz hxy' hyz',
  exact relation.transitive_trans_gen hxy' hyz',
end

end trans_gen

lemma cyclical_of_subset_cyclical {R : χ → χ → Prop} {s t : finset χ}
  (hst : s ⊆ t) (h_cyc : cyclical (restrict R s)) : cyclical (restrict R t) :=
begin
  rcases h_cyc with ⟨x, hx⟩,
  use x, refine (trans_gen_of_imp (λ a b hab, _ ) hx),
  exact restrict_of_subset hst hab,
end

lemma cyclical_of_serial' :
  ∀ (n : ℕ) (s : finset χ) (R : χ → χ → Prop), n = s.card → s.nonempty →
    (∀ x ∈ s, ∃ y ∈ s, R x y) → cyclical (restrict R s) :=
begin
  intro a, refine nat.case_strong_induction_on a _ _,
  { intros s h R hs, linarith [finset.card_pos.2 hs] },
  { intros n IH s R s_card hs₁ hs₂,
    obtain ⟨x, x_in⟩ := hs₁,
    obtain ⟨y, y_in, hxy⟩ := hs₂ x x_in,
    by_cases x_eq_y : x = y,
    { use x,
      apply relation.trans_gen.single,
      rw ← x_eq_y at hxy,
      exact ⟨hxy, ⟨x_in, x_in⟩⟩, },
    set t : finset χ := s.filter (λ z, relation.trans_gen (restrict R s) y z)
      with ht,
    by_cases x_in' : x ∈ t,
    { use x, simp only [finset.mem_filter] at x_in',
      exact relation.trans_gen.head ⟨hxy,x_in,y_in⟩ x_in'.2, },
    have t_nonempty : t.nonempty,
    { obtain ⟨z, z_in, hyz⟩ := hs₂ y y_in, use z,
      simp only [finset.mem_filter],
      exact ⟨z_in, relation.trans_gen.single ⟨hyz,y_in,z_in⟩⟩, },
    have t_ss : t ⊂ s,
    { rw finset.ssubset_iff_of_subset (finset.filter_subset _ s),
      exact ⟨x, x_in, x_in'⟩, },
    have t_card : t.card ≤ n :=
      by rw [← nat.lt_succ_iff, s_card]; exact finset.card_lt_card t_ss,
    have := IH t.card t_card t (restrict R t) rfl t_nonempty,
    rw restrict_restrict_eq_restrict R t at this,
    refine cyclical_of_subset_cyclical
      (by simp only [finset.filter_subset])
      (this _),
    intros a a_in,
    obtain ⟨b, b_in, hab⟩ := hs₂ a (finset.filter_subset _ s a_in),
    have b_in : b ∈ t,
    { simp only [finset.mem_filter] at ⊢ a_in,
      exact ⟨b_in, relation.trans_gen.tail a_in.2 ⟨hab,a_in.1,b_in⟩⟩, },
    exact ⟨b, b_in, ⟨hab, a_in, b_in⟩⟩ }
end

lemma cyclical_of_serial {s : finset χ} {R : χ → χ → Prop}
  (hs₁ : s.nonempty) (hs₂ : ∀ x ∈ s, ∃ y ∈ s, R x y) :
  cyclical (restrict R s) :=
cyclical_of_serial' s.card s R rfl hs₁ hs₂

/- Random lemmas for natural numbers -/
lemma exists_eq_plus_two (n : ℕ) (hn₀ : ¬ n = 0) (hn₁ : ¬ n = 1) :
  ∃ m, n = m + 2 :=
begin
  cases n with d, { exact (hn₀ nat.nat_zero_eq_zero).elim, },
  induction d with d hd, {exact (hn₁ rfl).elim, },
  use d,
end

lemma ge_two_of_ne_zero_ne_one {n : ℕ} (hn₀ : ¬ n = 0) (hn₁ : ¬ n = 1) :
  2 ≤ n :=
begin
  cases n with d, { exact (hn₀ nat.nat_zero_eq_zero).elim, },
  induction d with d hd, {exact (hn₁ rfl).elim, },
  rw nat.succ_le_iff,
  exact nat.one_lt_succ_succ d,
end

lemma mem_cands_of_mem_sv {prof : election_profile χ υ} {a : χ}
  (a_in : a ∈ stable_voting prof) : a ∈ prof.cands :=
begin
  have card_ne_zero : prof.cands.card ≠ 0,
  { by_contra h,
    simp only [stable_voting, stable_voting', h] at a_in,
    exact finset.card_ne_zero_of_mem a_in h, },
  by_cases hcands : prof.cands.card = 1,
  { rwa (sv_singleton prof hcands) at a_in },
  obtain ⟨n, hn⟩ := exists_eq_plus_two prof.cands.card
    card_ne_zero hcands,
  simp only [stable_voting, stable_voting', hn, exists_prop,
    exists_and_distrib_right, exists_eq_right, finset.mem_image,
    finset.mem_filter, finset.filter_congr_decidable,
    prod.exists, finset.mem_product] at a_in,
  rcases a_in with ⟨b,⟨⟨p_in,hp⟩,ha⟩⟩,
  exact p_in.1,
end

lemma false_iff_filter_empty {α : Type* } (s : finset α) (p : α → Prop) :
  (∀ x ∈ s, ¬ p x) ↔ s.filter p = ∅ :=
begin
  refine ⟨λ h, finset.filter_false_of_mem h, λ h x x_in, _⟩,
  rw ← finset.not_nonempty_iff_eq_empty at h,
  by_contradiction hx,
  refine h _,
  use x,
  simp only [finset.mem_filter],
  exact ⟨x_in, hx⟩,
end

lemma exists_sv_winner' :
  ∀ (n : ℕ) (prof : election_profile χ υ), prof.cands.card = n →
  0 < prof.cands.card → ∃ a, a ∈ stable_voting prof :=
begin
  intro n,
  cases n with d,
  { intros prof hn npos,
    linarith [hn, npos], },
  induction d with d IH,
  { rintros prof hn cpos,
    rw sv_singleton prof hn,
    exact finset.card_pos.1 cpos, },
  intros prof hm cpos,
  set m := d.succ with m_succ,
  obtain ⟨b, b_in⟩ := finset.card_pos.1 cpos,
  have h_erase_card : ∀ z ∈ prof.cands, finset.card (prof.cands.erase z) = m,
  { intros z  z_in,
    rw finset.card_erase_of_mem z_in,
    exact nat.pred_eq_of_eq_succ hm, },
  set prof' : election_profile χ υ :=
    ⟨(prof.cands.erase b),
     prof.voters, prof.Q⟩ with h_prof',
  obtain ⟨a, a_in⟩ := IH prof' (by rw ← h_erase_card b b_in)
    (by rw (h_erase_card b b_in); omega),
  have card_eq_d : prof.cands.card = d + 2 := by rw hm,
  simp only [stable_voting, stable_voting', card_eq_d,
    exists_prop, exists_and_distrib_right, exists_eq_right,
    finset.mem_image, finset.mem_filter, finset.filter_congr_decidable,
    prod.exists, finset.mem_product],
  let still_wins : χ → χ → Prop := λ x₁ x₂,
    if x₂_in : x₂ ∈ prof.cands
      then x₁ ∈ stable_voting' prof.voters prof.Q d.succ
          (prof.cands.erase x₂)
          (by rwa h_erase_card x₂ x₂_in)
    else false,
  set viable_set : finset (χ × χ) := (prof.cands.product prof.cands).filter
    (λ p, still_wins p.1 p.2 ∧ ¬ defeats prof.voters prof.cands prof.Q p.2 p.1) with hvs,
  have viable_nonempty : viable_set.nonempty,
  { by_contra h,
    have foo : (∀ (x : χ × χ),
       x ∈ prof.cands.product prof.cands →
       ¬(λ (p : χ × χ), still_wins p.fst p.snd ∧
          ¬defeats prof.voters prof.cands prof.Q p.snd p.fst) x),
    { push_neg,
      intros x x_in hx₁, by_contra hx₂,
      apply h, use x,
      simp only [hvs,finset.mem_filter],
      exact ⟨x_in, hx₁, hx₂⟩ },
    simp only [and_imp, prod.forall, not_and, not_not, finset.mem_product] at foo,
    have h_ser : ∀ x ∈ prof.cands, ∃ y ∈ prof.cands,
      defeats prof.voters prof.cands prof.Q x y,
    { intros x x_in,
      set prof_rem_x : election_profile χ υ :=
      ⟨(prof.cands.erase x),
       prof.voters, prof.Q⟩ with h_prof_rem_x,
      obtain ⟨y, y_in⟩ := IH prof_rem_x (by rw ← h_erase_card x x_in)
        (by rw (h_erase_card x x_in); exact nat.succ_pos d),
      have y_in' : y ∈ prof.cands :=
        (finset.mem_erase.1 (mem_cands_of_mem_sv y_in)).2,
      suffices : still_wins y x, { exact ⟨y, y_in', foo y x y_in' x_in this⟩, },
      simp only [still_wins, x_in, dif_pos],
      convert y_in,
      rwa h_erase_card x x_in, },
    apply not_acyclical_in'_of_cyclical'_restrict (cyclical'_of_cyclical
      (cyclical_of_serial (finset.card_pos.1 cpos) h_ser)),
    exact defeat_acyclical_in' prof.voters prof.cands prof.Q, },
  obtain ⟨p, p_in, hp⟩ := exists_best_margin prof.voters prof.Q viable_nonempty,
  refine ⟨p.1,p.2, ⟨_, (by rw hp)⟩⟩,
  rw [hvs, finset.mem_filter] at p_in,
  rcases p_in with ⟨hp₁, hp₂, hp₃⟩,
  refine ⟨finset.mem_product.1 hp₁, ⟨ _,hp₃⟩⟩,
  simp only [(finset.mem_product.mp hp₁).right, dif_pos,
    finset.mem_product, still_wins] at hp₂ ⊢,
  exact hp₂,
end

lemma exists_sv_winner (prof : election_profile χ υ) (cpos : 0 < prof.cands.card) :
  ∃ a, a ∈ stable_voting prof := exists_sv_winner' prof.cands.card prof rfl cpos

lemma sv_winner_undefeated' :
  ∀ (n : ℕ) (prof : election_profile χ υ), prof.cands.card = n →
  ∀ a ∈ stable_voting prof, is_undefeated prof.voters prof.cands prof.Q a :=
begin
  intro n,
  cases n with d,
  { intros prof hn a a_in,
    exact (finset.card_ne_zero_of_mem (mem_cands_of_mem_sv a_in) hn).elim, },
  induction d with d IH,
  { intros prof hn a a_in y y_in,
    rw finset.card_le_one.1 (le_of_eq hn)
      a (mem_cands_of_mem_sv a_in) y y_in,
    exact defeat_irreflexive prof.voters prof.cands prof.Q y },
  intros prof cands_card a a_in,
  simp only [stable_voting, stable_voting', cands_card, exists_prop,
    exists_and_distrib_right, exists_eq_right, finset.mem_image,
    finset.mem_filter, finset.filter_congr_decidable, prod.exists,
    finset.mem_product] at a_in,
  rcases a_in with ⟨x,⟨⟨p_in,hp⟩,ha⟩⟩,
  have p_in' : (a,x).snd ∈ prof.cands := by simp only; exact p_in.2,
  rw dif_pos p_in' at hp,
  have h_erase_card : (prof.cands.erase x).card = d.succ :=
    by simpa [finset.card_erase_of_mem p_in.2] using nat.pred_eq_of_eq_succ cands_card,
  set prof' : election_profile χ υ :=
    ⟨(prof.cands.erase x),
     prof.voters, prof.Q⟩ with h_prof',
  have a_in' : a ∈ stable_voting prof',
  { simp only [stable_voting], convert hp.1 },
  refine undefeated_erase _ hp.2,
  simpa using (IH prof' (by convert h_erase_card) a a_in'),
end

lemma sv_winner_undefeated {prof : election_profile χ υ} :
  ∀ a ∈ stable_voting prof, is_undefeated prof.voters prof.cands prof.Q a :=
sv_winner_undefeated' prof.cands.card prof rfl

lemma sv_winner_unique' :
  ∀ (n : ℕ) (prof : election_profile χ υ), prof.cands.card = n →
  0 < prof.cands.card →
  uniquely_weighted prof.voters prof.cands prof.Q →
  (stable_voting prof).card = 1 :=
begin
  intro n,
  cases n with d,
  { intros prof hn cpos,
    linarith [hn, cpos], },
  induction d with d IH,
  { rintros prof hn - -,
    rwa sv_singleton prof hn, },
  set m := d.succ with m_succ,
  intros prof hm cpos h_uniq,
  have card_eq_d : prof.cands.card = d + 2 := by rw hm,
  by_contradiction h_card,
  have hab : ∃ a b ∈ (stable_voting prof), a ≠ b,
  { obtain ⟨a, a_in⟩ := exists_sv_winner prof cpos,
    suffices : 2 ≤ (stable_voting prof).card,
    { obtain ⟨b, b_in, hb⟩ := finset.exists_second_distinct_mem this a_in,
      use ⟨a, b, a_in, b_in, hb.symm⟩, },
    exact ge_two_of_ne_zero_ne_one
      (ne_of_gt (finset.card_pos.2 (exists_sv_winner prof cpos))) h_card, },
  rcases hab with ⟨a, b, a_in, b_in, a_neq_b⟩,
  simp only [stable_voting, stable_voting',
    card_eq_d, exists_prop, exists_and_distrib_right, exists_eq_right,
    finset.mem_image, finset.mem_filter, finset.filter_congr_decidable,
    prod.exists, finset.mem_product] at a_in b_in,
  rcases a_in with ⟨x,⟨⟨p_in,hp⟩,ha⟩⟩, rcases b_in with ⟨y,⟨⟨q_in,hq⟩,hb⟩⟩,
  rw ← ha at hb,
  have h_erase_card : ∀ z ∈ prof.cands, finset.card (prof.cands.erase z) = m,
  { intros z  z_in,
    rw finset.card_erase_of_mem z_in,
    exact nat.pred_eq_of_eq_succ hm, },
  suffices : b ≠ y ∧ a ≠ x,
  { exact (h_uniq b y a x q_in.1 q_in.2 p_in.1 p_in.2 this.1 this.2
      (or.inl a_neq_b.symm)) hb },
  split,
  { have y_in' : (b, y).snd ∈ prof.cands := by simp only; exact q_in.2,
    rw dif_pos y_in' at hq,
    set prof' : election_profile χ υ :=
    ⟨(prof.cands.erase y),
     prof.voters, prof.Q⟩ with h_prof',
    have b_in' : b ∈ stable_voting prof':=
      by simpa [stable_voting, h_erase_card y q_in.2] using hq.1,
    exact (finset.mem_erase.1 (mem_cands_of_mem_sv b_in')).1, },
  { have x_in' : (a, x).snd ∈ prof.cands := by simp only; exact p_in.2,
    rw dif_pos x_in' at hp,
    set prof' : election_profile χ υ :=
    ⟨(prof.cands.erase x),
     prof.voters, prof.Q⟩ with h_prof',
    have a_in' : a ∈ stable_voting prof':=
      by simpa [stable_voting, h_erase_card x p_in.2] using hp.1,
    exact (finset.mem_erase.1 (mem_cands_of_mem_sv a_in')).1, },
end

lemma sv_winner_unique {prof : election_profile χ υ}
  (cpos: 0 < prof.cands.card)
  (h : uniquely_weighted prof.voters prof.cands prof.Q) :
  (stable_voting prof).card = 1 :=
sv_winner_unique' prof.cands.card prof rfl cpos h

noncomputable def stable_voting_alt' (voters : finset υ) (Q : υ → χ → χ → Prop) :
  Π (n : ℕ) (cands : finset χ) (hn : cands.card = n), finset χ
| 0 cands _ := cands
| 1 cands _  := cands
| (n+2) cands hn :=
let
  -- whether c wins when candidate rem is removed
  still_wins (c rem : χ) : Prop :=
    if rem_prop : rem ∈ cands
      then c ∈ stable_voting_alt' (n+1) (cands.erase rem)
          (by { rw [finset.card_erase_of_mem, hn]; simp [rem_prop], })
    else false,
  viable : finset (χ × χ) := (cands.product cands).filter
      (λ p, still_wins p.1 p.2 ∧ is_undefeated voters cands Q p.1)
in finset.image prod.fst $ viable.filter (λ p, (margin voters Q p.1 p.2 = best_margin voters viable Q))

noncomputable def stable_voting_alt (prof : election_profile χ υ)
  [decidable_eq χ] [∀ v, decidable_rel (prof.Q v)] : finset χ :=
stable_voting_alt' prof.voters prof.Q prof.cands.card prof.cands rfl

lemma sv_alt_empty  (prof : election_profile χ υ) (hcands : prof.cands.card = 0) :
   stable_voting_alt prof = prof.cands :=
  by simp only [stable_voting_alt, stable_voting_alt', hcands]

lemma sv_alt_singleton (prof : election_profile χ υ) (hcands : prof.cands.card = 1) :
  stable_voting_alt prof = prof.cands :=
by simp only [stable_voting_alt, stable_voting_alt', hcands]

lemma stable_voting_eq_stable_voting_alt' :
  ∀ (n : ℕ) (prof : election_profile χ υ), prof.cands.card = n →
  stable_voting prof = stable_voting_alt prof :=
begin
  intro n,
  cases n with d,
  { intros prof hn,
     rwa [sv_empty prof hn, sv_alt_empty prof hn], },
  induction d with d IH,
  { intros prof hn,
    rwa [sv_singleton prof hn, sv_alt_singleton prof hn], },
  set m := d.succ with m_succ,
  intros prof hm,
  have card_eq_d : prof.cands.card = d + 2 := by rw hm,
  have h_erase_card : ∀ z ∈ prof.cands, finset.card (prof.cands.erase z) = m,
  { intros z  z_in,
    rw finset.card_erase_of_mem z_in,
    exact nat.pred_eq_of_eq_succ hm, },
  ext a, split,
  { intro a_in,
    have a_undefeated := sv_winner_undefeated a a_in,
    simp only [stable_voting, stable_voting', stable_voting_alt,
      stable_voting_alt', card_eq_d, finset.filter_congr_decidable,
      exists_prop, exists_and_distrib_right, exists_eq_right,
      finset.mem_image, finset.mem_filter, prod.exists, finset.mem_product] at ⊢ a_in,
    rcases a_in with ⟨x,⟨⟨p_in,hp⟩,ha⟩⟩,
    refine ⟨x,⟨⟨p_in,⟨_,a_undefeated⟩⟩,_⟩⟩,
    { have x_in' : (a, x).snd ∈ prof.cands := by simp only; exact p_in.2,
      simp only [x_in', dif_pos] at ⊢ hp,
      set prof' : election_profile χ υ :=
        ⟨(prof.cands.erase x),
         prof.voters, prof.Q⟩ with h_prof',
      suffices : a ∈ stable_voting_alt prof',
      { simp only [stable_voting_alt, h_erase_card x p_in.right] at this,
        exact this, },
      have prof'_card : prof'.cands.card = m
        := by simp only [h_erase_card x p_in.2],
      simpa only [← IH prof' prof'_card,
        stable_voting, h_erase_card x p_in.2] using hp.1, },
    { convert ha, ext p,
      simp only [eq_self_iff_true] at *,
      sorry, }, },
  { sorry, },
end

class voting_method {χ υ : Type*} (M : election_profile χ υ → finset χ) : Prop :=
(winners_subset : ∀ prof : election_profile χ υ, M prof ⊆ prof.cands)
(winners_nonempty : ∀ prof : election_profile χ υ, prof.cands.nonempty → (M prof).nonempty)

export voting_method (winners_subset winners_nonempty)

lemma voting_method_singleton {prof : election_profile χ υ} {a : χ}
  (M : election_profile χ υ → finset χ) [voting_method M] (h : prof.cands = {a}) :
  M prof = {a} :=
begin
  have : M prof ⊆ prof.cands := voting_method.winners_subset prof,
  rw [h, finset.subset_singleton_iff] at this,
  cases this,
  { exfalso, refine (voting_method.winners_nonempty prof _).ne_empty this,
    simpa only [h] using finset.singleton_nonempty a, },
  { exact this, },
end

instance : voting_method (stable_voting : election_profile χ υ → finset χ) :=
⟨λ prof a a_in, mem_cands_of_mem_sv a_in,
 λ prof h, exists_sv_winner prof $ finset.card_pos.2 h⟩

def is_stable (M : election_profile χ υ → finset χ)
  (prof : election_profile χ υ) [∀ v, decidable_rel (prof.Q v)] (a: χ) : Prop :=
∃ b ∈ prof.cands, margin_pos prof.voters prof.Q a b ∧ a ∈ M (profile_without prof b)

def is_stable_for_winners_wt (M : election_profile χ υ → finset χ) : Prop :=
∀ (prof: election_profile χ υ),
(∃ x, is_stable M prof x) → ∀ a ∈ (M prof), is_stable M prof a

theorem sv_stable_for_winners_wt :
  is_stable_for_winners_wt (stable_voting : election_profile χ υ → finset χ) :=
begin
  rintros prof ⟨x, ⟨y, y_in, hy₁, hy₂⟩⟩ a a_in',
  have x_in : x ∈ prof.cands :=
    mem_prof_of_mem_profile_without (mem_cands_of_mem_sv hy₂),
  obtain ⟨d, hd⟩ : ∃ d : ℕ, prof.cands.card = d + 2,
  { use (profile_without prof y).cands.card.pred,
    rw [profile_without_card' prof y_in, ← nat.pred_eq_succ_iff, nat.pred_succ],
    refine (nat.succ_pred_eq_of_pos _).symm,
    rw finset.card_pos,
    exact ⟨x, mem_cands_of_mem_sv hy₂⟩, },
  have h_erase_card : ∀ z ∈ prof.cands, finset.card (prof.cands.erase z) = d.succ,
  { intros z  z_in,
    rw finset.card_erase_of_mem z_in,
    exact nat.pred_eq_of_eq_succ hd, },
  let still_wins : χ → χ → Prop := λ x₁ x₂,
    if x₂_in : x₂ ∈ prof.cands
      then x₁ ∈ stable_voting' prof.voters prof.Q d.succ
          (prof.cands.erase x₂)
          (by rwa h_erase_card x₂ x₂_in)
    else false,
  set viable_set : finset (χ × χ) := (prof.cands.product prof.cands).filter
    (λ p, still_wins p.1 p.2 ∧ ¬ defeats prof.voters prof.cands prof.Q p.2 p.1) with hvs,
  simp only [stable_voting, stable_voting', hd, exists_prop,
    exists_and_distrib_right, exists_eq_right, finset.mem_image,
    finset.mem_filter, finset.filter_congr_decidable,
    prod.exists, finset.mem_product] at a_in',
  rcases a_in' with ⟨b,⟨⟨⟨a_in,b_in⟩,hp⟩,hb⟩⟩,
  refine ⟨b, b_in, ⟨_,_⟩⟩,
  { unfold margin_pos, rw hb,
    refine best_margin_pos_of_exists_pos (x,y) _ (by convert hy₁),
    have xy_in : (x,y).snd ∈ prof.cands := by simpa,
    simp only [finset.mem_filter, finset.mem_product,
      dif_pos, xy_in, and_true, stable_voting, profile_without] at ⊢ hy₂,
    refine ⟨x_in, _, not_defeat_of_margin_pos prof.cands hy₁,⟩,
    convert hy₂,
    exact (h_erase_card y y_in).symm, },
  { suffices : (a,b).snd ∈ prof.cands,
    { simp only [dif_pos, this, stable_voting] at hp ⊢,
      convert hp.1 using 2,
      rw [cands_erase_eq_profile_without prof b, h_erase_card b b_in], },
    simpa, },
end

def condorcet_winner (prof : election_profile χ υ) (x : χ) : Prop :=
x ∈ prof.cands ∧ ∀ y ∈ prof.cands, y ≠ x → margin_pos prof.voters prof.Q x y

def condorcet_criterion (M : election_profile χ υ → finset χ) : Prop :=
  ∀ (prof : election_profile χ υ) (x : χ),
    condorcet_winner prof x → M prof = {x}

lemma condorcet_winner_profile_without {prof : election_profile χ υ} {x b : χ}
  (h : condorcet_winner prof x) (hb : x ≠ b):
  condorcet_winner (profile_without prof b) x :=
⟨finset.mem_erase_of_ne_of_mem hb h.1, λ y y_in hxy, h.2 y (finset.mem_of_mem_erase y_in) hxy⟩

lemma not_margin_pos_of_condorcet_winner {prof : election_profile χ υ} {x b: χ}
  (h : condorcet_winner prof x) (b_in : b ∈ prof.cands) : ¬ margin_pos prof.voters prof.Q b x :=
begin
  by_cases hb : b = x,
  { rw hb, exact not_margin_pos_self prof.voters prof.Q x },
  { exact not_margin_pos_of_reverse (h.2 b b_in hb) }
end

theorem condorcet_of_stability_for_winners_wt (M : election_profile χ υ → finset χ)
  [hM : voting_method M] : is_stable_for_winners_wt M → condorcet_criterion M :=
begin
  intros h_stable p y hy,
  suffices : ∀ (n : ℕ) (prof : election_profile χ υ) (x : χ), prof.cands.card = n →
    condorcet_winner prof x → M prof = {x},
  { exact this p.cands.card p y rfl hy, },
  intro n, induction n with n IH,
  { intros prof x h_card h_cond, exfalso,
    exact (finset.card_ne_zero_of_mem h_cond.1) h_card, },
  intros prof x h_card h_cond,
  by_cases h_cands : prof.cands = {x}, { exact voting_method_singleton M h_cands, },
  have hx₁ : ∀ a ∈ prof.cands, x ≠ a → M (profile_without prof a) = {x},
  { intros a a_in hax,
    refine IH (profile_without prof a) x _ (condorcet_winner_profile_without h_cond hax),
    rw ← profile_without_card prof a_in,
    exact nat.pred_eq_of_eq_succ h_card, },
  have hx₂ : ∀ a ∈ prof.cands, is_stable M prof a → a = x,
  { rintros a a_in ⟨c, c_in, hc₁, hc₂⟩,
    have x_ne_c : x ≠ c,
    { by_contra h, rw ← h at hc₁,
      exact (not_margin_pos_of_condorcet_winner h_cond a_in) hc₁ },
    rwa [← finset.mem_singleton, ← hx₁ c c_in x_ne_c] },
  have hx₃ : is_stable M prof x,
  { obtain ⟨b, b_in, hb⟩ :=
      finset.exists_distinct_mem_of_ne_singleton ⟨x, h_cond.1⟩ h_cands,
    refine ⟨b,b_in, h_cond.2 b b_in hb, _⟩,
    simp only [hx₁ b b_in hb.symm, finset.mem_singleton], },
  have hx₄ : ∀ a ∈ M prof, a = x,
  { intros c c_in,
    exact hx₂ c (voting_method.winners_subset prof c_in) (h_stable prof ⟨x, hx₃⟩ c c_in), },
  rw finset.eq_singleton_iff_unique_mem,
  refine ⟨_, hx₄⟩,
  obtain ⟨z, hz⟩ : (M prof).nonempty :=
    voting_method.winners_nonempty prof (finset.card_pos.1 (by omega)),
  rwa ← hx₄ z hz,
end

theorem sv_condorcet_criterion :
  condorcet_criterion (stable_voting : election_profile χ υ → finset χ) :=
condorcet_of_stability_for_winners_wt stable_voting sv_stable_for_winners_wt

noncomputable def smith_set (prof: election_profile χ υ) : finset χ :=
{ x ∈ prof.cands | ∀ y ∈ prof.cands,
   relation.trans_gen (margin_nonneg prof.voters prof.Q) x y }

def smith_criterion (M : election_profile χ υ → finset χ) : Prop :=
∀ (prof : election_profile χ υ) (x : χ), x ∈ M prof → x ∈ smith_set prof

lemma smith_set_subset (prof : election_profile χ υ) : smith_set prof ⊆ prof.cands :=
begin
  intros x x_in,
  simp only [smith_set, finset.sep_def, finset.mem_filter] at x_in,
  exact x_in.1,
end

lemma smith_set_singleton {prof : election_profile χ υ} {a : χ} (h : prof.cands = {a}) :
  smith_set prof = {a} :=
begin
  ext x, split,
  { intro x_in,
    simp only [smith_set, finset.sep_def, finset.mem_filter] at x_in,
    rw h at x_in,
    exact x_in.1, },
  { simp only [smith_set, finset.sep_def, finset.mem_singleton, finset.mem_filter],
    intro hx, split,
    { rw [h,hx],
      exact finset.mem_singleton_self a, },
    { intros y y_in,
      apply relation.trans_gen.single,
      have hy : y = a := by rwa [h,finset.mem_singleton] at y_in,
      rw [hx, hy],
      exact margin_nonneg_self prof.voters prof.Q a} },
end

lemma smith_set_of_profile_without_not_condorcet {prof : election_profile χ υ} {a b : χ}
  (ha : a ∈ smith_set (profile_without prof b)) (hb : ¬ condorcet_winner prof b) :
  a ∈ smith_set prof :=
begin
  by_cases b_in : b ∉ prof.cands, { rwa profile_without_eq_cands_of_not_mem b_in at ha, },
  simp only [condorcet_winner, exists_prop, not_and, ne.def, not_forall, not_not] at b_in hb,
  obtain ⟨x, x_in, hx₁, hx₂⟩ := hb b_in,
  rw ← margin_nonneg_iff_not_margin_pos prof.voters prof.Q x at hx₂,
  simp only [smith_set, finset.sep_def, finset.mem_filter,
    voters_eq_profile_without prof b, Q_eq_profile_without prof b] at ha ⊢,
  refine ⟨finset.mem_of_mem_erase ha.1, _⟩,
  intros y y_in,
  by_cases hyb : y = b,
  { rw ← hyb at hx₂,
    refine relation.trans_gen.tail (ha.2 x _) hx₂,
    rw [cands_erase_eq_profile_without prof b, finset.mem_erase],
    exact ⟨hx₁, x_in⟩, },
  { apply ha.2 y,
    rw [cands_erase_eq_profile_without prof b, finset.mem_erase],
    exact ⟨hyb, y_in⟩, },
end

theorem sv_smith_criterion :
  smith_criterion (stable_voting : election_profile χ υ → finset χ) :=
begin
  intros p z hz,
  suffices : ∀ (n : ℕ) (prof : election_profile χ υ) (x : χ), prof.cands.card = n →
    x ∈ stable_voting prof → x ∈ smith_set prof,
  { exact this p.cands.card p z rfl hz },
  intro n,
  cases n with d,
  { intros prof x h_card x_in', exfalso,
    exact (finset.nonempty.ne_empty ⟨x,mem_cands_of_mem_sv x_in'⟩)
      (finset.card_eq_zero.1 h_card), },
  induction d with d IH,
  { intros prof x h_card x_in',
    obtain ⟨a, ha⟩ := finset.card_eq_one.1 h_card,
    rw [sv_singleton prof h_card, ha] at x_in',
    rwa smith_set_singleton ha, },
  set m := d.succ with m_succ,
  intros prof x hm x_in,
  have card_eq_d : prof.cands.card = d + 2 := by rw hm,
  have h_erase_card : ∀ z ∈ prof.cands, finset.card (prof.cands.erase z) = m,
  { intros z  z_in,
    rw finset.card_erase_of_mem z_in,
    exact nat.pred_eq_of_eq_succ hm, },
  let x_in' := x_in,
  simp only [stable_voting, stable_voting', card_eq_d, exists_prop,
    exists_and_distrib_right, exists_eq_right, finset.mem_image,
    finset.mem_filter, finset.filter_congr_decidable, prod.exists, finset.mem_product] at x_in,
  rcases x_in with ⟨b,⟨⟨⟨x_in,b_in⟩,hp⟩,hx⟩⟩,
  have xb_in : (x,b).snd ∈ prof.cands := by simpa,
  have x_prof_without : x ∈ stable_voting (profile_without prof b),
  { simp only [stable_voting, profile_without, h_erase_card b b_in, dif_pos, xb_in] at hp ⊢,
    exact hp.1, },
  refine smith_set_of_profile_without_not_condorcet
    (IH (profile_without prof b) x _ x_prof_without) _,
  { rw [cands_erase_eq_profile_without prof b, h_erase_card b b_in], },
  { by_contra hb,
    rw [sv_condorcet_criterion prof b hb, finset.mem_singleton] at x_in',
    exact (ne_of_mem_profile_without (mem_cands_of_mem_sv x_prof_without)) x_in', },
end