Section LIST2.
Context {cs: compspecs}.
Context  {list_structid: ident} {list_link: ident} {list_token: share -> val -> mpred}.
Fixpoint lseg (ls: listspec list_structid list_link list_token) (dsh psh: share)
(contents: list (val * elemtype ls)) (x z: val) : mpred :=
match contents with
| (p,h)::hs => !! (p=x /\ ~ptr_eq x z) &&
EX y:val,  !! is_pointer_or_null y &&
list_token dsh x * list_cell ls dsh h x
* field_at psh list_struct (StructField list_link ::nil)
(valinject (nested_field_type list_struct (StructField list_link :: nil)) y) x
* lseg ls dsh psh hs y z
| nil => !! (ptr_eq x z) && emp
end.
Definition lseg_cons (ls: listspec list_structid list_link list_token) dsh psh (l: list (val * elemtype ls)) (x z: val) : mpred :=
!! (~ ptr_eq x z) &&
EX h:(elemtype ls), EX r:list (val * elemtype ls), EX y:val,
!!(l=(x,h)::r  /\ is_pointer_or_null y) &&
list_token dsh x * list_cell ls dsh h x *
field_at psh list_struct (StructField list_link :: nil) (valinject (nested_field_type list_struct (StructField list_link :: nil)) y) x *
lseg ls dsh psh r y z.
intros. rewrite lseg_unroll.
apply pred_ext. apply orp_left; auto.
rewrite andp_assoc.
do 2 (apply derives_extract_prop; intro).
congruence.
apply orp_right2. auto.
Qed.

Lemma unfold_lseg_cons (ls: listspec list_structid list_link list_token):
forall P Q1 Q R e dsh psh s,
PROPx P (LOCALx (Q1::Q) (SEPx (lseg ls dsh psh s e nullval :: R))) |--
!! (typed_true (tptr list_struct) e) ->
PROPx P (LOCALx (Q1::Q) (SEPx (lseg ls dsh psh s e nullval :: R))) |--
EX hryp: elemtype ls * list (val * elemtype ls) * val * val,
match hryp with (h,r,y,p) =>
!! (s=(p,h)::r /\ is_pointer_or_null y) &&
!! (p=e)&&
PROPx P (LOCALx Q
(SEPx (list_token dsh e :: list_cell ls dsh h e ::
field_at psh list_struct (StructField list_link :: nil) (valinject (nested_field_type list_struct (StructField list_link :: nil)) y) e ::
lseg ls dsh psh r y nullval ::
R)))
end.