list_reverse.v 1.71 KB
Newer Older
1
(** Correctness of in-place list reversal *)
2 3
From iris.program_logic Require Export weakestpre hoare.
From iris.heap_lang Require Export lang.
4 5
From iris.proofmode Require Export tactics.
From iris.heap_lang Require Import proofmode notation.
6
Set Default Proof Using "Type".
7 8

Section list_reverse.
9
Context `{!heapG Σ}.
10 11
Implicit Types l : loc.

12
Fixpoint is_list (hd : val) (xs : list val) : iProp Σ :=
13
  match xs with
Ralf Jung's avatar
Ralf Jung committed
14 15
  | [] => hd = NONEV
  | x :: xs =>  l hd', hd = SOMEV #l  l  (x,hd')  is_list hd' xs
16 17 18 19 20 21 22 23 24 25 26 27 28
  end%I.

Definition rev : val :=
  rec: "rev" "hd" "acc" :=
    match: "hd" with
      NONE => "acc"
    | SOME "l" =>
       let: "tmp1" := Fst !"l" in
       let: "tmp2" := Snd !"l" in
       "l" <- ("tmp1", "acc");;
       "rev" "tmp2" "hd"
    end.

29
Lemma rev_acc_wp hd acc xs ys (Φ : val  iProp Σ) :
30 31 32
  is_list hd xs - is_list acc ys -
    ( w, is_list w (reverse xs ++ ys) - Φ w) -
  WP rev hd acc {{ Φ }}.
33
Proof.
34
  iIntros "Hxs Hys HΦ".
35
  iLöb as "IH" forall (hd acc xs ys Φ). wp_rec. wp_let.
36 37 38 39 40 41 42 43 44
  destruct xs as [|x xs]; iSimplifyEq.
  - wp_match. by iApply "HΦ".
  - iDestruct "Hxs" as (l hd') "(% & Hx & Hxs)"; iSimplifyEq.
    wp_match. wp_load. wp_proj. wp_let. wp_load. wp_proj. wp_let. wp_store.
    iApply ("IH" $! hd' (SOMEV #l) xs (x :: ys) with "Hxs [Hx Hys]"); simpl.
    { iExists l, acc; by iFrame. }
    iIntros (w). rewrite cons_middle assoc -reverse_cons. iApply "HΦ".
Qed.

45
Lemma rev_wp hd xs (Φ : val  iProp Σ) :
46 47
  is_list hd xs - ( w, is_list w (reverse xs) - Φ w) -
  WP rev hd (InjL #()) {{ Φ }}.
48
Proof.
49 50 51
  iIntros "Hxs HΦ".
  iApply (rev_acc_wp hd NONEV xs [] with "Hxs [%]")=> //.
  iIntros (w). rewrite right_id_L. iApply "HΦ".
52 53
Qed.
End list_reverse.