Library QedkConcrete.nativelistbounds

Invariants through native point-list parsing and accumulation

From Stdlib Require Import List ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import QedkConcrete.modexpoutputs QedkConcrete.precompileoutputs
  QedkConcrete.nativefieldbounds.
Set Default Goal Selector "!".

Lemma native_list_values {A : Set}
    (P : A → Prop) count (element : PC.t A) :
  (0 ≤ count)%Z →
  nativeEnsures P element →
  nativeEnsures (Forall P) (@PC.list_value A count element).
Proof.
  intros Hcount Helement. unfold PC.list_value.
  change (nativeEnsures (Forall P) (PC.List.sequence
    (@OCamlList.init _ (Opaque.legacy_witness (@PC._rocq_fallback_list_value_0 A))
      count (fun _ ⇒ element)))).
  unfold OCamlList.init. rewrite (proj2 (Z.ltb_ge count 0) Hcount).
  generalize (Z.to_nat count), 0%Z. intros n. induction n; intro start.
  - apply native_ensures_return. constructor.
  - cbn [OCamlList.init_nat_aux PC.List.sequence Monad.Make.List.sequence].
    eapply native_ensures_bind; [exact Helement|].
    intros head Hhead. eapply native_ensures_bind; [apply IHn|].
    intros tail Htail. apply native_ensures_return. constructor; assumption.
Qed.

Lemma native_pair_left {A B : Set} (P : A → Prop) (left : PC.t A) (right : PC.t B) :
  nativeEnsures P left → nativeEnsures (fun pair ⇒ P (fst pair)) (PC.pair_value left right).
Proof.
  intro Hleft. unfold PC.pair_value. eapply native_ensures_bind; [exact Hleft|].
  intros l Hl. apply native_ensures_any; intro r. apply native_ensures_return; exact Hl.
Qed.

Lemma native_fold_preserves {A B : Set} (P : A → Prop) (Q : B → Prop)
    (step : B → A → B) values initial :
  (∀ accumulator value, Q accumulator → P value → Q (step accumulator value)) →
  Forall P values → Q initial → Q (PC.List.fold_left step initial values).
Proof.
  intros Hstep Hall. revert initial. induction Hall as [|head tail Hhead Htail IH]; intro initial.
  - exact (fun H ⇒ H).
  - intro Hinitial. apply IH, Hstep; assumption.
Qed.