stringmap.v 2.4 KB
 Robbert Krebbers committed Dec 22, 2015 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 ``````(* Copyright (c) 2012-2015, Robbert Krebbers. *) (* This file is distributed under the terms of the BSD license. *) (** This files implements an efficient implementation of finite maps whose keys range over Coq's data type of strings [string]. The implementation uses radix-2 search trees (uncompressed Patricia trees) as implemented in the file [pmap] and guarantees logarithmic-time operations. *) Require Export prelude.fin_maps prelude.pretty. Require Import prelude.gmap. Notation stringmap := (gmap string). Notation stringset := (gset string). (** * Generating fresh strings *) Local Open Scope N_scope. Let R {A} (s : string) (m : stringmap A) (n1 n2 : N) := n2 < n1 ∧ is_Some (m !! (s +:+ pretty (n1 - 1))). Lemma fresh_string_step {A} s (m : stringmap A) n x : m !! (s +:+ pretty n) = Some x → R s m (1 + n) n. Proof. split; [lia|]. replace (1 + n - 1) with n by lia; eauto. Qed. Lemma fresh_string_R_wf {A} s (m : stringmap A) : wf (R s m). Proof. induction (map_wf m) as [m _ IH]. intros n1; constructor; intros n2 [Hn Hs]. specialize (IH _ (delete_subset m (s +:+ pretty (n2 - 1)) Hs) n2). cut (n2 - 1 < n2); [|lia]. clear n1 Hn Hs; revert IH; generalize (n2 - 1). intros n1. induction 1 as [n2 _ IH]; constructor; intros n3 [??]. apply IH; [|lia]; split; [lia|]. by rewrite lookup_delete_ne by (intros ?; simplify_equality'; lia). Qed. Definition fresh_string_go {A} (s : string) (m : stringmap A) (n : N) (go : ∀ n', R s m n' n → string) : string := let s' := s +:+ pretty n in match Some_dec (m !! s') with | inleft (_↾Hs') => go (1 + n)%N (fresh_string_step s m n _ Hs') | inright _ => s' end. Definition fresh_string {A} (m : stringmap A) (s : string) : string := match m !! s with | None => s | Some _ => Fix_F _ (fresh_string_go s m) (wf_guard 32 (fresh_string_R_wf s m) 0) end. Lemma fresh_string_fresh {A} (m : stringmap A) s : m !! fresh_string m s = None. Proof. unfold fresh_string. destruct (m !! s) as [a|] eqn:Hs; [clear a Hs|done]. generalize 0 (wf_guard 32 (fresh_string_R_wf s m) 0); revert m. fix 3; intros m n [?]; simpl; unfold fresh_string_go at 1; simpl. destruct (Some_dec (m !! _)) as [[??]|?]; auto. Qed. Definition fresh_string_of_set (X : stringset) (s : string) : string := fresh_string (mapset.mapset_car X) s. Lemma fresh_string_of_set_fresh (X : stringset) s : fresh_string_of_set X s ∉ X. Proof. apply eq_None_ne_Some, fresh_string_fresh. Qed.``````