file_name
stringlengths
5
52
name
stringlengths
4
95
original_source_type
stringlengths
0
23k
source_type
stringlengths
9
23k
source_definition
stringlengths
9
57.9k
source
dict
source_range
dict
file_context
stringlengths
0
721k
dependencies
dict
opens_and_abbrevs
listlengths
2
94
vconfig
dict
interleaved
bool
1 class
verbose_type
stringlengths
1
7.42k
effect
stringclasses
118 values
effect_flags
sequencelengths
0
2
mutual_with
sequencelengths
0
11
ideal_premises
sequencelengths
0
236
proof_features
sequencelengths
0
1
is_simple_lemma
bool
2 classes
is_div
bool
2 classes
is_proof
bool
2 classes
is_simply_typed
bool
2 classes
is_type
bool
2 classes
partial_definition
stringlengths
5
3.99k
completed_definiton
stringlengths
1
1.63M
isa_cross_project_example
bool
1 class
Alg.fst
Alg.test_try_with2
val test_try_with2 (f: (unit -> Alg int [Raise; Write])) : Alg int [Raise; Write]
val test_try_with2 (f: (unit -> Alg int [Raise; Write])) : Alg int [Raise; Write]
let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 14, "end_line": 363, "start_col": 0, "start_line": 361 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg Prims.int) -> Alg.Alg Prims.int
Alg.Alg
[]
[]
[ "Prims.unit", "Prims.int", "Prims.Cons", "Alg.op", "Alg.Raise", "Alg.Write", "Prims.Nil", "Alg.try_with" ]
[]
false
true
false
false
false
let test_try_with2 (f: (unit -> Alg int [Raise; Write])) : Alg int [Raise; Write] =
let g () : Alg int [] = 42 in try_with f g
false
Alg.fst
Alg.handle_raise
val handle_raise (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) (g: (unit -> Alg a labs)) : Alg a labs
val handle_raise (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) (g: (unit -> Alg a labs)) : Alg a labs
let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ())
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 34, "end_line": 538, "start_col": 0, "start_line": 536 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg a) -> g: (_: Prims.unit -> Alg.Alg a) -> Alg.Alg a
Alg.Alg
[]
[]
[ "Prims.list", "Alg.op", "Prims.unit", "Prims.Cons", "Alg.Raise", "Alg.handle_one", "Alg.op_inp", "Alg.op_out" ]
[]
false
true
false
false
false
let handle_raise #a #labs (f: (unit -> Alg a (Raise :: labs))) (g: (unit -> Alg a labs)) : Alg a labs =
handle_one f (fun _ _ -> g ())
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.arrow
val arrow : a: Type -> b: (_: a -> Type) -> Type
let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x)
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 56, "end_line": 41, "start_col": 0, "start_line": 41 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: (_: a -> Type) -> Type
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
true
let arrow (a: Type) (b: (a -> Type)) =
x: a -> Tot (b x)
false
Alg.fst
Alg.lattice_put_repr
val lattice_put_repr (s: state) : L.repr unit [L.WR]
val lattice_put_repr (s: state) : L.repr unit [L.WR]
let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 17, "end_line": 764, "start_col": 0, "start_line": 763 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ())
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
s: Alg.state -> Lattice.repr Prims.unit [Lattice.WR]
Prims.Tot
[ "total" ]
[]
[ "Alg.state", "Lattice.put", "Prims.unit", "Lattice.repr", "Prims.Cons", "Lattice.eff_label", "Lattice.WR", "Prims.Nil" ]
[]
false
false
false
true
false
let lattice_put_repr (s: state) : L.repr unit [L.WR] =
reify (L.put s)
false
Alg.fst
Alg.handler_raise
val handler_raise (#a: _) : handler [Raise; Write; Read] (option a & state) [Write; Read]
val handler_raise (#a: _) : handler [Raise; Write; Read] (option a & state) [Write; Read]
let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 15, "end_line": 556, "start_col": 0, "start_line": 552 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ())
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Alg.handler [Alg.Raise; Alg.Write; Alg.Read] (FStar.Pervasives.Native.option a * Alg.state) [Alg.Write; Alg.Read]
Prims.Tot
[ "total" ]
[]
[ "Alg.op", "FStar.List.Tot.Base.memP", "Prims.Cons", "Alg.Raise", "Alg.Write", "Alg.Read", "Prims.Nil", "Alg.op_inp", "Alg.op_out", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.option", "Alg.state", "FStar.Pervasives.Native.Mktuple2", "Prims.int", "FStar.Pervasives.Native.None", "Alg.get", "Alg.defh", "Alg.handler_op", "Alg.handler" ]
[]
false
false
false
true
false
let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] =
function | Raise -> (fun i k -> (None, get ())) | _ -> defh
false
Alg.fst
Alg.handle_read'
val handle_read' (#a #labs: _) (f: (unit -> Alg a (Read :: labs))) (s: state) : Alg a labs
val handle_read' (#a #labs: _) (f: (unit -> Alg a (Read :: labs))) (s: state) : Alg a labs
let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 33, "end_line": 542, "start_col": 0, "start_line": 540 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ())
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg a) -> s: Alg.state -> Alg.Alg a
Alg.Alg
[]
[]
[ "Prims.list", "Alg.op", "Prims.unit", "Prims.Cons", "Alg.Read", "Alg.state", "Alg.handle_one", "Alg.op_inp", "Alg.op_out" ]
[]
false
true
false
false
false
let handle_read' #a #labs (f: (unit -> Alg a (Read :: labs))) (s: state) : Alg a labs =
handle_one f (fun _ k -> k s)
false
Alg.fst
Alg.__catchST1_aux
val __catchST1_aux (#a #labs: _) (f: tree a (Read :: Write :: labs)) : tree (state -> tree (a & state) labs) labs
val __catchST1_aux (#a #labs: _) (f: tree a (Read :: Write :: labs)) : tree (state -> tree (a & state) labs) labs
let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 57, "end_line": 395, "start_col": 0, "start_line": 388 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: Alg.tree a (Alg.Read :: Alg.Write :: labs) -> Alg.tree (_: Alg.state -> Alg.tree (a * Alg.state) labs) labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "Alg.tree", "Prims.Cons", "Alg.Read", "Alg.Write", "Alg.handle_tree", "Alg.state", "FStar.Pervasives.Native.tuple2", "Alg.Return", "FStar.Pervasives.Native.Mktuple2", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.bind", "Alg.Op", "Alg.handler_tree_op" ]
[]
false
false
false
false
false
let __catchST1_aux #a #labs (f: tree a (Read :: Write :: labs)) : tree (state -> tree (a & state) labs) labs =
handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function | Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k)
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.feq
val feq : f: FStar.FunctionalExtensionality.arrow a b -> g: FStar.FunctionalExtensionality.arrow a b -> Prims.logical
let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 100, "end_line": 48, "start_col": 0, "start_line": 48 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: FStar.FunctionalExtensionality.arrow a b -> g: FStar.FunctionalExtensionality.arrow a b -> Prims.logical
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow", "Prims.l_Forall", "Prims.eq2", "Prims.logical" ]
[]
false
false
false
false
true
let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) =
forall x. {:pattern (f x)\/(g x)} f x == g x
false
Alg.fst
Alg.handle_st
val handle_st (a: Type) (labs: ops) (f: (unit -> Alg a (Write :: Read :: labs))) (s0: state) : Alg a labs
val handle_st (a: Type) (labs: ops) (f: (unit -> Alg a (Write :: Read :: labs))) (s0: state) : Alg a labs
let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 61, "end_line": 496, "start_col": 0, "start_line": 491 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> labs: Alg.ops -> f: (_: Prims.unit -> Alg.Alg a) -> s0: Alg.state -> Alg.Alg a
Alg.Alg
[]
[]
[ "Alg.ops", "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Write", "Alg.Read", "Alg.state", "Alg.handle_read", "Alg.handle_write", "Alg.op_inp", "Alg.op_out" ]
[]
false
true
false
false
false
let handle_st (a: Type) (labs: ops) (f: (unit -> Alg a (Write :: Read :: labs))) (s0: state) : Alg a labs =
handle_read (fun () -> handle_write f) (fun _ k -> k s0)
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.restricted_t
val restricted_t : a: Type -> b: (_: a -> Type) -> Type
let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f}
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 78, "end_line": 102, "start_col": 0, "start_line": 102 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b].
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: (_: a -> Type) -> Type
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow", "FStar.FunctionalExtensionality.is_restricted" ]
[]
false
false
false
true
true
let restricted_t (a: Type) (b: (a -> Type)) =
f: arrow a b {is_restricted a f}
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.op_Hat_Subtraction_Greater
val op_Hat_Subtraction_Greater : a: Type -> b: Type -> Type
let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b)
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 72, "end_line": 111, "start_col": 0, "start_line": 111 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: Type -> Type
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.restricted_t" ]
[]
false
false
false
true
true
let ( ^-> ) (a b: Type) =
restricted_t a (fun _ -> b)
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.efun_g
val efun_g : a: Type -> b: (_: a -> Type) -> Type
let efun_g (a: Type) (b: (a -> Type)) = arrow_g a b
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 51, "end_line": 143, "start_col": 0, "start_line": 143 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *) unfold let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x) (** Use [arrow_g] instead *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: (_: a -> Type) -> Type
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow_g" ]
[]
false
false
false
true
true
let efun_g (a: Type) (b: (a -> Type)) =
arrow_g a b
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.is_restricted
val is_restricted : a: Type -> f: FStar.FunctionalExtensionality.arrow a b -> Prims.logical
let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 81, "end_line": 94, "start_col": 0, "start_line": 94 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g]
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> f: FStar.FunctionalExtensionality.arrow a b -> Prims.logical
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow", "Prims.eq2", "FStar.FunctionalExtensionality.on_domain", "Prims.logical" ]
[]
false
false
false
false
true
let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) =
on_domain a f == f
false
Alg.fst
Alg.__catchST1
val __catchST1 (#a #labs: _) (f: tree a (Read :: Write :: labs)) (s0: state) : tree (a & state) labs
val __catchST1 (#a #labs: _) (f: tree a (Read :: Write :: labs)) (s0: state) : tree (a & state) labs
let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 47, "end_line": 402, "start_col": 0, "start_line": 400 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: Alg.tree a (Alg.Read :: Alg.Write :: labs) -> s0: Alg.state -> Alg.tree (a * Alg.state) labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "Alg.tree", "Prims.Cons", "Alg.Read", "Alg.Write", "Alg.state", "Alg.bind", "FStar.Pervasives.Native.tuple2", "Alg.__catchST1_aux" ]
[]
false
false
false
false
false
let __catchST1 #a #labs (f: tree a (Read :: Write :: labs)) (s0: state) : tree (a & state) labs =
bind _ _ (__catchST1_aux f) (fun f -> f s0)
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.efun
val efun : a: Type -> b: (_: a -> Type) -> Type
let efun (a: Type) (b: (a -> Type)) = arrow a b
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 47, "end_line": 45, "start_col": 0, "start_line": 45 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: (_: a -> Type) -> Type
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow" ]
[]
false
false
false
true
true
let efun (a: Type) (b: (a -> Type)) =
arrow a b
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.feq_g
val feq_g : f: FStar.FunctionalExtensionality.arrow_g a b -> g: FStar.FunctionalExtensionality.arrow_g a b -> Prims.logical
let feq_g (#a: Type) (#b: (a -> Type)) (f g: arrow_g a b) = forall x. {:pattern (f x)\/(g x)} f x == g x
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 46, "end_line": 147, "start_col": 0, "start_line": 146 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *) unfold let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x) (** Use [arrow_g] instead *) [@@ (deprecated "Use arrow_g instead")] let efun_g (a: Type) (b: (a -> Type)) = arrow_g a b
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: FStar.FunctionalExtensionality.arrow_g a b -> g: FStar.FunctionalExtensionality.arrow_g a b -> Prims.logical
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow_g", "Prims.l_Forall", "Prims.eq2", "Prims.logical" ]
[]
false
false
false
false
true
let feq_g (#a: Type) (#b: (a -> Type)) (f g: arrow_g a b) =
forall x. {:pattern (f x)\/(g x)} f x == g x
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.on
val on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b)
val on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b)
let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 62, "end_line": 123, "start_col": 0, "start_line": 123 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> f: (_: a -> b) -> a ^-> b
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.on_dom", "FStar.FunctionalExtensionality.op_Hat_Subtraction_Greater" ]
[]
false
false
false
true
false
let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) =
on_dom a f
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.arrow_g
val arrow_g : a: Type -> b: (_: a -> Type) -> Type
let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x)
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 59, "end_line": 139, "start_col": 0, "start_line": 139 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: (_: a -> Type) -> Type
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
true
let arrow_g (a: Type) (b: (a -> Type)) =
x: a -> GTot (b x)
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.is_restricted_g
val is_restricted_g : a: Type -> f: FStar.FunctionalExtensionality.arrow_g a b -> Prims.logical
let is_restricted_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) = on_domain_g a f == f
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 87, "end_line": 162, "start_col": 0, "start_line": 162 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *) unfold let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x) (** Use [arrow_g] instead *) [@@ (deprecated "Use arrow_g instead")] let efun_g (a: Type) (b: (a -> Type)) = arrow_g a b (** [feq_g #a #b f g]: pointwise equality of [f] and [g] on domain [a] **) let feq_g (#a: Type) (#b: (a -> Type)) (f g: arrow_g a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** The counterpart of [on_domain] for ghost functions *) val on_domain_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Tot (arrow_g a b) (** [on_domain_g a f] is pointwise equal to [f] *) val feq_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (feq_g (on_domain_g a f) f) [SMTPat (on_domain_g a f)] (** on_domain_g is idempotent *) val idempotence_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (on_domain_g a (on_domain_g a f) == on_domain_g a f) [SMTPat (on_domain_g a (on_domain_g a f))]
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> f: FStar.FunctionalExtensionality.arrow_g a b -> Prims.logical
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow_g", "Prims.eq2", "FStar.FunctionalExtensionality.on_domain_g", "Prims.logical" ]
[]
false
false
false
false
true
let is_restricted_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) =
on_domain_g a f == f
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.op_Hat_Subtraction_Greater_Greater
val op_Hat_Subtraction_Greater_Greater : a: Type -> b: Type -> Type
let op_Hat_Subtraction_Greater_Greater (a b: Type) = restricted_g_t a (fun _ -> b)
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 82, "end_line": 173, "start_col": 0, "start_line": 173 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *) unfold let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x) (** Use [arrow_g] instead *) [@@ (deprecated "Use arrow_g instead")] let efun_g (a: Type) (b: (a -> Type)) = arrow_g a b (** [feq_g #a #b f g]: pointwise equality of [f] and [g] on domain [a] **) let feq_g (#a: Type) (#b: (a -> Type)) (f g: arrow_g a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** The counterpart of [on_domain] for ghost functions *) val on_domain_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Tot (arrow_g a b) (** [on_domain_g a f] is pointwise equal to [f] *) val feq_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (feq_g (on_domain_g a f) f) [SMTPat (on_domain_g a f)] (** on_domain_g is idempotent *) val idempotence_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (on_domain_g a (on_domain_g a f) == on_domain_g a f) [SMTPat (on_domain_g a (on_domain_g a f))] (** Counterpart of [is_restricted] for ghost functions *) let is_restricted_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) = on_domain_g a f == f (** Counterpart of [restricted_t] for ghost functions *) let restricted_g_t (a: Type) (b: (a -> Type)) = f: arrow_g a b {is_restricted_g a f} (** [a ^->> b]: Notation for ghost, non-dependent restricted functions from [a] a to [b]. *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: Type -> Type
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.restricted_g_t" ]
[]
false
false
false
true
true
let ( ^->> ) (a b: Type) =
restricted_g_t a (fun _ -> b)
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.restricted_g_t
val restricted_g_t : a: Type -> b: (_: a -> Type) -> Type
let restricted_g_t (a: Type) (b: (a -> Type)) = f: arrow_g a b {is_restricted_g a f}
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 84, "end_line": 165, "start_col": 0, "start_line": 165 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *) unfold let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x) (** Use [arrow_g] instead *) [@@ (deprecated "Use arrow_g instead")] let efun_g (a: Type) (b: (a -> Type)) = arrow_g a b (** [feq_g #a #b f g]: pointwise equality of [f] and [g] on domain [a] **) let feq_g (#a: Type) (#b: (a -> Type)) (f g: arrow_g a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** The counterpart of [on_domain] for ghost functions *) val on_domain_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Tot (arrow_g a b) (** [on_domain_g a f] is pointwise equal to [f] *) val feq_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (feq_g (on_domain_g a f) f) [SMTPat (on_domain_g a f)] (** on_domain_g is idempotent *) val idempotence_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (on_domain_g a (on_domain_g a f) == on_domain_g a f) [SMTPat (on_domain_g a (on_domain_g a f))] (** Counterpart of [is_restricted] for ghost functions *) let is_restricted_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) = on_domain_g a f == f
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> b: (_: a -> Type) -> Type
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow_g", "FStar.FunctionalExtensionality.is_restricted_g" ]
[]
false
false
false
true
true
let restricted_g_t (a: Type) (b: (a -> Type)) =
f: arrow_g a b {is_restricted_g a f}
false
Alg.fst
Alg.run_exnst
val run_exnst (#a: _) (f: (unit -> Alg a [Write; Raise; Read])) (s_0: state) : option a & state
val run_exnst (#a: _) (f: (unit -> Alg a [Write; Raise; Read])) (s_0: state) : option a & state
let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 50, "end_line": 450, "start_col": 0, "start_line": 449 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg a) -> s_0: Alg.state -> FStar.Pervasives.Native.option a * Alg.state
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Write", "Alg.Raise", "Alg.Read", "Prims.Nil", "Alg.state", "Alg.run", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.option", "Alg.catchST", "Alg.catchE" ]
[]
false
false
false
false
false
let run_exnst #a (f: (unit -> Alg a [Write; Raise; Read])) (s_0: state) : option a & state =
run (fun () -> catchST (fun () -> catchE f) s_0)
false
Alg.fst
Alg.runSTE_pure
val runSTE_pure (#a: _) (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : option a & state
val runSTE_pure (#a: _) (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : option a & state
let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 29, "end_line": 582, "start_col": 0, "start_line": 581 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg a) -> s0: Alg.state -> FStar.Pervasives.Native.option a * Alg.state
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Raise", "Alg.Write", "Alg.Read", "Prims.Nil", "Alg.state", "Alg.run", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.option", "Alg.runSTE" ]
[]
false
false
false
false
false
let runSTE_pure #a (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : option a & state =
run (fun () -> runSTE f s0)
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.on_g
val on_g (a #b: Type) (f: (a -> GTot b)) : (a ^->> b)
val on_g (a #b: Type) (f: (a -> GTot b)) : (a ^->> b)
let on_g (a #b: Type) (f: (a -> GTot b)) : (a ^->> b) = on_dom_g a f
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 68, "end_line": 185, "start_col": 0, "start_line": 185 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *) unfold let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x) (** Use [arrow_g] instead *) [@@ (deprecated "Use arrow_g instead")] let efun_g (a: Type) (b: (a -> Type)) = arrow_g a b (** [feq_g #a #b f g]: pointwise equality of [f] and [g] on domain [a] **) let feq_g (#a: Type) (#b: (a -> Type)) (f g: arrow_g a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** The counterpart of [on_domain] for ghost functions *) val on_domain_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Tot (arrow_g a b) (** [on_domain_g a f] is pointwise equal to [f] *) val feq_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (feq_g (on_domain_g a f) f) [SMTPat (on_domain_g a f)] (** on_domain_g is idempotent *) val idempotence_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (on_domain_g a (on_domain_g a f) == on_domain_g a f) [SMTPat (on_domain_g a (on_domain_g a f))] (** Counterpart of [is_restricted] for ghost functions *) let is_restricted_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) = on_domain_g a f == f (** Counterpart of [restricted_t] for ghost functions *) let restricted_g_t (a: Type) (b: (a -> Type)) = f: arrow_g a b {is_restricted_g a f} (** [a ^->> b]: Notation for ghost, non-dependent restricted functions from [a] a to [b]. *) unfold let op_Hat_Subtraction_Greater_Greater (a b: Type) = restricted_g_t a (fun _ -> b) (** [on_dom_g a f]: A convenience function to introduce a restricted, ghost, dependent function *) unfold let on_dom_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : restricted_g_t a b = on_domain_g a f (** [on_g a f]: A convenience function to introduce a restricted, ghost, non-dependent function *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> f: (_: a -> Prims.GTot b) -> a ^->> b
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.on_dom_g", "FStar.FunctionalExtensionality.op_Hat_Subtraction_Greater_Greater" ]
[]
false
false
false
false
false
let on_g (a #b: Type) (f: (a -> GTot b)) : (a ^->> b) =
on_dom_g a f
false
Alg.fst
Alg.interp_pure_tree
val interp_pure_tree (#a: _) (t: tree a []) : Tot a
val interp_pure_tree (#a: _) (t: tree a []) : Tot a
let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 17, "end_line": 589, "start_col": 0, "start_line": 587 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Alg.tree a [] -> a
Prims.Tot
[ "total" ]
[]
[ "Alg.tree", "Prims.Nil", "Alg.op" ]
[]
false
false
false
true
false
let interp_pure_tree #a (t: tree a []) : Tot a =
match t with | Return x -> x
false
Alg.fst
Alg.handle
val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs
val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs
let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 7, "end_line": 678, "start_col": 0, "start_line": 667 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
o: Alg.op -> f: Alg.tree a (o :: labs) -> h: Alg.handler_tree_op o b labs -> v: (_: a -> Alg.tree b labs) -> Alg.tree b labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "Alg.tree", "Prims.Cons", "Alg.handler_tree_op", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Prims.op_Equality", "Alg.handle", "Prims.bool", "Alg.Op" ]
[ "recursion" ]
false
false
false
false
false
let rec handle #a #b #labs l f h v =
match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else let k' o : tree b labs = handle l (k o) h v in Op act i k'
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.on_dom
val on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b
val on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b
let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 88, "end_line": 117, "start_col": 0, "start_line": 117 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> f: FStar.FunctionalExtensionality.arrow a b -> FStar.FunctionalExtensionality.restricted_t a b
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow", "FStar.FunctionalExtensionality.on_domain", "FStar.FunctionalExtensionality.restricted_t" ]
[]
false
false
false
false
false
let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b =
on_domain a f
false
Alg.fst
Alg.catch0'
val catch0' (#a #labs: _) (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs
val catch0' (#a #labs: _) (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs
let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 55, "end_line": 706, "start_col": 0, "start_line": 703 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t1: Alg.tree a (Alg.Raise :: labs) -> t2: Alg.tree a labs -> Alg.tree a labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "Alg.tree", "Prims.Cons", "Alg.Raise", "Alg.handle", "Alg.op_inp", "Alg.op_out", "Alg.Return" ]
[]
false
false
false
false
false
let catch0' #a #labs (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs =
handle Raise t1 (fun i k -> t2) (fun x -> Return x)
false
Alg.fst
Alg.lattice_raise_repr
val lattice_raise_repr: #a: Type -> Prims.unit -> L.repr a [L.EXN]
val lattice_raise_repr: #a: Type -> Prims.unit -> L.repr a [L.EXN]
let lattice_raise_repr (#a:Type) () : L.repr a [L.EXN] = reify (L.raise #a ())
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 23, "end_line": 767, "start_col": 0, "start_line": 766 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ()) let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> Lattice.repr a [Lattice.EXN]
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Lattice.raise", "Lattice.repr", "Prims.Cons", "Lattice.eff_label", "Lattice.EXN", "Prims.Nil" ]
[]
false
false
false
true
false
let lattice_raise_repr (#a: Type) () : L.repr a [L.EXN] =
reify (L.raise #a ())
false
Alg.fst
Alg.lab_corr
val lab_corr (l: baseop) (ls: list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)]
val lab_corr (l: baseop) (ls: list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)]
let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 29, "end_line": 740, "start_col": 0, "start_line": 735 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab'
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Alg.baseop -> ls: Prims.list Alg.baseop -> FStar.Pervasives.Lemma (ensures FStar.List.Tot.Base.memP l ls <==> FStar.List.Tot.Base.mem (Alg.trlab l) (Alg.trlabs ls)) [SMTPat (FStar.List.Tot.Base.memP l ls)]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.baseop", "Prims.list", "Alg.lab_corr", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.l_iff", "FStar.List.Tot.Base.memP", "Prims.b2t", "FStar.List.Tot.Base.mem", "Lattice.eff_label", "Alg.trlab", "Alg.trlabs", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.Nil" ]
[ "recursion" ]
false
false
true
false
false
let rec lab_corr (l: baseop) (ls: list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] =
match ls with | [] -> () | l1 :: ls -> lab_corr l ls
false
Alg.fst
Alg.handler_raise_write
val handler_raise_write (#a: _) : handler [Raise; Write] (option a & state) [Write; Read]
val handler_raise_write (#a: _) : handler [Raise; Write] (option a & state) [Write; Read]
let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 43, "end_line": 562, "start_col": 0, "start_line": 558 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Alg.handler [Alg.Raise; Alg.Write] (FStar.Pervasives.Native.option a * Alg.state) [Alg.Write; Alg.Read]
Prims.Tot
[ "total" ]
[]
[ "Alg.op", "FStar.List.Tot.Base.memP", "Prims.Cons", "Alg.Raise", "Alg.Write", "Prims.Nil", "Alg.op_inp", "Alg.op_out", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.option", "Alg.state", "Alg.Read", "FStar.Pervasives.Native.Mktuple2", "Prims.int", "FStar.Pervasives.Native.None", "Alg.get", "Alg.handle_write'", "Alg.handler_op", "Alg.handler" ]
[]
false
false
false
true
false
let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] =
function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k)
false
Alg.fst
Alg.handle2
val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs
val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs
let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 7, "end_line": 701, "start_col": 0, "start_line": 688 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l1: Alg.op -> l2: Alg.op -> f: Alg.tree a (l1 :: l2 :: labs) -> h1: Alg.handler_tree_op l1 b labs -> h2: Alg.handler_tree_op l2 b labs -> v: (_: a -> Alg.tree b labs) -> Alg.tree b labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "Alg.tree", "Prims.Cons", "Alg.handler_tree_op", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Prims.op_Equality", "Alg.handle2", "Prims.bool", "Alg.Op" ]
[ "recursion" ]
false
false
false
false
false
let rec handle2 #a #b #labs l1 l2 f h1 h2 v =
match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k'
false
FStar.FunctionalExtensionality.fsti
FStar.FunctionalExtensionality.on_dom_g
val on_dom_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : restricted_g_t a b
val on_dom_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : restricted_g_t a b
let on_dom_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : restricted_g_t a b = on_domain_g a f
{ "file_name": "ulib/FStar.FunctionalExtensionality.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 96, "end_line": 179, "start_col": 0, "start_line": 179 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module FStar.FunctionalExtensionality /// Functional extensionality asserts the equality of pointwise-equal /// functions. /// /// The formulation of this axiom is particularly subtle in F* because /// of its interaction with subtyping. In fact, prior formulations of /// this axiom were discovered to be unsound by Aseem Rastogi. /// /// The predicate [feq #a #b f g] asserts that [f, g: x:a -> (b x)] are /// pointwise equal on the domain [a]. /// /// However, due to subtyping [f] and [g] may also be defined on some /// domain larger than [a]. We need to be careful to ensure that merely /// proving [f] and [g] equal on their sub-domain [a] does not lead us /// to conclude that they are equal everywhere. /// /// For more context on how functional extensionality works in F*, see /// 1. tests/micro-benchmarks/Test.FunctionalExtensionality.fst /// 2. ulib/FStar.Map.fst and ulib/FStar.Map.fsti /// 3. Issue #1542 on github.com/FStarLang/FStar/issues/1542 (** The type of total, dependent functions *) unfold let arrow (a: Type) (b: (a -> Type)) = x: a -> Tot (b x) (** Using [arrow] instead *) [@@ (deprecated "Use arrow instead")] let efun (a: Type) (b: (a -> Type)) = arrow a b (** feq #a #b f g: pointwise equality of [f] and [g] on domain [a] *) let feq (#a: Type) (#b: (a -> Type)) (f g: arrow a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** [on_domain a f]: This is a key function provided by the module. It has several features. 1. Intuitively, [on_domain a f] can be seen as a function whose maximal domain is [a]. 2. While, [on_domain a f] is proven to be *pointwise* equal to [f], crucially it is not provably equal to [f], since [f] may actually have a domain larger than [a]. 3. [on_domain] is idempotent 4. [on_domain a f x] has special treatment in F*'s normalizer. It reduces to [f x], reflecting the pointwise equality of [on_domain a f] and [f]. 5. [on_domain] is marked [inline_for_extraction], to eliminate the overhead of an indirection in extracted code. (This feature will be exercised as part of cross-module inlining across interface boundaries) *) inline_for_extraction val on_domain (a: Type) (#b: (a -> Type)) ([@@@strictly_positive] f: arrow a b) : Tot (arrow a b) (** feq_on_domain: [on_domain a f] is pointwise equal to [f] *) val feq_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (feq (on_domain a f) f) [SMTPat (on_domain a f)] (** on_domain is idempotent *) val idempotence_on_domain (#a: Type) (#b: (a -> Type)) (f: arrow a b) : Lemma (on_domain a (on_domain a f) == on_domain a f) [SMTPat (on_domain a (on_domain a f))] (** [is_restricted a f]: Though stated indirectly, [is_restricted a f] is valid when [f] is a function whose maximal domain is equal to [a]. Equivalently, one may see its definition as [exists g. f == on_domain a g] *) let is_restricted (a: Type) (#b: (a -> Type)) (f: arrow a b) = on_domain a f == f (** restricted_t a b: Lifts the [is_restricted] predicate into a refinement type This is the type of functions whose maximal domain is [a] and whose (dependent) co-domain is [b]. *) let restricted_t (a: Type) (b: (a -> Type)) = f: arrow a b {is_restricted a f} (** [a ^-> b]: Notation for non-dependent restricted functions from [a] to [b]. The first symbol [^] makes it right associative, as expected for arrows. *) unfold let op_Hat_Subtraction_Greater (a b: Type) = restricted_t a (fun _ -> b) (** [on_dom a f]: A convenience function to introduce a restricted, dependent function *) unfold let on_dom (a: Type) (#b: (a -> Type)) (f: arrow a b) : restricted_t a b = on_domain a f (** [on a f]: A convenience function to introduce a restricted, non-dependent function *) unfold let on (a #b: Type) (f: (a -> Tot b)) : (a ^-> b) = on_dom a f (**** MAIN AXIOM *) (** [extensionality]: The main axiom of this module states that functions [f] and [g] that are pointwise equal on domain [a] are provably equal when restricted to [a] *) val extensionality (a: Type) (b: (a -> Type)) (f g: arrow a b) : Lemma (ensures (feq #a #b f g <==> on_domain a f == on_domain a g)) [SMTPat (feq #a #b f g)] (**** DUPLICATED FOR GHOST FUNCTIONS *) (** The type of ghost, total, dependent functions *) unfold let arrow_g (a: Type) (b: (a -> Type)) = x: a -> GTot (b x) (** Use [arrow_g] instead *) [@@ (deprecated "Use arrow_g instead")] let efun_g (a: Type) (b: (a -> Type)) = arrow_g a b (** [feq_g #a #b f g]: pointwise equality of [f] and [g] on domain [a] **) let feq_g (#a: Type) (#b: (a -> Type)) (f g: arrow_g a b) = forall x. {:pattern (f x)\/(g x)} f x == g x (** The counterpart of [on_domain] for ghost functions *) val on_domain_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Tot (arrow_g a b) (** [on_domain_g a f] is pointwise equal to [f] *) val feq_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (feq_g (on_domain_g a f) f) [SMTPat (on_domain_g a f)] (** on_domain_g is idempotent *) val idempotence_on_domain_g (#a: Type) (#b: (a -> Type)) (f: arrow_g a b) : Lemma (on_domain_g a (on_domain_g a f) == on_domain_g a f) [SMTPat (on_domain_g a (on_domain_g a f))] (** Counterpart of [is_restricted] for ghost functions *) let is_restricted_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) = on_domain_g a f == f (** Counterpart of [restricted_t] for ghost functions *) let restricted_g_t (a: Type) (b: (a -> Type)) = f: arrow_g a b {is_restricted_g a f} (** [a ^->> b]: Notation for ghost, non-dependent restricted functions from [a] a to [b]. *) unfold let op_Hat_Subtraction_Greater_Greater (a b: Type) = restricted_g_t a (fun _ -> b) (** [on_dom_g a f]: A convenience function to introduce a restricted, ghost, dependent function *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "FStar.FunctionalExtensionality.fsti" }
[ { "abbrev": false, "full_module": "FStar.Tactics.Effect", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.V2.Builtins", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Type -> f: FStar.FunctionalExtensionality.arrow_g a b -> FStar.FunctionalExtensionality.restricted_g_t a b
Prims.Tot
[ "total" ]
[]
[ "FStar.FunctionalExtensionality.arrow_g", "FStar.FunctionalExtensionality.on_domain_g", "FStar.FunctionalExtensionality.restricted_g_t" ]
[]
false
false
false
false
false
let on_dom_g (a: Type) (#b: (a -> Type)) (f: arrow_g a b) : restricted_g_t a b =
on_domain_g a f
false
Alg.fst
Alg.runSTE
val runSTE (#a: _) (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : Alg (option a & state) []
val runSTE (#a: _) (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : Alg (option a & state) []
let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 62, "end_line": 578, "start_col": 0, "start_line": 573 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg a) -> s0: Alg.state -> Alg.Alg (FStar.Pervasives.Native.option a * Alg.state)
Alg.Alg
[]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Raise", "Alg.Write", "Alg.Read", "Prims.Nil", "Alg.state", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.option", "Alg.handle_with", "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.Some", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "FStar.Pervasives.Native.None", "Alg.handler_op" ]
[]
false
true
false
false
false
let runSTE #a (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : Alg (option a & state) [] =
handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function | Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0
false
Alg.fst
Alg.interp_rdwr_tree
val interp_rdwr_tree (#a: _) (t: tree a [Read; Write]) (s: state) : Tot (a & state)
val interp_rdwr_tree (#a: _) (t: tree a [Read; Write]) (s: state) : Tot (a & state)
let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 29, "end_line": 607, "start_col": 0, "start_line": 601 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Alg.tree a [Alg.Read; Alg.Write] -> s: Alg.state -> a * Alg.state
Prims.Tot
[ "total" ]
[]
[ "Alg.tree", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Write", "Prims.Nil", "Alg.state", "FStar.Pervasives.Native.Mktuple2", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Alg.interp_rdwr_tree", "FStar.Pervasives.Native.tuple2" ]
[ "recursion" ]
false
false
false
true
false
let rec interp_rdwr_tree #a (t: tree a [Read; Write]) (s: state) : Tot (a & state) =
match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s
false
Alg.fst
Alg.interp_rd_tree
val interp_rd_tree (#a: _) (t: tree a [Read]) (s: state) : Tot a
val interp_rd_tree (#a: _) (t: tree a [Read]) (s: state) : Tot a
let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 26, "end_line": 597, "start_col": 0, "start_line": 593 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ()))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Alg.tree a [Alg.Read] -> s: Alg.state -> a
Prims.Tot
[ "total" ]
[]
[ "Alg.tree", "Prims.Cons", "Alg.op", "Alg.Read", "Prims.Nil", "Alg.state", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Alg.interp_rd_tree" ]
[ "recursion" ]
false
false
false
true
false
let rec interp_rd_tree #a (t: tree a [Read]) (s: state) : Tot a =
match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s
false
Alg.fst
Alg.catch0''
val catch0'' (#a #labs: _) (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs
val catch0'' (#a #labs: _) (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs
let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k))
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 57, "end_line": 714, "start_col": 0, "start_line": 708 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t1: Alg.tree a (Alg.Raise :: labs) -> t2: Alg.tree a labs -> Alg.tree a labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "Alg.tree", "Prims.Cons", "Alg.Raise", "Alg.handle_tree", "Alg.Return", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.Op", "Alg.handler_tree_op" ]
[]
false
false
false
false
false
let catch0'' #a #labs (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs =
handle_tree t1 (fun x -> Return x) (function | Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k))
false
Alg.fst
Alg.trlab'
val trlab' : _: Lattice.eff_label -> Alg.op
let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 18, "end_line": 730, "start_col": 0, "start_line": 727 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Lattice.eff_label -> Alg.op
Prims.Tot
[ "total" ]
[]
[ "Lattice.eff_label", "Alg.Read", "Alg.Write", "Alg.Raise", "Alg.op" ]
[]
false
false
false
true
false
let trlab' =
function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise
false
Alg.fst
Alg.interp_all_tree
val interp_all_tree (#a: _) (t: tree a [Read; Write; Raise]) (s: state) : Tot (option a & state)
val interp_all_tree (#a: _) (t: tree a [Read; Write; Raise]) (s: state) : Tot (option a & state)
let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 13, "end_line": 630, "start_col": 0, "start_line": 622 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Alg.tree a [Alg.Read; Alg.Write; Alg.Raise] -> s: Alg.state -> FStar.Pervasives.Native.option a * Alg.state
Prims.Tot
[ "total" ]
[]
[ "Alg.tree", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Write", "Alg.Raise", "Prims.Nil", "Alg.state", "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.Some", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Alg.interp_all_tree", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.tuple2" ]
[ "recursion" ]
false
false
false
true
false
let rec interp_all_tree #a (t: tree a [Read; Write; Raise]) (s: state) : Tot (option a & state) =
match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s)
false
Alg.fst
Alg.interp_read_raise_tree
val interp_read_raise_tree (#a: _) (t: tree a [Read; Raise]) (s: state) : either exn a
val interp_read_raise_tree (#a: _) (t: tree a [Read; Raise]) (s: state) : either exn a
let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 9, "end_line": 617, "start_col": 0, "start_line": 611 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Alg.tree a [Alg.Read; Alg.Raise] -> s: Alg.state -> FStar.Pervasives.either Prims.exn a
Prims.Tot
[ "total" ]
[]
[ "Alg.tree", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Raise", "Prims.Nil", "Alg.state", "FStar.Pervasives.Inr", "Prims.exn", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Alg.interp_read_raise_tree", "FStar.Pervasives.Inl", "FStar.Pervasives.either" ]
[ "recursion" ]
false
false
false
true
false
let rec interp_read_raise_tree #a (t: tree a [Read; Raise]) (s: state) : either exn a =
match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e
false
Alg.fst
Alg.fixup_no_other
val fixup_no_other (l: op{Other? l}) (ls: list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))]
val fixup_no_other (l: op{Other? l}) (ls: list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))]
let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 35, "end_line": 759, "start_col": 0, "start_line": 754 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Alg.op{Other? l} -> ls: Prims.list Alg.baseop -> FStar.Pervasives.Lemma (ensures FStar.List.Tot.Base.memP l (Alg.fixup ls) <==> Prims.l_False) [SMTPat (FStar.List.Tot.Base.memP l (Alg.fixup ls))]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.op", "Prims.b2t", "Alg.uu___is_Other", "Prims.list", "Alg.baseop", "Alg.fixup_no_other", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.l_iff", "FStar.List.Tot.Base.memP", "Alg.fixup", "Prims.l_False", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.Nil" ]
[ "recursion" ]
false
false
true
false
false
let rec fixup_no_other (l: op{Other? l}) (ls: list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] =
match ls with | [] -> () | l1 :: ls -> fixup_no_other l ls
false
Alg.fst
Alg.fixup_corr
val fixup_corr (l: baseop) (ls: list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))]
val fixup_corr (l: baseop) (ls: list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))]
let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 31, "end_line": 752, "start_col": 0, "start_line": 747 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
l: Alg.baseop -> ls: Prims.list Alg.baseop -> FStar.Pervasives.Lemma (ensures FStar.List.Tot.Base.memP l (Alg.fixup ls) <==> FStar.List.Tot.Base.memP l ls) [SMTPat (FStar.List.Tot.Base.memP l (Alg.fixup ls))]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.baseop", "Prims.list", "Alg.fixup_corr", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.l_iff", "FStar.List.Tot.Base.memP", "Alg.op", "Alg.fixup", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.Nil" ]
[ "recursion" ]
false
false
true
false
false
let rec fixup_corr (l: baseop) (ls: list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] =
match ls with | [] -> () | l1 :: ls -> fixup_corr l ls
false
Alg.fst
Alg.trlab
val trlab (o: baseop) : L.eff_label
val trlab (o: baseop) : L.eff_label
let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 18, "end_line": 725, "start_col": 0, "start_line": 722 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)}
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
o: Alg.baseop -> Lattice.eff_label
Prims.Tot
[ "total" ]
[]
[ "Alg.baseop", "Lattice.RD", "Lattice.WR", "Lattice.EXN", "Lattice.eff_label" ]
[]
false
false
false
true
false
let trlab: o: baseop -> L.eff_label =
function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN
false
Alg.fst
Alg.abides'
val abides' (f: sem0 'a) (labs: list baseop) : prop
val abides' (f: sem0 'a) (labs: list baseop) : prop
let abides' (f : sem0 'a) (labs:list baseop) : prop = (Read `memP` labs \/ (forall s0 s1. fst (f s0) == fst (f s1))) /\ (Write `memP` labs \/ (forall s0. snd (f s0) == s0)) /\ (Raise `memP` labs \/ (forall s0. Inr? (fst (f s0))))
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 58, "end_line": 805, "start_col": 0, "start_line": 802 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ()) let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s) let lattice_raise_repr (#a:Type) () : L.repr a [L.EXN] = reify (L.raise #a ()) // This would be a lot nicer if it was done in L.EFF itself, // but the termination proof fails since it has no logical payload. let rec interp_into_lattice_tree #a (#labs:list baseop) (t : tree a (fixup labs)) : L.repr a (trlabs labs) = match t with | Return x -> L.return _ x | Op Read i k -> L.bind _ _ _ _ (lattice_get_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Write i k -> L.bind _ _ _ _ (lattice_put_repr i) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Raise i k -> L.bind _ _ _ _ (lattice_raise_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) let interp_into_lattice #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : Lattice.EFF a (trlabs labs) = Lattice.EFF?.reflect (interp_into_lattice_tree (reify (f ()))) // This is rather silly: we reflect and then reify. Maybe define interp_into_lattice // directly? let interp_full #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : L.repr a (trlabs labs) = reify (interp_into_lattice #a #labs f) (* Doing it directly. *) type sem0 (a:Type) : Type = state -> Tot (either exn a & state)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: Alg.sem0 'a -> labs: Prims.list Alg.baseop -> Prims.prop
Prims.Tot
[ "total" ]
[]
[ "Alg.sem0", "Prims.list", "Alg.baseop", "Prims.l_and", "Prims.l_or", "FStar.List.Tot.Base.memP", "Alg.Read", "Prims.l_Forall", "Alg.state", "Prims.eq2", "FStar.Pervasives.either", "Prims.exn", "FStar.Pervasives.Native.fst", "Alg.Write", "FStar.Pervasives.Native.snd", "Alg.Raise", "Prims.b2t", "FStar.Pervasives.uu___is_Inr", "Prims.prop" ]
[]
false
false
false
true
true
let abides' (f: sem0 'a) (labs: list baseop) : prop =
(Read `memP` labs \/ (forall s0 s1. fst (f s0) == fst (f s1))) /\ (Write `memP` labs \/ (forall s0. snd (f s0) == s0)) /\ (Raise `memP` labs \/ (forall s0. Inr? (fst (f s0))))
false
Alg.fst
Alg.interp_full
val interp_full (#a: _) (#labs: list baseop) (f: (unit -> Alg a (fixup labs))) : L.repr a (trlabs labs)
val interp_full (#a: _) (#labs: list baseop) (f: (unit -> Alg a (fixup labs))) : L.repr a (trlabs labs)
let interp_full #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : L.repr a (trlabs labs) = reify (interp_into_lattice #a #labs f)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 42, "end_line": 796, "start_col": 0, "start_line": 793 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ()) let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s) let lattice_raise_repr (#a:Type) () : L.repr a [L.EXN] = reify (L.raise #a ()) // This would be a lot nicer if it was done in L.EFF itself, // but the termination proof fails since it has no logical payload. let rec interp_into_lattice_tree #a (#labs:list baseop) (t : tree a (fixup labs)) : L.repr a (trlabs labs) = match t with | Return x -> L.return _ x | Op Read i k -> L.bind _ _ _ _ (lattice_get_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Write i k -> L.bind _ _ _ _ (lattice_put_repr i) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Raise i k -> L.bind _ _ _ _ (lattice_raise_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) let interp_into_lattice #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : Lattice.EFF a (trlabs labs) = Lattice.EFF?.reflect (interp_into_lattice_tree (reify (f ()))) // This is rather silly: we reflect and then reify. Maybe define interp_into_lattice
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg a) -> Lattice.repr a (Alg.trlabs labs)
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.baseop", "Prims.unit", "Alg.fixup", "Alg.interp_into_lattice", "Lattice.repr", "Alg.trlabs" ]
[]
false
false
false
false
false
let interp_full #a (#labs: list baseop) (f: (unit -> Alg a (fixup labs))) : L.repr a (trlabs labs) =
reify (interp_into_lattice #a #labs f)
false
Alg.fst
Alg.interp_into_lattice
val interp_into_lattice (#a: _) (#labs: list baseop) (f: (unit -> Alg a (fixup labs))) : Lattice.EFF a (trlabs labs)
val interp_into_lattice (#a: _) (#labs: list baseop) (f: (unit -> Alg a (fixup labs))) : Lattice.EFF a (trlabs labs)
let interp_into_lattice #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : Lattice.EFF a (trlabs labs) = Lattice.EFF?.reflect (interp_into_lattice_tree (reify (f ())))
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 66, "end_line": 789, "start_col": 0, "start_line": 786 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ()) let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s) let lattice_raise_repr (#a:Type) () : L.repr a [L.EXN] = reify (L.raise #a ()) // This would be a lot nicer if it was done in L.EFF itself, // but the termination proof fails since it has no logical payload. let rec interp_into_lattice_tree #a (#labs:list baseop) (t : tree a (fixup labs)) : L.repr a (trlabs labs) = match t with | Return x -> L.return _ x | Op Read i k -> L.bind _ _ _ _ (lattice_get_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Write i k -> L.bind _ _ _ _ (lattice_put_repr i) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Raise i k -> L.bind _ _ _ _ (lattice_raise_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: (_: Prims.unit -> Alg.Alg a) -> Lattice.EFF a
Lattice.EFF
[]
[]
[ "Prims.list", "Alg.baseop", "Prims.unit", "Alg.fixup", "Alg.interp_into_lattice_tree", "Alg.trlabs" ]
[]
false
true
false
false
false
let interp_into_lattice #a (#labs: list baseop) (f: (unit -> Alg a (fixup labs))) : Lattice.EFF a (trlabs labs) =
Lattice.EFF?.reflect (interp_into_lattice_tree (reify (f ())))
false
Alg.fst
Alg.interp_into_lattice_tree
val interp_into_lattice_tree (#a: _) (#labs: list baseop) (t: tree a (fixup labs)) : L.repr a (trlabs labs)
val interp_into_lattice_tree (#a: _) (#labs: list baseop) (t: tree a (fixup labs)) : L.repr a (trlabs labs)
let rec interp_into_lattice_tree #a (#labs:list baseop) (t : tree a (fixup labs)) : L.repr a (trlabs labs) = match t with | Return x -> L.return _ x | Op Read i k -> L.bind _ _ _ _ (lattice_get_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Write i k -> L.bind _ _ _ _ (lattice_put_repr i) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Raise i k -> L.bind _ _ _ _ (lattice_raise_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x))
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 57, "end_line": 784, "start_col": 0, "start_line": 771 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ()) let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s) let lattice_raise_repr (#a:Type) () : L.repr a [L.EXN] = reify (L.raise #a ()) // This would be a lot nicer if it was done in L.EFF itself,
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Alg.tree a (Alg.fixup labs) -> Lattice.repr a (Alg.trlabs labs)
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.baseop", "Alg.tree", "Alg.fixup", "Lattice.return", "Alg.op_inp", "Alg.Read", "Alg.op_out", "Alg.tree0", "Lattice.bind", "Prims.int", "Prims.Cons", "Lattice.eff_label", "Lattice.RD", "Prims.Nil", "Alg.trlabs", "Alg.lattice_get_repr", "Alg.interp_into_lattice_tree", "Lattice.repr", "Alg.Write", "Prims.unit", "Lattice.WR", "Alg.lattice_put_repr", "Alg.Raise", "Lattice.EXN", "Alg.lattice_raise_repr" ]
[ "recursion" ]
false
false
false
false
false
let rec interp_into_lattice_tree #a (#labs: list baseop) (t: tree a (fixup labs)) : L.repr a (trlabs labs) =
match t with | Return x -> L.return _ x | Op Read i k -> L.bind _ _ _ _ (lattice_get_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Write i k -> L.bind _ _ _ _ (lattice_put_repr i) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Raise i k -> L.bind _ _ _ _ (lattice_raise_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x))
false
Alg.fst
Alg.interp_from_lattice_tree
val interp_from_lattice_tree (#a #labs: _) (t: L.repr a labs) : tree a [Read; Raise; Write]
val interp_from_lattice_tree (#a #labs: _) (t: L.repr a labs) : tree a [Read; Raise; Write]
let interp_from_lattice_tree #a #labs (t : L.repr a labs) : tree a [Read; Raise; Write] // conservative = Op Read () (fun s0 -> let (r, s1) = t s0 in match r with | Some x -> Op Write s1 (fun _ -> Return x) | None -> Op Write s1 (fun _ -> Op Raise (Failure "") (fun x -> match x with)))
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 86, "end_line": 829, "start_col": 0, "start_line": 822 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ()) let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s) let lattice_raise_repr (#a:Type) () : L.repr a [L.EXN] = reify (L.raise #a ()) // This would be a lot nicer if it was done in L.EFF itself, // but the termination proof fails since it has no logical payload. let rec interp_into_lattice_tree #a (#labs:list baseop) (t : tree a (fixup labs)) : L.repr a (trlabs labs) = match t with | Return x -> L.return _ x | Op Read i k -> L.bind _ _ _ _ (lattice_get_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Write i k -> L.bind _ _ _ _ (lattice_put_repr i) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Raise i k -> L.bind _ _ _ _ (lattice_raise_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) let interp_into_lattice #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : Lattice.EFF a (trlabs labs) = Lattice.EFF?.reflect (interp_into_lattice_tree (reify (f ()))) // This is rather silly: we reflect and then reify. Maybe define interp_into_lattice // directly? let interp_full #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : L.repr a (trlabs labs) = reify (interp_into_lattice #a #labs f) (* Doing it directly. *) type sem0 (a:Type) : Type = state -> Tot (either exn a & state) let abides' (f : sem0 'a) (labs:list baseop) : prop = (Read `memP` labs \/ (forall s0 s1. fst (f s0) == fst (f s1))) /\ (Write `memP` labs \/ (forall s0. snd (f s0) == s0)) /\ (Raise `memP` labs \/ (forall s0. Inr? (fst (f s0)))) type sem (a:Type) (labs : list baseop) = r:(sem0 a){abides' r labs} let rec interp_sem #a (#labs:list baseop) (t : tree a (fixup labs)) : sem a labs = match t with | Return x -> fun s0 -> (Inr x, s0) | Op Read _ k -> let r : sem a labs = fun s0 -> interp_sem #a #labs (k s0) s0 in r | Op Write s k -> fun s0 -> interp_sem #a #labs (k ()) s | Op Raise e k -> fun s0 -> (Inl e, s0) (* Way back: from the pure ALG into the free one, necessarily giving a fully normalized tree *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Lattice.repr a labs -> Alg.tree a [Alg.Read; Alg.Raise; Alg.Write]
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Lattice.eff_label", "Lattice.repr", "Alg.Op", "Alg.Read", "Alg.op_out", "FStar.Pervasives.Native.option", "Lattice.state", "Alg.Write", "Alg.Return", "Alg.tree0", "Alg.Raise", "Alg.Failure", "FStar.Pervasives.Native.tuple2", "Alg.tree", "Prims.Cons", "Alg.op", "Prims.Nil" ]
[]
false
false
false
false
false
let interp_from_lattice_tree #a #labs (t: L.repr a labs) : tree a [Read; Raise; Write] =
Op Read () (fun s0 -> let r, s1 = t s0 in match r with | Some x -> Op Write s1 (fun _ -> Return x) | None -> Op Write s1 (fun _ -> Op Raise (Failure "") (function )))
false
Alg.fst
Alg.interp_sem
val interp_sem (#a: _) (#labs: list baseop) (t: tree a (fixup labs)) : sem a labs
val interp_sem (#a: _) (#labs: list baseop) (t: tree a (fixup labs)) : sem a labs
let rec interp_sem #a (#labs:list baseop) (t : tree a (fixup labs)) : sem a labs = match t with | Return x -> fun s0 -> (Inr x, s0) | Op Read _ k -> let r : sem a labs = fun s0 -> interp_sem #a #labs (k s0) s0 in r | Op Write s k -> fun s0 -> interp_sem #a #labs (k ()) s | Op Raise e k -> fun s0 -> (Inl e, s0)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 41, "end_line": 817, "start_col": 0, "start_line": 809 }
module Alg (*** Algebraic effects. ***) open FStar.Tactics.V2 open FStar.List.Tot open FStar.Universe //module WF = FStar.WellFounded module L = Lattice type state = int type empty = (* The set of operations. We keep an uninterpreted infinite set of `Other` so we never rely on knowing all operations. *) type op = | Read | Write | Raise | Other of int assume val other_inp : int -> Type let op_inp : op -> Type = function | Read -> unit | Write -> state | Raise -> exn | Other i -> other_inp i assume val other_out : int -> Type let op_out : op -> Type = function | Read -> state | Write -> unit | Raise -> empty | Other i -> other_out i (* Free monad over `op` *) noeq type tree0 (a:Type) : Type = | Return : a -> tree0 a | Op : op:op -> i:(op_inp op) -> k:(op_out op -> tree0 a) -> tree0 a type ops = list op let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2 (* Limiting the operations allowed in a tree *) let rec abides #a (labs:ops) (f : tree0 a) : prop = begin match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True end (* Refined free monad *) type tree (a:Type) (labs : list op) : Type = r:(tree0 a){abides labs r} (***** Some boring list lemmas *****) let rec memP_at (l1 l2 : ops) (l : op) : Lemma (memP l (l1@l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1@l2))] = match l1 with | [] -> () | _::l1 -> memP_at l1 l2 l let rec sublist_at (l1 l2 : ops) : Lemma (sublist l1 (l1@l2) /\ sublist l2 (l1@l2)) [SMTPatOr [[SMTPat (sublist l1 (l1@l2))]; [SMTPat (sublist l2 (l1@l2))]]] = match l1 with | [] -> () | _::l1 -> sublist_at l1 l2 let sublist_at_self (l : ops) : Lemma (sublist l (l@l)) [SMTPat (sublist l (l@l))] = () let rec abides_sublist_nopat #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c) = match c with | Return _ -> () | Op a i k -> let sub o : Lemma (abides l2 (k o)) = abides_sublist_nopat l1 l2 (k o) in Classical.forall_intro sub let abides_sublist #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2 c)) [SMTPat (abides l2 c); SMTPat (sublist l1 l2)] = abides_sublist_nopat l1 l2 c let abides_at_self #a (l : ops) (c : tree0 a) : Lemma (abides (l@l) c <==> abides l c) [SMTPat (abides (l@l) c)] = (* Trigger some patterns *) assert (sublist l (l@l)); assert (sublist (l@l) l) let abides_app #a (l1 l2 : ops) (c : tree0 a) : Lemma (requires (abides l1 c \/ abides l2 c)) (ensures (abides (l1@l2) c)) [SMTPat (abides (l1@l2) c)] = sublist_at l1 l2 (***** / boring list lemmas *****) (* Folding a computation tree. The folding operation `h` need only be defined for the operations in the tree. We also take a value case so this essentially has a builtin 'map' as well. *) val fold_with (#a #b:_) (#labs : ops) (f:tree a labs) (v : a -> b) (h: (o:op{o `memP` labs} -> op_inp o -> (op_out o -> b) -> b)) : b let rec fold_with #a #b #labs f v h = match f with | Return x -> v x | Op act i k -> let k' (o : op_out act) : b = fold_with #_ #_ #labs (k o) v h in h act i k' (* A (tree) handler for a single operation *) let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs (* A (tree) handler for an operation set *) let handler_tree (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_tree_op o b labs1 (* The most generic handling construct, we use it to implement bind. It is actually just a special case of folding. *) val handle_tree (#a #b:_) (#labs0 #labs1 : ops) ($f : tree a labs0) (v : a -> tree b labs1) (h : handler_tree labs0 b labs1) : tree b labs1 let handle_tree f v h = fold_with f v h let return (a:Type) (x:a) : tree a [] = Return x let bind (a b : Type) (#labs1 #labs2 : ops) (c : tree a labs1) (f : (x:a -> tree b labs2)) : Tot (tree b (labs1@labs2)) = handle_tree #_ #_ #_ #(labs1@labs2) c f (fun act i k -> Op act i k) let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f let if_then_else (a : Type) (#labs1 #labs2 : ops) (f : tree a labs1) (g : tree a labs2) (p : bool) : Type = tree a (labs1@labs2) total reifiable reflectable effect { Alg (a:Type) (_:ops) with {repr = tree; return; bind; subcomp; if_then_else} } let lift_pure_alg (a:Type) (wp : pure_wp a) (f : unit -> PURE a wp) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True)) = let v = FStar.Monotonic.Pure.elim_pure f (fun _ -> True) in Return v sub_effect PURE ~> Alg = lift_pure_alg (* Mapping an algebraic operation into an effectful computation. *) let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return) let get : unit -> Alg int [Read] = geneff Read let put : state -> Alg unit [Write] = geneff Write let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with let another_raise #a (e:exn) : Alg a [Raise] = // Funnily enough, the version below succeeds from concluding `a == // empty` under the lambda since the context becomes inconsistent. All // good, just surprising. Alg?.reflect (Op Raise e Return) let rec listmap #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) labs = match l with | [] -> [] | x::xs -> f x :: listmap #_ #_ #labs f xs let rec listmap_read #a #b #labs (f : a -> Alg b labs) (l : list a) : Alg (list b) (Read::labs) = match l with | [] -> let x = get () in [] | x::xs -> let _ = get () in f x :: listmap_read #_ #_ #labs f xs (* Running pure trees *) let frompure #a (t : tree a []) : a = match t with | Return x -> x (* Running pure computations *) let run #a (f : unit -> Alg a []) : a = frompure (reify (f ())) exception Failure of string let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z let test1 (x y : int) : Alg int [Raise; Read; Write] = let z = get () in if x + z > 0 then raise (Failure "asd") else (put 42; y - z) (* A simple operation-polymorphic add in direct style *) let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g () // FIXME: putting this definition inside catch causes a blowup: // // Unexpected error // Failure("Empty option") // Raised at file "stdlib.ml", line 29, characters 17-33 // Called from file "ulib/ml/FStar_All.ml" (inlined), line 4, characters 21-24 // Called from file "src/ocaml-output/FStar_TypeChecker_Util.ml", line 874, characters 18-65 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 675, characters 34-38 // Called from file "src/ocaml-output/FStar_TypeChecker_Common.ml", line 657, characters 25-33 // Called from file "src/ocaml-output/FStar_TypeChecker_TcTerm.ml", line 2048, characters 30-68 // Called from file "src/basic/ml/FStar_Util.ml", line 24, characters 14-18 // .... (* Explicitly defining catch on trees *) let rec __catch0 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = match t1 with | Op Raise e _ -> t2 | Op act i k -> let k' o : tree a labs = __catch0 (k o) t2 in Op act i k' | Return v -> Return v (* Equivalently via handle_tree *) let __catch1 #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> fun i k -> t2 | op -> fun i k -> Op op i k) (* Lifting it into the effect *) let catch #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = Alg?.reflect (__catch1 (reify (f ())) (reify (g ()))) (* Example: get rid of the Raise *) let test_catch #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in catch f g (* Or keep it... Koka-style *) let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g (* But of course, we have to handle if it is not in the output. *) [@@expect_failure [19]] let test_catch3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in catch f g (***** Now for the effectful version *****) (* An (effectful) handler for a single operation *) let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs (* An (effectful) handler for an operation set *) let handler (labs0 : ops) (b:Type) (labs1 : ops) : Type = o:op{o `memP` labs0} -> handler_op o b labs1 (* The generic effectful handling operation, defined simply by massaging handle_tree into the Alg effect. *) let handle_with (#a #b:_) (#labs0 #labs1 : ops) ($f : unit -> Alg a labs0) (v : a -> Alg b labs1) (h : handler labs0 b labs1) (* Looking at v and h together, they basically represent * a handler type [ a<labs0> ->> b<labs1> ] *) : Alg b labs1 = Alg?.reflect (handle_tree (reify (f ())) (fun x -> reify (v x)) (fun a i k -> reify (h a i (fun o -> Alg?.reflect (k o))))) (* A default case for handlers. With the side condition that the operation we're defaulting will remain in the tree, so it has to be in `labs`. All arguments are implicit, F* can usually figure `op` out. *) let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i) (* The version taking the operation explicitly. *) let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i) // Or: = fun _ -> defh (* Of course this can also be done for trees *) let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k (* Another version of catch, but directly in the effect. Note that we do not build Op nor Return nodes, but work in a more direct style. For the default case, we just call the operation op with the input it received and then call the continuation with the result. *) let try_with #a #labs (f : (unit -> Alg a (Raise::labs))) (g:unit -> Alg a labs) : Alg a labs = handle_with f (fun x -> x) (function Raise -> fun _ _ -> g () | _ -> defh) let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some x let catchE #a #labs (f : unit -> Alg a (Raise::labs)) : Alg (option a) labs = handle_with f some_as_alg (function Raise -> fun _ _ -> None | _ -> defh) (* Repeating the examples above *) let test_try_with #labs (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [] = 42 in try_with f g let test_try_with2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in try_with f g [@@expect_failure [19]] let test_try_with3 (f : unit -> Alg int [Raise; Write]) : Alg int [Write] = let g () : Alg int [Raise] = raise (Failure "hmm") in try_with f g (***** The payoff is best seen with handling state *****) (* Explcitly catching state *) let rec __catchST0 #a #labs (t1 : tree a (Read::Write::labs)) (s0:state) : tree (a & int) labs = match t1 with | Return v -> Return (v, s0) | Op Write s k -> __catchST0 (k ()) s | Op Read _ k -> __catchST0 (k s0) s0 | Op act i k -> (* default case *) let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k' (* An alternative: handling Read/Write into the state monad. The handler is basically interpreting [Read () k] as [\s -> k s s] and similarly for Write. Note the stacking of effects: we return a labs-tree that contains a function which returns a labs-tree. *) let __catchST1_aux #a #labs (f : tree a (Read::Write::labs)) : tree (state -> tree (a & state) labs) labs = handle_tree #_ #(state -> tree (a & state) labs) f (fun x -> Return (fun s0 -> Return (x, s0))) (function Read -> fun _ k -> Return (fun s -> bind _ _ (k s) (fun f -> f s)) | Write -> fun s k -> Return (fun _ -> bind _ _ (k ()) (fun f -> f s)) | act -> fun i k -> Op act i k) (* Since tree is a monad, however, we can apply the internal function join the two layers via the multiplication, and recover a more sane shape. *) let __catchST1 #a #labs (f : tree a (Read::Write::labs)) (s0:state) : tree (a & state) labs = bind _ _ (__catchST1_aux f) (fun f -> f s0) // = join (fmap (fun f -> f s0) (__catchST1_aux f)) (* Reflecting it into the effect *) let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (f ())) s0) (* Instead of that cumbersome encoding with the explicitly monadic handler, we can leverage handle_with and it in direct style. The version below is essentially the same, but without any need to write binds, returns, and Op nodes. Note how the layering of the effects is seamlessly handled except for the need of a small annotation. To apply the handled stacked computation to the initial state, there is no bind or fmap+join, just application to s0. *) let catchST #a #labs (f: unit -> Alg a (Read::Write::labs)) (s0:state) : Alg (a & state) labs = handle_with #_ #(state -> Alg _ labs) #_ #labs f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | _ -> defh) s0 (* Of course, we can also fully run computations into pure functions if no labels remain *) let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0) (* We could also handle it directly if no labels remain, without providing a default case. F* can prove the match is complete. Note the minimal superficial differences to catchST. *) let runST2 #a #labs (f: unit -> Alg a (Read::Write::[])) (s0:state) : Alg (a & state) [] = handle_with #_ #(state -> Alg _ []) #_ #[] f (fun x s -> (x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s) s0 (* We can interpret state+exceptions as monadic computations in the two usual ways: *) let run_stexn #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option (a & state) = run (fun () -> catchE (fun () -> catchST f s_0)) let run_exnst #a (f : unit -> Alg a [Write; Raise; Read]) (s_0:state) : option a & state = run (fun () -> catchST (fun () -> catchE f) s_0) (***** There are many other ways in which to program with handlers, we show a few in what follows. *) (* Unary read handler which just provides s0 *) let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = fun _ k -> k s0 (* Handling only Read *) let handle_read (#a:Type) (#labs:ops) (f : unit -> Alg a (Read::labs)) (h : handler_op Read a labs) : Alg a labs = handle_with f (fun x -> x) (function Read -> h | _ -> defh) (* A handler for write which handles Reads in the continuation with the state at hand. Note that `k` is automatically subcomped to ignore a label. *) let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s) (* Handling writes with the handler above *) let handle_write (#a:Type) (#labs:ops) (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_with f (fun x -> x) (function Write -> write_handler | _ -> defh) (* Handling state by 1) handling writes and all the reads under them via the write handler above 2) handling the initial Reads. *) let handle_st (a:Type) (labs: ops) (f : unit -> Alg a (Write::Read::labs)) (s0:state) : Alg a labs = handle_read (fun () -> handle_write f) (fun _ k -> k s0) (* Widening the domain of a handler by leaving some operations in labs0) (untouched. Requires being able to compare labels. *) let widen_handler (#b:_) (#labs0 #labs1:_) (h:handler labs0 b labs1) : handler (labs0@labs1) b labs1 = fun op -> (* This relies on decidable equality of operation labels, * or at least on being able to decide whether `op` is in `labs0` * or not. Since currently they are an `eqtype`, `mem` will do it. *) mem_memP op labs0; // "mem decides memP" if op `mem` labs0 then h op else defh (* Partial handling *) let handle_sub (#a #b:_) (#labs0 #labs1:_) (f : unit -> Alg a (labs0@labs1)) (v : a -> Alg b labs1) (h : handler labs0 b labs1) : Alg b labs1 = handle_with f v (widen_handler h) let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h) let handle_one (#a:_) (#o:op) (#labs1:_) ($f : unit -> Alg a (o::labs1)) (h : handler_op o a labs1) : Alg a labs1 = handle_with f (fun x -> x) (widen_handler_1 h) let append_single (a:Type) (x:a) (l:list a) : Lemma (x::l == [x]@l) [SMTPat (x::l)] = () let handle_raise #a #labs (f : unit -> Alg a (Raise::labs)) (g : unit -> Alg a labs) : Alg a labs = handle_one f (fun _ _ -> g ()) let handle_read' #a #labs (f : unit -> Alg a (Read::labs)) (s:state) : Alg a labs = handle_one f (fun _ k -> k s) let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s) let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ()) let handler_raise #a : handler [Raise; Write; Read] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | _ -> defh let handler_raise_write #a : handler [Raise; Write] (option a & state) [Write; Read] = function | Raise -> (fun i k -> (None, get ())) | Write -> (fun i k -> handle_write' k) (* Running by handling one operation at a time *) let run_tree #a (f : unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> handle_read' (fun () -> handle_write' (fun () -> handle_with f handle_return handler_raise)) s0) (* Running state+exceptions *) let runSTE #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : Alg (option a & state) [] = handle_with #_ #(state -> Alg (option a & state) []) #[Raise; Write; Read] #[] f (fun x s -> (Some x, s)) (function Read -> fun _ k s -> k s s | Write -> fun s k _ -> k () s | Raise -> fun e k s -> (None, s)) s0 (* And into pure *) let runSTE_pure #a (f: unit -> Alg a [Raise; Write; Read]) (s0:state) : option a & state = run (fun () -> runSTE f s0) (*** Interps into other effects *) let interp_pure_tree #a (t : tree a []) : Tot a = match t with | Return x -> x let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_tree (reify (f ())) let rec interp_rd_tree #a (t : tree a [Read]) (s:state) : Tot a = match t with | Return x -> x | Op Read _ k -> interp_rd_tree (k s) s let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s let rec interp_rdwr_tree #a (t : tree a [Read; Write]) (s:state) : Tot (a & state) = match t with | Return x -> (x, s) | Op Read _ k -> interp_rdwr_tree (k s) s | Op Write s k -> interp_rdwr_tree (k ()) s let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s let rec interp_read_raise_tree #a (t : tree a [Read; Raise]) (s:state) : either exn a = match t with | Return x -> Inr x | Op Read _ k -> interp_read_raise_tree (k s) s | Op Raise e k -> Inl e let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s let rec interp_all_tree #a (t : tree a [Read; Write; Raise]) (s:state) : Tot (option a & state) = match t with | Return x -> (Some x, s) | Op Read _ k -> interp_all_tree (k s) s | Op Write s k -> interp_all_tree (k ()) s | Op Raise e k -> (None, s) let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s //let action_input (a:action 'i 'o) = 'i //let action_output (a:action 'i 'o) = 'o // //let handler_ty (a:action _ _) (b:Type) (labs:list eff_label) = // action_input a -> // (action_output a -> tree b labs) -> tree b labs // //let dpi31 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : a = // let (| x, y, z |) = t in x // //let dpi32 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : b (dpi31 t) = // let (| x, y, z |) = t in y // //let dpi33 (#a:Type) (#b:a->Type) (#c:(x:a->b x->Type)) (t : (x:a & y:b x & c x y)) : c (dpi31 t) (dpi32 t) = // let (| x, y, z |) = t in z //handler_ty (dpi33 (action_of l)) b labs //F* complains this is not a function //let (| _, _, a |) = action_of l in //handler_ty a b labs (*** Other ways to define handlers *) (* A generic handler for a (single) label l. Anyway a special case of handle_tree. *) val handle (#a #b:_) (#labs:_) (o:op) (f:tree a (o::labs)) (h:handler_tree_op o b labs) (v: a -> tree b labs) : tree b labs let rec handle #a #b #labs l f h v = match f with | Return x -> v x | Op act i k -> if act = l then h i (fun o -> handle l (k o) h v) else begin let k' o : tree b labs = handle l (k o) h v in Op act i k' end (* Easy enough to handle 2 labels at once. Again a special case of handle_tree too. *) val handle2 (#a #b:_) (#labs:_) (l1 l2 : op) (f:tree a (l1::l2::labs)) (h1:handler_tree_op l1 b labs) (h2:handler_tree_op l2 b labs) (v : a -> tree b labs) : tree b labs let rec handle2 #a #b #labs l1 l2 f h1 h2 v = match f with | Return x -> v x | Op act i k -> if act = l1 then h1 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else if act = l2 then h2 i (fun o -> handle2 l1 l2 (k o) h1 h2 v) else begin let k' o : tree b labs = handle2 l1 l2 (k o) h1 h2 v in Op act i k' end let catch0' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle Raise t1 (fun i k -> t2) (fun x -> Return x) let catch0'' #a #labs (t1 : tree a (Raise::labs)) (t2 : tree a labs) : tree a labs = handle_tree t1 (fun x -> Return x) (function Raise -> (fun i k -> t2) | act -> (fun i k -> Op act i k)) (*** Connection to Lattice *) let baseop = o:op{not (Other? o)} let trlab : o:baseop -> L.eff_label = function | Read -> L.RD | Write -> L.WR | Raise -> L.EXN let trlab' = function | L.RD -> Read | L.WR -> Write | L.EXN -> Raise let trlabs = List.Tot.map trlab let trlabs' = List.Tot.map trlab' let rec lab_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` ls <==> (trlab l) `mem` (trlabs ls)) [SMTPat (l `memP` ls)] // needed for interp_into_lattice_tree below = match ls with | [] -> () | l1::ls -> lab_corr l ls (* Tied to the particular tree of Lattice.fst *) (* no datatype subtyping *) let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x) let rec fixup_corr (l:baseop) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> l `memP` ls) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_corr l ls let rec fixup_no_other (l:op{Other? l}) (ls:list baseop) : Lemma (l `memP` (fixup ls) <==> False) [SMTPat (l `memP` (fixup ls))] = match ls with | [] -> () | l1::ls -> fixup_no_other l ls let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ()) let lattice_put_repr (s:state) : L.repr unit [L.WR] = reify (L.put s) let lattice_raise_repr (#a:Type) () : L.repr a [L.EXN] = reify (L.raise #a ()) // This would be a lot nicer if it was done in L.EFF itself, // but the termination proof fails since it has no logical payload. let rec interp_into_lattice_tree #a (#labs:list baseop) (t : tree a (fixup labs)) : L.repr a (trlabs labs) = match t with | Return x -> L.return _ x | Op Read i k -> L.bind _ _ _ _ (lattice_get_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Write i k -> L.bind _ _ _ _ (lattice_put_repr i) (fun x -> interp_into_lattice_tree #a #labs (k x)) | Op Raise i k -> L.bind _ _ _ _ (lattice_raise_repr ()) (fun x -> interp_into_lattice_tree #a #labs (k x)) let interp_into_lattice #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : Lattice.EFF a (trlabs labs) = Lattice.EFF?.reflect (interp_into_lattice_tree (reify (f ()))) // This is rather silly: we reflect and then reify. Maybe define interp_into_lattice // directly? let interp_full #a (#labs:list baseop) (f : unit -> Alg a (fixup labs)) : L.repr a (trlabs labs) = reify (interp_into_lattice #a #labs f) (* Doing it directly. *) type sem0 (a:Type) : Type = state -> Tot (either exn a & state) let abides' (f : sem0 'a) (labs:list baseop) : prop = (Read `memP` labs \/ (forall s0 s1. fst (f s0) == fst (f s1))) /\ (Write `memP` labs \/ (forall s0. snd (f s0) == s0)) /\ (Raise `memP` labs \/ (forall s0. Inr? (fst (f s0)))) type sem (a:Type) (labs : list baseop) = r:(sem0 a){abides' r labs}
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lattice.fst.checked", "FStar.Universe.fsti.checked", "FStar.Tactics.V2.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Monotonic.Pure.fst.checked", "FStar.List.Tot.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "Alg.fst" }
[ { "abbrev": true, "full_module": "Lattice", "short_module": "L" }, { "abbrev": false, "full_module": "FStar.Universe", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Alg.tree a (Alg.fixup labs) -> Alg.sem a labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.baseop", "Alg.tree", "Alg.fixup", "Alg.state", "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.either", "Prims.exn", "FStar.Pervasives.Inr", "FStar.Pervasives.Native.tuple2", "Alg.op_inp", "Alg.Read", "Alg.op_out", "Alg.tree0", "Alg.sem", "Prims.int", "Alg.interp_sem", "Alg.Write", "Alg.Raise", "FStar.Pervasives.Inl" ]
[ "recursion" ]
false
false
false
false
false
let rec interp_sem #a (#labs: list baseop) (t: tree a (fixup labs)) : sem a labs =
match t with | Return x -> fun s0 -> (Inr x, s0) | Op Read _ k -> let r:sem a labs = fun s0 -> interp_sem #a #labs (k s0) s0 in r | Op Write s k -> fun s0 -> interp_sem #a #labs (k ()) s | Op Raise e k -> fun s0 -> (Inl e, s0)
false
EverCrypt.DRBG.fst
EverCrypt.DRBG.mk_generate
val mk_generate: #a:supported_alg -> EverCrypt.HMAC.compute_st a -> generate_st a
val mk_generate: #a:supported_alg -> EverCrypt.HMAC.compute_st a -> generate_st a
let mk_generate #a hmac output st n additional_input additional_input_len = if additional_input_len >. max_additional_input_length || n >. max_output_length then false else ( push_frame(); let ok = mk_reseed hmac st additional_input additional_input_len in let result = if not ok then false else begin let st_s = !*st in let b = mk_generate hmac output (p st_s) n additional_input_len additional_input in b (* This used to be true, which is fishy *) end in let h1 = get () in pop_frame(); let h2 = get () in frame_invariant (B.loc_all_regions_from false (HS.get_tip h1)) st h1 h2; result )
{ "file_name": "providers/evercrypt/fst/EverCrypt.DRBG.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 10, "end_line": 222, "start_col": 0, "start_line": 201 }
module EverCrypt.DRBG open FStar.HyperStack.ST open Lib.IntTypes open Spec.Hash.Definitions module HS = FStar.HyperStack module B = LowStar.Buffer module S = Spec.HMAC_DRBG open Hacl.HMAC_DRBG open Lib.RandomBuffer.System open LowStar.BufferOps friend Hacl.HMAC_DRBG friend EverCrypt.HMAC #set-options "--max_ifuel 0 --max_fuel 0 --z3rlimit 50" /// Some duplication from Hacl.HMAC_DRBG because we don't want clients to depend on it /// /// Respects EverCrypt convention and reverses order of buf_len, buf arguments [@CAbstractStruct] noeq type state_s: supported_alg -> Type0 = | SHA1_s : state SHA1 -> state_s SHA1 | SHA2_256_s: state SHA2_256 -> state_s SHA2_256 | SHA2_384_s: state SHA2_384 -> state_s SHA2_384 | SHA2_512_s: state SHA2_512 -> state_s SHA2_512 let invert_state_s (a:supported_alg): Lemma (requires True) (ensures inversion (state_s a)) [ SMTPat (state_s a) ] = allow_inversion (state_s a) /// Only call this function in extracted code with a known `a` inline_for_extraction noextract let p #a (s:state_s a) : Hacl.HMAC_DRBG.state a = match a with | SHA1 -> let SHA1_s p = s in p | SHA2_256 -> let SHA2_256_s p = s in p | SHA2_384 -> let SHA2_384_s p = s in p | SHA2_512 -> let SHA2_512_s p = s in p let freeable_s #a st = freeable (p st) let footprint_s #a st = footprint (p st) let invariant_s #a st h = invariant (p st) h let repr #a st h = let st = B.get h st 0 in repr (p st) h let loc_includes_union_l_footprint_s #a l1 l2 st = B.loc_includes_union_l l1 l2 (footprint_s st) let invariant_loc_in_footprint #a st m = () let frame_invariant #a l st h0 h1 = () /// State allocation // Would like to specialize alloca in each branch, but two calls to StackInline // functions in the same block lead to variable redefinitions at extraction. let alloca a = let st = match a with | SHA1 -> SHA1_s (alloca a) | SHA2_256 -> SHA2_256_s (alloca a) | SHA2_384 -> SHA2_384_s (alloca a) | SHA2_512 -> SHA2_512_s (alloca a) in B.alloca st 1ul let create_in a r = let st = match a with | SHA1 -> SHA1_s (create_in SHA1 r) | SHA2_256 -> SHA2_256_s (create_in SHA2_256 r) | SHA2_384 -> SHA2_384_s (create_in SHA2_384 r) | SHA2_512 -> SHA2_512_s (create_in SHA2_512 r) in B.malloc r st 1ul let create a = create_in a HS.root /// Instantiate function inline_for_extraction noextract val mk_instantiate: #a:supported_alg -> EverCrypt.HMAC.compute_st a -> instantiate_st a let mk_instantiate #a hmac st personalization_string personalization_string_len = if personalization_string_len >. max_personalization_string_length then false else let entropy_input_len = min_length a in let nonce_len = min_length a /. 2ul in let min_entropy = entropy_input_len +! nonce_len in push_frame(); assert_norm (range (v min_entropy) U32); let entropy = B.alloca (u8 0) min_entropy in let ok = randombytes entropy min_entropy in let result = if not ok then false else begin let entropy_input = B.sub entropy 0ul entropy_input_len in let nonce = B.sub entropy entropy_input_len nonce_len in S.hmac_input_bound a; let st_s = !*st in mk_instantiate hmac (p st_s) entropy_input_len entropy_input nonce_len nonce personalization_string_len personalization_string; true end in pop_frame(); result (** @type: true *) val instantiate_sha1 : instantiate_st SHA1 (** @type: true *) val instantiate_sha2_256: instantiate_st SHA2_256 (** @type: true *) val instantiate_sha2_384: instantiate_st SHA2_384 (** @type: true *) val instantiate_sha2_512: instantiate_st SHA2_512 let instantiate_sha1 = mk_instantiate EverCrypt.HMAC.compute_sha1 let instantiate_sha2_256 = mk_instantiate EverCrypt.HMAC.compute_sha2_256 let instantiate_sha2_384 = mk_instantiate EverCrypt.HMAC.compute_sha2_384 let instantiate_sha2_512 = mk_instantiate EverCrypt.HMAC.compute_sha2_512 /// Reseed function inline_for_extraction noextract val mk_reseed: #a:supported_alg -> EverCrypt.HMAC.compute_st a -> reseed_st a let mk_reseed #a hmac st additional_input additional_input_len = if additional_input_len >. max_additional_input_length then false else let entropy_input_len = min_length a in push_frame(); let entropy_input = B.alloca (u8 0) entropy_input_len in let ok = randombytes entropy_input entropy_input_len in let result = if not ok then false else begin S.hmac_input_bound a; let st_s = !*st in mk_reseed hmac (p st_s) entropy_input_len entropy_input additional_input_len additional_input; true end in pop_frame(); result (** @type: true *) val reseed_sha1 : reseed_st SHA1 (** @type: true *) val reseed_sha2_256: reseed_st SHA2_256 (** @type: true *) val reseed_sha2_384: reseed_st SHA2_384 (** @type: true *) val reseed_sha2_512: reseed_st SHA2_512 let reseed_sha1 = mk_reseed EverCrypt.HMAC.compute_sha1 let reseed_sha2_256 = mk_reseed EverCrypt.HMAC.compute_sha2_256 let reseed_sha2_384 = mk_reseed EverCrypt.HMAC.compute_sha2_384 let reseed_sha2_512 = mk_reseed EverCrypt.HMAC.compute_sha2_512 /// Generate function inline_for_extraction noextract
{ "checked_file": "/", "dependencies": [ "Spec.HMAC_DRBG.fsti.checked", "Spec.Hash.Definitions.fst.checked", "prims.fst.checked", "LowStar.BufferOps.fst.checked", "LowStar.Buffer.fst.checked", "Lib.RandomBuffer.System.fsti.checked", "Lib.Memzero0.fsti.checked", "Lib.IntTypes.fsti.checked", "Hacl.HMAC_DRBG.fst.checked", "Hacl.HMAC_DRBG.fst.checked", "FStar.UInt32.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked", "EverCrypt.HMAC.fst.checked" ], "interface_file": true, "source_file": "EverCrypt.DRBG.fst" }
[ { "abbrev": false, "full_module": "LowStar.BufferOps", "short_module": null }, { "abbrev": false, "full_module": "Lib.RandomBuffer.System", "short_module": null }, { "abbrev": false, "full_module": "Hacl.HMAC_DRBG", "short_module": null }, { "abbrev": true, "full_module": "Spec.HMAC_DRBG", "short_module": "S" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": true, "full_module": "Spec.HMAC_DRBG", "short_module": "S" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "EverCrypt", "short_module": null }, { "abbrev": false, "full_module": "EverCrypt", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
hmac: EverCrypt.HMAC.compute_st a -> EverCrypt.DRBG.generate_st a
Prims.Tot
[ "total" ]
[]
[ "Hacl.HMAC_DRBG.supported_alg", "EverCrypt.HMAC.compute_st", "LowStar.Buffer.buffer", "Lib.IntTypes.uint8", "EverCrypt.DRBG.state", "Lib.IntTypes.size_t", "Prims.op_BarBar", "Lib.IntTypes.op_Greater_Dot", "Lib.IntTypes.U32", "Hacl.HMAC_DRBG.max_additional_input_length", "Hacl.HMAC_DRBG.max_output_length", "Prims.bool", "Prims.unit", "EverCrypt.DRBG.frame_invariant", "LowStar.Monotonic.Buffer.loc_all_regions_from", "FStar.Monotonic.HyperStack.get_tip", "FStar.Monotonic.HyperStack.mem", "FStar.HyperStack.ST.get", "FStar.HyperStack.ST.pop_frame", "Prims.op_Negation", "Hacl.HMAC_DRBG.mk_generate", "EverCrypt.DRBG.p", "EverCrypt.DRBG.state_s", "LowStar.BufferOps.op_Bang_Star", "LowStar.Buffer.trivial_preorder", "EverCrypt.DRBG.mk_reseed", "FStar.HyperStack.ST.push_frame" ]
[]
false
false
false
false
false
let mk_generate #a hmac output st n additional_input additional_input_len =
if additional_input_len >. max_additional_input_length || n >. max_output_length then false else (push_frame (); let ok = mk_reseed hmac st additional_input additional_input_len in let result = if not ok then false else let st_s = !*st in let b = mk_generate hmac output (p st_s) n additional_input_len additional_input in b in let h1 = get () in pop_frame (); let h2 = get () in frame_invariant (B.loc_all_regions_from false (HS.get_tip h1)) st h1 h2; result)
false
LowParse.Spec.Tac.Enum.fst
LowParse.Spec.Tac.Enum.forall_maybe_enum_key_unknown_tac
val forall_maybe_enum_key_unknown_tac: Prims.unit -> T.Tac unit
val forall_maybe_enum_key_unknown_tac: Prims.unit -> T.Tac unit
let forall_maybe_enum_key_unknown_tac () : T.Tac unit = let open T in let x = intro () in norm [delta; iota; zeta; primops]; trivial (); qed ()
{ "file_name": "src/lowparse/LowParse.Spec.Tac.Enum.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 12, "end_line": 84, "start_col": 0, "start_line": 79 }
module LowParse.Spec.Tac.Enum include LowParse.Spec.Enum module T = LowParse.TacLib // // The enum tactic solves goals of type ?u:eqtype with enum types that are // in the environment at type Type0 // So typechecking such uvars fails since F* 2635 bug fix // (since uvar solutions are checked with smt off) // // To circumvent that, we use t_apply with tc_resolve_uvars flag on, // so that ?u will be typechecked as soon as it is resolved, // resulting in an smt guard that will be added to the proofstate // let apply (t:T.term) : T.Tac unit = T.t_apply true false true t noextract let rec enum_tac_gen (t_cons_nil: T.term) (t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = match e with | [] -> T.fail "enum_tac_gen: e must be cons" | [_] -> apply t_cons_nil; T.iseq [ T.solve_vc; T.solve_vc; ]; T.qed () | _ :: e_ -> apply t_cons; T.iseq [ T.solve_vc; (fun () -> enum_tac_gen t_cons_nil t_cons e_); ]; T.qed () noextract let maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote maybe_enum_key_of_repr'_t_cons_nil') (quote maybe_enum_key_of_repr'_t_cons') e noextract let enum_repr_of_key_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote enum_repr_of_key_cons_nil') (quote enum_repr_of_key_cons') e noextract let synth_maybe_enum_key_inv_unknown_tac (#key: Type) (x: key) : T.Tac unit = let open T in destruct (quote x); to_all_goals (fun () -> let breq = intros_until_squash () in rewrite breq; norm [delta; iota; zeta; primops]; trivial (); qed () ); qed () noextract let forall_maybe_enum_key_known_tac () : T.Tac unit = let open T in norm [delta; iota; zeta; primops]; trivial (); qed ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.TacLib.fst.checked", "LowParse.Spec.Enum.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Spec.Tac.Enum.fst" }
[ { "abbrev": true, "full_module": "LowParse.TacLib", "short_module": "T" }, { "abbrev": false, "full_module": "LowParse.Spec.Enum", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Tactics.V1.Derived.qed", "FStar.Tactics.V1.Derived.trivial", "FStar.Stubs.Tactics.V1.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Pervasives.primops", "Prims.Nil", "FStar.Stubs.Reflection.Types.binder", "FStar.Stubs.Tactics.V1.Builtins.intro" ]
[]
false
true
false
false
false
let forall_maybe_enum_key_unknown_tac () : T.Tac unit =
let open T in let x = intro () in norm [delta; iota; zeta; primops]; trivial (); qed ()
false
LowParse.Spec.Tac.Enum.fst
LowParse.Spec.Tac.Enum.apply
val apply (t: T.term) : T.Tac unit
val apply (t: T.term) : T.Tac unit
let apply (t:T.term) : T.Tac unit = T.t_apply true false true t
{ "file_name": "src/lowparse/LowParse.Spec.Tac.Enum.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 29, "end_line": 18, "start_col": 0, "start_line": 17 }
module LowParse.Spec.Tac.Enum include LowParse.Spec.Enum module T = LowParse.TacLib // // The enum tactic solves goals of type ?u:eqtype with enum types that are // in the environment at type Type0 // So typechecking such uvars fails since F* 2635 bug fix // (since uvar solutions are checked with smt off) // // To circumvent that, we use t_apply with tc_resolve_uvars flag on, // so that ?u will be typechecked as soon as it is resolved, // resulting in an smt guard that will be added to the proofstate //
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.TacLib.fst.checked", "LowParse.Spec.Enum.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Spec.Tac.Enum.fst" }
[ { "abbrev": true, "full_module": "LowParse.TacLib", "short_module": "T" }, { "abbrev": false, "full_module": "LowParse.Spec.Enum", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: FStar.Stubs.Reflection.Types.term -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Tactics.V1.Builtins.t_apply", "Prims.unit" ]
[]
false
true
false
false
false
let apply (t: T.term) : T.Tac unit =
T.t_apply true false true t
false
LowParse.Spec.Tac.Enum.fst
LowParse.Spec.Tac.Enum.synth_maybe_enum_key_inv_unknown_tac
val synth_maybe_enum_key_inv_unknown_tac (#key: Type) (x: key) : T.Tac unit
val synth_maybe_enum_key_inv_unknown_tac (#key: Type) (x: key) : T.Tac unit
let synth_maybe_enum_key_inv_unknown_tac (#key: Type) (x: key) : T.Tac unit = let open T in destruct (quote x); to_all_goals (fun () -> let breq = intros_until_squash () in rewrite breq; norm [delta; iota; zeta; primops]; trivial (); qed () ); qed ()
{ "file_name": "src/lowparse/LowParse.Spec.Tac.Enum.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 10, "end_line": 69, "start_col": 0, "start_line": 59 }
module LowParse.Spec.Tac.Enum include LowParse.Spec.Enum module T = LowParse.TacLib // // The enum tactic solves goals of type ?u:eqtype with enum types that are // in the environment at type Type0 // So typechecking such uvars fails since F* 2635 bug fix // (since uvar solutions are checked with smt off) // // To circumvent that, we use t_apply with tc_resolve_uvars flag on, // so that ?u will be typechecked as soon as it is resolved, // resulting in an smt guard that will be added to the proofstate // let apply (t:T.term) : T.Tac unit = T.t_apply true false true t noextract let rec enum_tac_gen (t_cons_nil: T.term) (t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = match e with | [] -> T.fail "enum_tac_gen: e must be cons" | [_] -> apply t_cons_nil; T.iseq [ T.solve_vc; T.solve_vc; ]; T.qed () | _ :: e_ -> apply t_cons; T.iseq [ T.solve_vc; (fun () -> enum_tac_gen t_cons_nil t_cons e_); ]; T.qed () noextract let maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote maybe_enum_key_of_repr'_t_cons_nil') (quote maybe_enum_key_of_repr'_t_cons') e noextract let enum_repr_of_key_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote enum_repr_of_key_cons_nil') (quote enum_repr_of_key_cons') e
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.TacLib.fst.checked", "LowParse.Spec.Enum.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Spec.Tac.Enum.fst" }
[ { "abbrev": true, "full_module": "LowParse.TacLib", "short_module": "T" }, { "abbrev": false, "full_module": "LowParse.Spec.Enum", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: key -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.V1.Derived.qed", "Prims.unit", "LowParse.TacLib.to_all_goals", "FStar.Tactics.V1.Derived.trivial", "FStar.Stubs.Tactics.V1.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Pervasives.primops", "Prims.Nil", "FStar.Stubs.Tactics.V1.Builtins.rewrite", "FStar.Stubs.Reflection.Types.binder", "LowParse.TacLib.intros_until_squash", "FStar.Tactics.V1.Derived.destruct", "FStar.Stubs.Reflection.Types.term" ]
[]
false
true
false
false
false
let synth_maybe_enum_key_inv_unknown_tac (#key: Type) (x: key) : T.Tac unit =
let open T in destruct (quote x); to_all_goals (fun () -> let breq = intros_until_squash () in rewrite breq; norm [delta; iota; zeta; primops]; trivial (); qed ()); qed ()
false
LowParse.Spec.Tac.Enum.fst
LowParse.Spec.Tac.Enum.enum_repr_of_key_tac
val enum_repr_of_key_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit
val enum_repr_of_key_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit
let enum_repr_of_key_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote enum_repr_of_key_cons_nil') (quote enum_repr_of_key_cons') e
{ "file_name": "src/lowparse/LowParse.Spec.Tac.Enum.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 82, "end_line": 56, "start_col": 0, "start_line": 52 }
module LowParse.Spec.Tac.Enum include LowParse.Spec.Enum module T = LowParse.TacLib // // The enum tactic solves goals of type ?u:eqtype with enum types that are // in the environment at type Type0 // So typechecking such uvars fails since F* 2635 bug fix // (since uvar solutions are checked with smt off) // // To circumvent that, we use t_apply with tc_resolve_uvars flag on, // so that ?u will be typechecked as soon as it is resolved, // resulting in an smt guard that will be added to the proofstate // let apply (t:T.term) : T.Tac unit = T.t_apply true false true t noextract let rec enum_tac_gen (t_cons_nil: T.term) (t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = match e with | [] -> T.fail "enum_tac_gen: e must be cons" | [_] -> apply t_cons_nil; T.iseq [ T.solve_vc; T.solve_vc; ]; T.qed () | _ :: e_ -> apply t_cons; T.iseq [ T.solve_vc; (fun () -> enum_tac_gen t_cons_nil t_cons e_); ]; T.qed () noextract let maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote maybe_enum_key_of_repr'_t_cons_nil') (quote maybe_enum_key_of_repr'_t_cons') e
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.TacLib.fst.checked", "LowParse.Spec.Enum.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Spec.Tac.Enum.fst" }
[ { "abbrev": true, "full_module": "LowParse.TacLib", "short_module": "T" }, { "abbrev": false, "full_module": "LowParse.Spec.Enum", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
e: Prims.list (key * repr) -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Pervasives.Native.tuple2", "LowParse.Spec.Tac.Enum.enum_tac_gen", "Prims.unit", "FStar.Stubs.Reflection.Types.term", "LowParse.Spec.Enum.enum_repr_of_key_cons'", "LowParse.Spec.Enum.enum_repr_of_key_cons_nil'" ]
[]
false
true
false
false
false
let enum_repr_of_key_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit =
enum_tac_gen (quote enum_repr_of_key_cons_nil') (quote enum_repr_of_key_cons') e
false
LowParse.Spec.Tac.Enum.fst
LowParse.Spec.Tac.Enum.forall_maybe_enum_key_known_tac
val forall_maybe_enum_key_known_tac: Prims.unit -> T.Tac unit
val forall_maybe_enum_key_known_tac: Prims.unit -> T.Tac unit
let forall_maybe_enum_key_known_tac () : T.Tac unit = let open T in norm [delta; iota; zeta; primops]; trivial (); qed ()
{ "file_name": "src/lowparse/LowParse.Spec.Tac.Enum.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 12, "end_line": 76, "start_col": 0, "start_line": 72 }
module LowParse.Spec.Tac.Enum include LowParse.Spec.Enum module T = LowParse.TacLib // // The enum tactic solves goals of type ?u:eqtype with enum types that are // in the environment at type Type0 // So typechecking such uvars fails since F* 2635 bug fix // (since uvar solutions are checked with smt off) // // To circumvent that, we use t_apply with tc_resolve_uvars flag on, // so that ?u will be typechecked as soon as it is resolved, // resulting in an smt guard that will be added to the proofstate // let apply (t:T.term) : T.Tac unit = T.t_apply true false true t noextract let rec enum_tac_gen (t_cons_nil: T.term) (t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = match e with | [] -> T.fail "enum_tac_gen: e must be cons" | [_] -> apply t_cons_nil; T.iseq [ T.solve_vc; T.solve_vc; ]; T.qed () | _ :: e_ -> apply t_cons; T.iseq [ T.solve_vc; (fun () -> enum_tac_gen t_cons_nil t_cons e_); ]; T.qed () noextract let maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote maybe_enum_key_of_repr'_t_cons_nil') (quote maybe_enum_key_of_repr'_t_cons') e noextract let enum_repr_of_key_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote enum_repr_of_key_cons_nil') (quote enum_repr_of_key_cons') e noextract let synth_maybe_enum_key_inv_unknown_tac (#key: Type) (x: key) : T.Tac unit = let open T in destruct (quote x); to_all_goals (fun () -> let breq = intros_until_squash () in rewrite breq; norm [delta; iota; zeta; primops]; trivial (); qed () ); qed ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.TacLib.fst.checked", "LowParse.Spec.Enum.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Spec.Tac.Enum.fst" }
[ { "abbrev": true, "full_module": "LowParse.TacLib", "short_module": "T" }, { "abbrev": false, "full_module": "LowParse.Spec.Enum", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Tactics.V1.Derived.qed", "FStar.Tactics.V1.Derived.trivial", "FStar.Stubs.Tactics.V1.Builtins.norm", "Prims.Cons", "FStar.Pervasives.norm_step", "FStar.Pervasives.delta", "FStar.Pervasives.iota", "FStar.Pervasives.zeta", "FStar.Pervasives.primops", "Prims.Nil" ]
[]
false
true
false
false
false
let forall_maybe_enum_key_known_tac () : T.Tac unit =
let open T in norm [delta; iota; zeta; primops]; trivial (); qed ()
false
LowParse.Spec.Tac.Enum.fst
LowParse.Spec.Tac.Enum.maybe_enum_key_of_repr_tac
val maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit
val maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit
let maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = enum_tac_gen (quote maybe_enum_key_of_repr'_t_cons_nil') (quote maybe_enum_key_of_repr'_t_cons') e
{ "file_name": "src/lowparse/LowParse.Spec.Tac.Enum.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 100, "end_line": 49, "start_col": 0, "start_line": 45 }
module LowParse.Spec.Tac.Enum include LowParse.Spec.Enum module T = LowParse.TacLib // // The enum tactic solves goals of type ?u:eqtype with enum types that are // in the environment at type Type0 // So typechecking such uvars fails since F* 2635 bug fix // (since uvar solutions are checked with smt off) // // To circumvent that, we use t_apply with tc_resolve_uvars flag on, // so that ?u will be typechecked as soon as it is resolved, // resulting in an smt guard that will be added to the proofstate // let apply (t:T.term) : T.Tac unit = T.t_apply true false true t noextract let rec enum_tac_gen (t_cons_nil: T.term) (t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = match e with | [] -> T.fail "enum_tac_gen: e must be cons" | [_] -> apply t_cons_nil; T.iseq [ T.solve_vc; T.solve_vc; ]; T.qed () | _ :: e_ -> apply t_cons; T.iseq [ T.solve_vc; (fun () -> enum_tac_gen t_cons_nil t_cons e_); ]; T.qed ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.TacLib.fst.checked", "LowParse.Spec.Enum.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Spec.Tac.Enum.fst" }
[ { "abbrev": true, "full_module": "LowParse.TacLib", "short_module": "T" }, { "abbrev": false, "full_module": "LowParse.Spec.Enum", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
e: Prims.list (key * repr) -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Pervasives.Native.tuple2", "LowParse.Spec.Tac.Enum.enum_tac_gen", "Prims.unit", "FStar.Stubs.Reflection.Types.term", "LowParse.Spec.Enum.maybe_enum_key_of_repr'_t_cons'", "LowParse.Spec.Enum.maybe_enum_key_of_repr'_t_cons_nil'" ]
[]
false
true
false
false
false
let maybe_enum_key_of_repr_tac (#key #repr: Type) (e: list (key * repr)) : T.Tac unit =
enum_tac_gen (quote maybe_enum_key_of_repr'_t_cons_nil') (quote maybe_enum_key_of_repr'_t_cons') e
false
LowParse.Spec.Tac.Enum.fst
LowParse.Spec.Tac.Enum.enum_tac_gen
val enum_tac_gen (t_cons_nil t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit
val enum_tac_gen (t_cons_nil t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit
let rec enum_tac_gen (t_cons_nil: T.term) (t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit = match e with | [] -> T.fail "enum_tac_gen: e must be cons" | [_] -> apply t_cons_nil; T.iseq [ T.solve_vc; T.solve_vc; ]; T.qed () | _ :: e_ -> apply t_cons; T.iseq [ T.solve_vc; (fun () -> enum_tac_gen t_cons_nil t_cons e_); ]; T.qed ()
{ "file_name": "src/lowparse/LowParse.Spec.Tac.Enum.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 12, "end_line": 42, "start_col": 0, "start_line": 21 }
module LowParse.Spec.Tac.Enum include LowParse.Spec.Enum module T = LowParse.TacLib // // The enum tactic solves goals of type ?u:eqtype with enum types that are // in the environment at type Type0 // So typechecking such uvars fails since F* 2635 bug fix // (since uvar solutions are checked with smt off) // // To circumvent that, we use t_apply with tc_resolve_uvars flag on, // so that ?u will be typechecked as soon as it is resolved, // resulting in an smt guard that will be added to the proofstate // let apply (t:T.term) : T.Tac unit = T.t_apply true false true t
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.TacLib.fst.checked", "LowParse.Spec.Enum.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Spec.Tac.Enum.fst" }
[ { "abbrev": true, "full_module": "LowParse.TacLib", "short_module": "T" }, { "abbrev": false, "full_module": "LowParse.Spec.Enum", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Tac", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t_cons_nil: FStar.Stubs.Reflection.Types.term -> t_cons: FStar.Stubs.Reflection.Types.term -> e: Prims.list (key * repr) -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Stubs.Reflection.Types.term", "Prims.list", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.V1.Derived.fail", "Prims.unit", "FStar.Tactics.V1.Derived.qed", "FStar.Tactics.V1.Derived.iseq", "Prims.Cons", "LowParse.TacLib.solve_vc", "Prims.Nil", "LowParse.Spec.Tac.Enum.apply", "LowParse.Spec.Tac.Enum.enum_tac_gen" ]
[ "recursion" ]
false
true
false
false
false
let rec enum_tac_gen (t_cons_nil t_cons: T.term) (#key #repr: Type) (e: list (key * repr)) : T.Tac unit =
match e with | [] -> T.fail "enum_tac_gen: e must be cons" | [_] -> apply t_cons_nil; T.iseq [T.solve_vc; T.solve_vc]; T.qed () | _ :: e_ -> apply t_cons; T.iseq [T.solve_vc; (fun () -> enum_tac_gen t_cons_nil t_cons e_)]; T.qed ()
false
Pulse.C.Types.Array.Base.fst
Pulse.C.Types.Array.Base.array_domain
val array_domain (n: Ghost.erased SZ.t) : Tot eqtype
val array_domain (n: Ghost.erased SZ.t) : Tot eqtype
let array_domain (n: Ghost.erased SZ.t) : Tot eqtype = (i: SZ.t { SZ.v i < SZ.v n })
{ "file_name": "share/steel/examples/pulse/lib/c/Pulse.C.Types.Array.Base.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 31, "end_line": 8, "start_col": 0, "start_line": 5 }
module Pulse.C.Types.Array.Base module SZ = FStar.SizeT
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.SizeT.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Pulse.C.Types.Array.Base.fst" }
[ { "abbrev": true, "full_module": "FStar.SizeT", "short_module": "SZ" }, { "abbrev": false, "full_module": "Pulse.C.Types.Array", "short_module": null }, { "abbrev": false, "full_module": "Pulse.C.Types.Array", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
n: FStar.Ghost.erased FStar.SizeT.t -> Prims.eqtype
Prims.Tot
[ "total" ]
[]
[ "FStar.Ghost.erased", "FStar.SizeT.t", "Prims.b2t", "Prims.op_LessThan", "FStar.SizeT.v", "FStar.Ghost.reveal", "Prims.eqtype" ]
[]
false
false
false
true
false
let array_domain (n: Ghost.erased SZ.t) : Tot eqtype =
(i: SZ.t{SZ.v i < SZ.v n})
false
HyE.Ideal.fsti
HyE.Ideal.conf
val conf : Prims.bool
let conf = ind_cca
{ "file_name": "examples/crypto/HyE.Ideal.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 18, "end_line": 25, "start_col": 0, "start_line": 25 }
(* Copyright 2008-2018 Microsoft Research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) module HyE.Ideal val ind_cca : bool val int_ctxt : b:bool{ ind_cca ==> b } val int_cpa : b:bool{ ind_cca ==> b }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "HyE.Ideal.fsti" }
[ { "abbrev": false, "full_module": "HyE", "short_module": null }, { "abbrev": false, "full_module": "HyE", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Prims.bool
Prims.Tot
[ "total" ]
[]
[ "HyE.Ideal.ind_cca" ]
[]
false
false
false
true
false
let conf =
ind_cca
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.fail_parser
val fail_parser : k: LowParse.Spec.Base.parser_kind -> t: Type -> Prims.Pure (LowParse.Spec.Base.tot_parser k t)
let fail_parser = tot_fail_parser
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 33, "end_line": 6, "start_col": 0, "start_line": 6 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k: LowParse.Spec.Base.parser_kind -> t: Type -> Prims.Pure (LowParse.Spec.Base.tot_parser k t)
Prims.Pure
[]
[]
[ "LowParse.Spec.Combinators.tot_fail_parser" ]
[]
false
false
false
false
false
let fail_parser =
tot_fail_parser
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_ret
val parse_ret : v: _ -> LowParse.Spec.Base.tot_parser LowParse.Spec.Combinators.parse_ret_kind _
let parse_ret = tot_parse_ret
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 29, "end_line": 9, "start_col": 0, "start_line": 9 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
v: _ -> LowParse.Spec.Base.tot_parser LowParse.Spec.Combinators.parse_ret_kind _
Prims.Tot
[ "total" ]
[]
[ "LowParse.Spec.Combinators.tot_parse_ret", "LowParse.Spec.Base.tot_parser", "LowParse.Spec.Combinators.parse_ret_kind" ]
[]
false
false
false
true
false
let parse_ret =
tot_parse_ret
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_empty
val parse_empty:parser parse_ret_kind unit
val parse_empty:parser parse_ret_kind unit
let parse_empty : parser parse_ret_kind unit = parse_ret ()
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 14, "end_line": 13, "start_col": 0, "start_line": 12 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
LowParse.Tot.Base.parser LowParse.Spec.Combinators.parse_ret_kind Prims.unit
Prims.Tot
[ "total" ]
[]
[ "LowParse.Tot.Combinators.parse_ret", "Prims.unit" ]
[]
false
false
false
true
false
let parse_empty:parser parse_ret_kind unit =
parse_ret ()
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_tagged_union_payload
val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t)
val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t)
let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 93, "end_line": 113, "start_col": 0, "start_line": 113 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
tag_of_data: (_: data_t -> tag_t) -> p: (t: tag_t -> LowParse.Tot.Base.parser k (LowParse.Spec.Base.refine_with_tag tag_of_data t)) -> tg: tag_t -> LowParse.Tot.Base.parser k data_t
Prims.Tot
[ "total" ]
[]
[ "LowParse.Spec.Combinators.tot_parse_tagged_union_payload", "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Spec.Base.refine_with_tag" ]
[]
false
false
false
false
false
let parse_tagged_union_payload #tag_t #data_t =
tot_parse_tagged_union_payload #tag_t #data_t
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_tagged_union
val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t)
val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t)
let parse_tagged_union #kt #tag_t = tot_parse_tagged_union #kt #tag_t
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 69, "end_line": 126, "start_col": 0, "start_line": 126 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t) let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t inline_for_extraction val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
pt: LowParse.Tot.Base.parser kt tag_t -> tag_of_data: (_: data_t -> tag_t) -> p: (t: tag_t -> LowParse.Tot.Base.parser k (LowParse.Spec.Base.refine_with_tag tag_of_data t)) -> LowParse.Tot.Base.parser (LowParse.Spec.Combinators.and_then_kind kt k) data_t
Prims.Tot
[ "total" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Spec.Combinators.tot_parse_tagged_union", "LowParse.Tot.Base.parser", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.Combinators.and_then_kind" ]
[]
false
false
false
false
false
let parse_tagged_union #kt #tag_t =
tot_parse_tagged_union #kt #tag_t
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.nondep_then
val nondep_then (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) : Tot (parser (and_then_kind k1 k2) (t1 * t2))
val nondep_then (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) : Tot (parser (and_then_kind k1 k2) (t1 * t2))
let nondep_then #k1 = tot_nondep_then #k1
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 41, "end_line": 186, "start_col": 0, "start_line": 186 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t) let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t inline_for_extraction val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t) let parse_tagged_union #kt #tag_t = tot_parse_tagged_union #kt #tag_t let parse_tagged_union_payload_and_then_cases_injective (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p)) = parse_tagged_union_payload_and_then_cases_injective tag_of_data #k p val parse_tagged_union_eq (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (input: bytes) : Lemma (parse (parse_tagged_union pt tag_of_data p) input == (match parse pt input with | None -> None | Some (tg, consumed_tg) -> let input_tg = Seq.slice input consumed_tg (Seq.length input) in begin match parse (p tg) input_tg with | Some (x, consumed_x) -> Some ((x <: data_t), consumed_tg + consumed_x) | None -> None end )) let parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input = parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input val serialize_tagged_union (#kt: parser_kind) (#tag_t: Type) (#pt: parser kt tag_t) (st: serializer pt) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (#p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (s: (t: tag_t) -> Tot (serializer (p t))) : Pure (serializer (parse_tagged_union pt tag_of_data p)) (requires (kt.parser_kind_subkind == Some ParserStrong)) (ensures (fun _ -> True)) let serialize_tagged_union #kt st tag_of_data #k s = serialize_tot_tagged_union #kt st tag_of_data #k s val nondep_then (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) : Tot (parser (and_then_kind k1 k2) (t1 * t2))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p1: LowParse.Tot.Base.parser k1 t1 -> p2: LowParse.Tot.Base.parser k2 t2 -> LowParse.Tot.Base.parser (LowParse.Spec.Combinators.and_then_kind k1 k2) (t1 * t2)
Prims.Tot
[ "total" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Spec.Combinators.tot_nondep_then", "LowParse.Tot.Base.parser", "LowParse.Spec.Combinators.and_then_kind", "FStar.Pervasives.Native.tuple2" ]
[]
false
false
false
false
false
let nondep_then #k1 =
tot_nondep_then #k1
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_synth_eq
val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b))
val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b))
let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 61, "end_line": 29, "start_col": 0, "start_line": 29 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p1: LowParse.Tot.Base.parser k t1 -> f2: (_: t1 -> t2) -> b: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (requires LowParse.Spec.Combinators.synth_injective f2) (ensures LowParse.Spec.Base.parse (LowParse.Tot.Combinators.parse_synth p1 f2) b == LowParse.Spec.Combinators.parse_synth' p1 f2 b)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Spec.Combinators.tot_parse_synth_eq", "LowParse.Tot.Base.parser", "LowParse.Bytes.bytes", "Prims.unit", "LowParse.Spec.Combinators.synth_injective", "Prims.squash", "Prims.eq2", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.tuple2", "LowParse.Spec.Base.consumed_length", "LowParse.Spec.Base.parse", "LowParse.Tot.Combinators.parse_synth", "LowParse.Spec.Combinators.parse_synth'", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let parse_synth_eq #k #t1 #t2 =
tot_parse_synth_eq #k #t1 #t2
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.serialize_synth
val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2))
val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2))
let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 63, "end_line": 45, "start_col": 0, "start_line": 45 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p1: LowParse.Spec.Base.tot_parser k t1 -> f2: (_: t1 -> t2) -> s1: LowParse.Tot.Base.serializer p1 -> g1: (_: t2 -> Prims.GTot t1) -> u70: u73: Prims.unit { LowParse.Spec.Combinators.synth_inverse f2 g1 /\ LowParse.Spec.Combinators.synth_injective f2 } -> LowParse.Tot.Base.serializer (LowParse.Spec.Combinators.tot_parse_synth p1 f2)
Prims.Tot
[ "total" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Spec.Combinators.serialize_tot_synth", "LowParse.Spec.Base.tot_parser", "LowParse.Tot.Base.serializer", "Prims.unit", "Prims.l_and", "LowParse.Spec.Combinators.synth_inverse", "LowParse.Spec.Combinators.synth_injective", "LowParse.Spec.Combinators.tot_parse_synth" ]
[]
false
false
false
false
false
let serialize_synth #k #t1 #t2 =
serialize_tot_synth #k #t1 #t2
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.serialize_weaken
val serialize_weaken (#k: parser_kind) (#t: Type) (k': parser_kind) (#p: parser k t) (s: serializer p {k' `is_weaker_than` k}) : Tot (serializer (weaken k' p))
val serialize_weaken (#k: parser_kind) (#t: Type) (k': parser_kind) (#p: parser k t) (s: serializer p {k' `is_weaker_than` k}) : Tot (serializer (weaken k' p))
let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 26, "end_line": 54, "start_col": 0, "start_line": 47 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k': LowParse.Spec.Base.parser_kind -> s: LowParse.Tot.Base.serializer p {LowParse.Spec.Base.is_weaker_than k' k} -> LowParse.Tot.Base.serializer (LowParse.Tot.Base.weaken k' p)
Prims.Tot
[ "total" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Tot.Base.serializer", "LowParse.Spec.Base.is_weaker_than", "LowParse.Spec.Combinators.serialize_weaken", "LowParse.Tot.Base.weaken" ]
[]
false
false
false
false
false
let serialize_weaken (#k: parser_kind) (#t: Type) (k': parser_kind) (#p: parser k t) (s: serializer p {k' `is_weaker_than` k}) : Tot (serializer (weaken k' p)) =
serialize_weaken #k k' s
false
Lib.IntVector.Transpose.fsti
Lib.IntVector.Transpose.vec_t4
val vec_t4 : t: Lib.IntVector.v_inttype -> Type0
let vec_t4 (t:v_inttype) = vec_t t 4 & vec_t t 4 & vec_t t 4 & vec_t t 4
{ "file_name": "lib/Lib.IntVector.Transpose.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 72, "end_line": 11, "start_col": 0, "start_line": 11 }
module Lib.IntVector.Transpose open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector #set-options "--z3rlimit 50 --fuel 0 --ifuel 0"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Lib.IntVector.Transpose.fsti" }
[ { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Lib.IntVector.v_inttype -> Type0
Prims.Tot
[ "total" ]
[]
[ "Lib.IntVector.v_inttype", "FStar.Pervasives.Native.tuple4", "Lib.IntVector.vec_t" ]
[]
false
false
false
true
true
let vec_t4 (t: v_inttype) =
vec_t t 4 & vec_t t 4 & vec_t t 4 & vec_t t 4
false
Lib.IntVector.Transpose.fsti
Lib.IntVector.Transpose.vec_t8
val vec_t8 : t: Lib.IntVector.v_inttype -> Type0
let vec_t8 (t:v_inttype) = vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8
{ "file_name": "lib/Lib.IntVector.Transpose.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 120, "end_line": 14, "start_col": 0, "start_line": 14 }
module Lib.IntVector.Transpose open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" inline_for_extraction let vec_t4 (t:v_inttype) = vec_t t 4 & vec_t t 4 & vec_t t 4 & vec_t t 4
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Lib.IntVector.Transpose.fsti" }
[ { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
t: Lib.IntVector.v_inttype -> Type0
Prims.Tot
[ "total" ]
[]
[ "Lib.IntVector.v_inttype", "FStar.Pervasives.Native.tuple8", "Lib.IntVector.vec_t" ]
[]
false
false
false
true
true
let vec_t8 (t: v_inttype) =
vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_filter_eq
val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None ))
val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None ))
let parse_filter_eq #k #t = tot_parse_filter_eq #k #t
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 53, "end_line": 74, "start_col": 0, "start_line": 74 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None ))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: LowParse.Tot.Base.parser k t -> f: (_: t -> Prims.bool) -> input: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (ensures LowParse.Spec.Base.parse (LowParse.Tot.Combinators.parse_filter p f) input == ((match LowParse.Spec.Base.parse p input with | FStar.Pervasives.Native.None #_ -> FStar.Pervasives.Native.None | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ x consumed) -> (match f x with | true -> FStar.Pervasives.Native.Some (x, consumed) | _ -> FStar.Pervasives.Native.None) <: FStar.Pervasives.Native.option (LowParse.Spec.Combinators.parse_filter_refine f * LowParse.Spec.Base.consumed_length input)) <: FStar.Pervasives.Native.option (LowParse.Spec.Combinators.parse_filter_refine f * LowParse.Spec.Base.consumed_length input)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Spec.Combinators.tot_parse_filter_eq", "LowParse.Tot.Base.parser", "Prims.bool", "LowParse.Bytes.bytes", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.eq2", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.tuple2", "LowParse.Spec.Combinators.parse_filter_refine", "LowParse.Spec.Base.consumed_length", "LowParse.Spec.Base.parse", "LowParse.Tot.Combinators.parse_filter", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.Some", "FStar.Pervasives.Native.Mktuple2", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let parse_filter_eq #k #t =
tot_parse_filter_eq #k #t
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.serialize_filter
val serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f))
val serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f))
let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 42, "end_line": 84, "start_col": 0, "start_line": 76 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
s: LowParse.Tot.Base.serializer p -> f: (_: t -> Prims.bool) -> LowParse.Tot.Base.serializer (LowParse.Tot.Combinators.parse_filter p f)
Prims.Tot
[ "total" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Tot.Base.serializer", "Prims.bool", "LowParse.Spec.Base.serialize_ext", "LowParse.Spec.Combinators.parse_filter_kind", "LowParse.Spec.Combinators.parse_filter_refine", "LowParse.Spec.Combinators.parse_filter", "LowParse.Spec.Combinators.serialize_filter", "LowParse.Tot.Combinators.parse_filter", "Prims.unit", "FStar.Classical.forall_intro", "LowParse.Bytes.bytes", "Prims.eq2", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.tuple2", "LowParse.Spec.Base.consumed_length", "LowParse.Spec.Base.parse", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.Some", "FStar.Pervasives.Native.Mktuple2", "LowParse.Tot.Combinators.parse_filter_eq" ]
[]
false
false
false
false
false
let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) =
Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.make_constant_size_parser
val make_constant_size_parser (sz: nat) (t: Type) (f: (s: bytes{Seq.length s == sz} -> Tot (option t))) : Pure (tot_parser (constant_size_parser_kind sz) t) (requires (make_constant_size_parser_precond sz t f)) (ensures (fun _ -> True))
val make_constant_size_parser (sz: nat) (t: Type) (f: (s: bytes{Seq.length s == sz} -> Tot (option t))) : Pure (tot_parser (constant_size_parser_kind sz) t) (requires (make_constant_size_parser_precond sz t f)) (ensures (fun _ -> True))
let make_constant_size_parser (sz: nat) (t: Type) (f: ((s: bytes {Seq.length s == sz}) -> Tot (option t))) : Pure ( tot_parser (constant_size_parser_kind sz) t ) (requires ( make_constant_size_parser_precond sz t f )) (ensures (fun _ -> True)) = tot_make_constant_size_parser sz t f
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 38, "end_line": 224, "start_col": 0, "start_line": 211 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t) let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t inline_for_extraction val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t) let parse_tagged_union #kt #tag_t = tot_parse_tagged_union #kt #tag_t let parse_tagged_union_payload_and_then_cases_injective (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p)) = parse_tagged_union_payload_and_then_cases_injective tag_of_data #k p val parse_tagged_union_eq (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (input: bytes) : Lemma (parse (parse_tagged_union pt tag_of_data p) input == (match parse pt input with | None -> None | Some (tg, consumed_tg) -> let input_tg = Seq.slice input consumed_tg (Seq.length input) in begin match parse (p tg) input_tg with | Some (x, consumed_x) -> Some ((x <: data_t), consumed_tg + consumed_x) | None -> None end )) let parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input = parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input val serialize_tagged_union (#kt: parser_kind) (#tag_t: Type) (#pt: parser kt tag_t) (st: serializer pt) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (#p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (s: (t: tag_t) -> Tot (serializer (p t))) : Pure (serializer (parse_tagged_union pt tag_of_data p)) (requires (kt.parser_kind_subkind == Some ParserStrong)) (ensures (fun _ -> True)) let serialize_tagged_union #kt st tag_of_data #k s = serialize_tot_tagged_union #kt st tag_of_data #k s val nondep_then (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) : Tot (parser (and_then_kind k1 k2) (t1 * t2)) let nondep_then #k1 = tot_nondep_then #k1 val nondep_then_eq (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) (b: bytes) : Lemma (parse (nondep_then p1 p2) b == (match parse p1 b with | Some (x1, consumed1) -> let b' = Seq.slice b consumed1 (Seq.length b) in begin match parse p2 b' with | Some (x2, consumed2) -> Some ((x1, x2), consumed1 + consumed2) | _ -> None end | _ -> None )) let nondep_then_eq #k1 #t1 p1 #k2 #t2 p2 b = nondep_then_eq #k1 p1 #k2 p2 b
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
sz: Prims.nat -> t: Type -> f: (s: LowParse.Bytes.bytes{FStar.Seq.Base.length s == sz} -> FStar.Pervasives.Native.option t) -> Prims.Pure (LowParse.Spec.Base.tot_parser (LowParse.Spec.Combinators.constant_size_parser_kind sz) t)
Prims.Pure
[]
[]
[ "Prims.nat", "LowParse.Bytes.bytes", "Prims.eq2", "FStar.Seq.Base.length", "LowParse.Bytes.byte", "FStar.Pervasives.Native.option", "LowParse.Spec.Combinators.tot_make_constant_size_parser", "LowParse.Spec.Base.tot_parser", "LowParse.Spec.Combinators.constant_size_parser_kind", "LowParse.Spec.Combinators.make_constant_size_parser_precond", "Prims.l_True" ]
[]
false
false
false
false
false
let make_constant_size_parser (sz: nat) (t: Type) (f: (s: bytes{Seq.length s == sz} -> Tot (option t))) : Pure (tot_parser (constant_size_parser_kind sz) t) (requires (make_constant_size_parser_precond sz t f)) (ensures (fun _ -> True)) =
tot_make_constant_size_parser sz t f
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.serialize_tagged_union
val serialize_tagged_union (#kt: parser_kind) (#tag_t: Type) (#pt: parser kt tag_t) (st: serializer pt) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (#p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (s: (t: tag_t) -> Tot (serializer (p t))) : Pure (serializer (parse_tagged_union pt tag_of_data p)) (requires (kt.parser_kind_subkind == Some ParserStrong)) (ensures (fun _ -> True))
val serialize_tagged_union (#kt: parser_kind) (#tag_t: Type) (#pt: parser kt tag_t) (st: serializer pt) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (#p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (s: (t: tag_t) -> Tot (serializer (p t))) : Pure (serializer (parse_tagged_union pt tag_of_data p)) (requires (kt.parser_kind_subkind == Some ParserStrong)) (ensures (fun _ -> True))
let serialize_tagged_union #kt st tag_of_data #k s = serialize_tot_tagged_union #kt st tag_of_data #k s
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 103, "end_line": 175, "start_col": 0, "start_line": 175 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t) let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t inline_for_extraction val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t) let parse_tagged_union #kt #tag_t = tot_parse_tagged_union #kt #tag_t let parse_tagged_union_payload_and_then_cases_injective (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p)) = parse_tagged_union_payload_and_then_cases_injective tag_of_data #k p val parse_tagged_union_eq (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (input: bytes) : Lemma (parse (parse_tagged_union pt tag_of_data p) input == (match parse pt input with | None -> None | Some (tg, consumed_tg) -> let input_tg = Seq.slice input consumed_tg (Seq.length input) in begin match parse (p tg) input_tg with | Some (x, consumed_x) -> Some ((x <: data_t), consumed_tg + consumed_x) | None -> None end )) let parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input = parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input val serialize_tagged_union (#kt: parser_kind) (#tag_t: Type) (#pt: parser kt tag_t) (st: serializer pt) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (#p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (s: (t: tag_t) -> Tot (serializer (p t))) : Pure (serializer (parse_tagged_union pt tag_of_data p)) (requires (kt.parser_kind_subkind == Some ParserStrong)) (ensures (fun _ -> True))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
st: LowParse.Tot.Base.serializer pt -> tag_of_data: (_: data_t -> tag_t) -> s: (t: tag_t -> LowParse.Tot.Base.serializer (p t)) -> Prims.Pure (LowParse.Tot.Base.serializer (LowParse.Tot.Combinators.parse_tagged_union pt tag_of_data p))
Prims.Pure
[]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Tot.Base.serializer", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.Combinators.serialize_tot_tagged_union", "LowParse.Spec.Combinators.and_then_kind", "LowParse.Tot.Combinators.parse_tagged_union" ]
[]
false
false
false
false
false
let serialize_tagged_union #kt st tag_of_data #k s =
serialize_tot_tagged_union #kt st tag_of_data #k s
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.and_then_eq
val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input))
val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input))
let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 79, "end_line": 101, "start_col": 0, "start_line": 101 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: LowParse.Tot.Base.parser k t -> p': (_: t -> LowParse.Tot.Base.parser k' t') -> input: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (requires LowParse.Spec.Combinators.and_then_cases_injective p') (ensures LowParse.Spec.Base.parse (LowParse.Tot.Combinators.and_then p p') input == LowParse.Spec.Combinators.and_then_bare p p' input)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Bytes.bytes", "LowParse.Spec.Combinators.and_then_eq", "Prims.unit" ]
[]
true
false
true
false
false
let and_then_eq #k #t p #k' #t' p' input =
and_then_eq #k #t p #k' #t' p' input
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_tagged_union_payload_and_then_cases_injective
val parse_tagged_union_payload_and_then_cases_injective (#tag_t #data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t -> Tot (parser k (refine_with_tag tag_of_data t)))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p))
val parse_tagged_union_payload_and_then_cases_injective (#tag_t #data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t -> Tot (parser k (refine_with_tag tag_of_data t)))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p))
let parse_tagged_union_payload_and_then_cases_injective (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p)) = parse_tagged_union_payload_and_then_cases_injective tag_of_data #k p
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 70, "end_line": 136, "start_col": 0, "start_line": 128 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t) let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t inline_for_extraction val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t) let parse_tagged_union #kt #tag_t = tot_parse_tagged_union #kt #tag_t
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
tag_of_data: (_: data_t -> tag_t) -> p: (t: tag_t -> LowParse.Tot.Base.parser k (LowParse.Spec.Base.refine_with_tag tag_of_data t)) -> FStar.Pervasives.Lemma (ensures LowParse.Spec.Combinators.and_then_cases_injective (LowParse.Tot.Combinators.parse_tagged_union_payload tag_of_data p))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.Combinators.parse_tagged_union_payload_and_then_cases_injective", "Prims.unit", "Prims.l_True", "Prims.squash", "LowParse.Spec.Combinators.and_then_cases_injective", "LowParse.Tot.Combinators.parse_tagged_union_payload", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
true
false
true
false
false
let parse_tagged_union_payload_and_then_cases_injective (#tag_t #data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t -> Tot (parser k (refine_with_tag tag_of_data t)))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p)) =
parse_tagged_union_payload_and_then_cases_injective tag_of_data #k p
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.parse_tagged_union_eq
val parse_tagged_union_eq (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (input: bytes) : Lemma (parse (parse_tagged_union pt tag_of_data p) input == (match parse pt input with | None -> None | Some (tg, consumed_tg) -> let input_tg = Seq.slice input consumed_tg (Seq.length input) in begin match parse (p tg) input_tg with | Some (x, consumed_x) -> Some ((x <: data_t), consumed_tg + consumed_x) | None -> None end ))
val parse_tagged_union_eq (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (input: bytes) : Lemma (parse (parse_tagged_union pt tag_of_data p) input == (match parse pt input with | None -> None | Some (tg, consumed_tg) -> let input_tg = Seq.slice input consumed_tg (Seq.length input) in begin match parse (p tg) input_tg with | Some (x, consumed_x) -> Some ((x <: data_t), consumed_tg + consumed_x) | None -> None end ))
let parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input = parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 68, "end_line": 159, "start_col": 0, "start_line": 158 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t) let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t inline_for_extraction val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t) let parse_tagged_union #kt #tag_t = tot_parse_tagged_union #kt #tag_t let parse_tagged_union_payload_and_then_cases_injective (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p)) = parse_tagged_union_payload_and_then_cases_injective tag_of_data #k p val parse_tagged_union_eq (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (input: bytes) : Lemma (parse (parse_tagged_union pt tag_of_data p) input == (match parse pt input with | None -> None | Some (tg, consumed_tg) -> let input_tg = Seq.slice input consumed_tg (Seq.length input) in begin match parse (p tg) input_tg with | Some (x, consumed_x) -> Some ((x <: data_t), consumed_tg + consumed_x) | None -> None end ))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
pt: LowParse.Tot.Base.parser kt tag_t -> tag_of_data: (_: data_t -> tag_t) -> p: (t: tag_t -> LowParse.Tot.Base.parser k (LowParse.Spec.Base.refine_with_tag tag_of_data t)) -> input: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (ensures LowParse.Spec.Base.parse (LowParse.Tot.Combinators.parse_tagged_union pt tag_of_data p) input == ((match LowParse.Spec.Base.parse pt input with | FStar.Pervasives.Native.None #_ -> FStar.Pervasives.Native.None | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ tg consumed_tg) -> let input_tg = FStar.Seq.Base.slice input consumed_tg (FStar.Seq.Base.length input) in (match LowParse.Spec.Base.parse (p tg) input_tg with | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ x consumed_x) -> FStar.Pervasives.Native.Some (x, consumed_tg + consumed_x) | FStar.Pervasives.Native.None #_ -> FStar.Pervasives.Native.None) <: FStar.Pervasives.Native.option (data_t * LowParse.Spec.Base.consumed_length input)) <: FStar.Pervasives.Native.option (data_t * LowParse.Spec.Base.consumed_length input)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Spec.Base.refine_with_tag", "LowParse.Bytes.bytes", "LowParse.Spec.Combinators.parse_tagged_union_eq", "Prims.unit" ]
[]
true
false
true
false
false
let parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input =
parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input
false
Lib.IntVector.Transpose.fsti
Lib.IntVector.Transpose.transpose4x4_lseq
val transpose4x4_lseq (#t: v_inttype{t = U32 \/ t = U64}) (vs: lseq (vec_t t 4) 4) : lseq (vec_t t 4) 4
val transpose4x4_lseq (#t: v_inttype{t = U32 \/ t = U64}) (vs: lseq (vec_t t 4) 4) : lseq (vec_t t 4) 4
let transpose4x4_lseq (#t:v_inttype{t = U32 \/ t = U64}) (vs:lseq (vec_t t 4) 4) : lseq (vec_t t 4) 4 = let (v0,v1,v2,v3) = (vs.[0],vs.[1],vs.[2],vs.[3]) in let (r0,r1,r2,r3) = transpose4x4 (v0,v1,v2,v3) in create4 r0 r1 r2 r3
{ "file_name": "lib/Lib.IntVector.Transpose.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 21, "end_line": 28, "start_col": 0, "start_line": 25 }
module Lib.IntVector.Transpose open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" inline_for_extraction let vec_t4 (t:v_inttype) = vec_t t 4 & vec_t t 4 & vec_t t 4 & vec_t t 4 inline_for_extraction let vec_t8 (t:v_inttype) = vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 inline_for_extraction val transpose4x4: #t:v_inttype{t = U32 \/ t = U64} -> vec_t4 t -> vec_t4 t inline_for_extraction val transpose8x8: #t:v_inttype{t = U32} -> vec_t8 t -> vec_t8 t
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Lib.IntVector.Transpose.fsti" }
[ { "abbrev": true, "full_module": "Lib.LoopCombinators", "short_module": "Loops" }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
vs: Lib.Sequence.lseq (Lib.IntVector.vec_t t 4) 4 -> Lib.Sequence.lseq (Lib.IntVector.vec_t t 4) 4
Prims.Tot
[ "total" ]
[]
[ "Lib.IntVector.v_inttype", "Prims.l_or", "Prims.b2t", "Prims.op_Equality", "Lib.IntTypes.inttype", "Lib.IntTypes.U32", "Lib.IntTypes.U64", "Lib.Sequence.lseq", "Lib.IntVector.vec_t", "Lib.Sequence.create4", "Lib.IntVector.Transpose.vec_t4", "Lib.IntVector.Transpose.transpose4x4", "FStar.Pervasives.Native.Mktuple4", "FStar.Pervasives.Native.tuple4", "Lib.Sequence.op_String_Access" ]
[]
false
false
false
false
false
let transpose4x4_lseq (#t: v_inttype{t = U32 \/ t = U64}) (vs: lseq (vec_t t 4) 4) : lseq (vec_t t 4) 4 =
let v0, v1, v2, v3 = (vs.[ 0 ], vs.[ 1 ], vs.[ 2 ], vs.[ 3 ]) in let r0, r1, r2, r3 = transpose4x4 (v0, v1, v2, v3) in create4 r0 r1 r2 r3
false
LowParse.Tot.Combinators.fst
LowParse.Tot.Combinators.nondep_then_eq
val nondep_then_eq (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) (b: bytes) : Lemma (parse (nondep_then p1 p2) b == (match parse p1 b with | Some (x1, consumed1) -> let b' = Seq.slice b consumed1 (Seq.length b) in begin match parse p2 b' with | Some (x2, consumed2) -> Some ((x1, x2), consumed1 + consumed2) | _ -> None end | _ -> None ))
val nondep_then_eq (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) (b: bytes) : Lemma (parse (nondep_then p1 p2) b == (match parse p1 b with | Some (x1, consumed1) -> let b' = Seq.slice b consumed1 (Seq.length b) in begin match parse p2 b' with | Some (x2, consumed2) -> Some ((x1, x2), consumed1 + consumed2) | _ -> None end | _ -> None ))
let nondep_then_eq #k1 #t1 p1 #k2 #t2 p2 b = nondep_then_eq #k1 p1 #k2 p2 b
{ "file_name": "src/lowparse/LowParse.Tot.Combinators.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 32, "end_line": 209, "start_col": 0, "start_line": 208 }
module LowParse.Tot.Combinators include LowParse.Spec.Combinators include LowParse.Tot.Base inline_for_extraction let fail_parser = tot_fail_parser inline_for_extraction let parse_ret = tot_parse_ret inline_for_extraction let parse_empty : parser parse_ret_kind unit = parse_ret () inline_for_extraction let parse_synth #k #t1 #t2 = tot_parse_synth #k #t1 #t2 val parse_synth_eq (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: parser k t1) (f2: t1 -> Tot t2) (b: bytes) : Lemma (requires (synth_injective f2)) (ensures (parse (parse_synth p1 f2) b == parse_synth' #k p1 f2 b)) let parse_synth_eq #k #t1 #t2 = tot_parse_synth_eq #k #t1 #t2 val serialize_synth (#k: parser_kind) (#t1: Type) (#t2: Type) (p1: tot_parser k t1) (f2: t1 -> Tot t2) (s1: serializer p1) (g1: t2 -> GTot t1) (u: unit { synth_inverse f2 g1 /\ synth_injective f2 }) : Tot (serializer (tot_parse_synth p1 f2)) let serialize_synth #k #t1 #t2 = serialize_tot_synth #k #t1 #t2 let serialize_weaken (#k: parser_kind) (#t: Type) (k' : parser_kind) (#p: parser k t) (s: serializer p { k' `is_weaker_than` k }) : Tot (serializer (weaken k' p)) = serialize_weaken #k k' s inline_for_extraction let parse_filter #k #t = tot_parse_filter #k #t val parse_filter_eq (#k: parser_kind) (#t: Type) (p: parser k t) (f: (t -> Tot bool)) (input: bytes) : Lemma (parse (parse_filter p f) input == (match parse p input with | None -> None | Some (x, consumed) -> if f x then Some (x, consumed) else None )) let parse_filter_eq #k #t = tot_parse_filter_eq #k #t let serialize_filter (#k: parser_kind) (#t: Type) (#p: parser k t) (s: serializer p) (f: (t -> Tot bool)) : Tot (serializer (parse_filter p f)) = Classical.forall_intro (parse_filter_eq #k #t p f); serialize_ext _ (serialize_filter s f) _ inline_for_extraction let and_then #k #t = tot_and_then #k #t val and_then_eq (#k: parser_kind) (#t:Type) (p: parser k t) (#k': parser_kind) (#t':Type) (p': (t -> Tot (parser k' t'))) (input: bytes) : Lemma (requires (and_then_cases_injective p')) (ensures (parse (and_then p p') input == and_then_bare p p' input)) let and_then_eq #k #t p #k' #t' p' input = and_then_eq #k #t p #k' #t' p' input inline_for_extraction val parse_tagged_union_payload (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (tg: tag_t) : Tot (parser k data_t) let parse_tagged_union_payload #tag_t #data_t = tot_parse_tagged_union_payload #tag_t #data_t inline_for_extraction val parse_tagged_union (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Tot (parser (and_then_kind kt k) data_t) let parse_tagged_union #kt #tag_t = tot_parse_tagged_union #kt #tag_t let parse_tagged_union_payload_and_then_cases_injective (#tag_t: Type) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) : Lemma (and_then_cases_injective (parse_tagged_union_payload tag_of_data p)) = parse_tagged_union_payload_and_then_cases_injective tag_of_data #k p val parse_tagged_union_eq (#kt: parser_kind) (#tag_t: Type) (pt: parser kt tag_t) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (input: bytes) : Lemma (parse (parse_tagged_union pt tag_of_data p) input == (match parse pt input with | None -> None | Some (tg, consumed_tg) -> let input_tg = Seq.slice input consumed_tg (Seq.length input) in begin match parse (p tg) input_tg with | Some (x, consumed_x) -> Some ((x <: data_t), consumed_tg + consumed_x) | None -> None end )) let parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input = parse_tagged_union_eq #kt #tag_t pt #data_t tag_of_data #k p input val serialize_tagged_union (#kt: parser_kind) (#tag_t: Type) (#pt: parser kt tag_t) (st: serializer pt) (#data_t: Type) (tag_of_data: (data_t -> Tot tag_t)) (#k: parser_kind) (#p: (t: tag_t) -> Tot (parser k (refine_with_tag tag_of_data t))) (s: (t: tag_t) -> Tot (serializer (p t))) : Pure (serializer (parse_tagged_union pt tag_of_data p)) (requires (kt.parser_kind_subkind == Some ParserStrong)) (ensures (fun _ -> True)) let serialize_tagged_union #kt st tag_of_data #k s = serialize_tot_tagged_union #kt st tag_of_data #k s val nondep_then (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) : Tot (parser (and_then_kind k1 k2) (t1 * t2)) let nondep_then #k1 = tot_nondep_then #k1 val nondep_then_eq (#k1: parser_kind) (#t1: Type) (p1: parser k1 t1) (#k2: parser_kind) (#t2: Type) (p2: parser k2 t2) (b: bytes) : Lemma (parse (nondep_then p1 p2) b == (match parse p1 b with | Some (x1, consumed1) -> let b' = Seq.slice b consumed1 (Seq.length b) in begin match parse p2 b' with | Some (x2, consumed2) -> Some ((x1, x2), consumed1 + consumed2) | _ -> None end | _ -> None ))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Tot.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "LowParse.Tot.Combinators.fst" }
[ { "abbrev": false, "full_module": "LowParse.Tot.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Tot", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 2, "initial_ifuel": 1, "max_fuel": 8, "max_ifuel": 2, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": true, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p1: LowParse.Tot.Base.parser k1 t1 -> p2: LowParse.Tot.Base.parser k2 t2 -> b: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (ensures LowParse.Spec.Base.parse (LowParse.Tot.Combinators.nondep_then p1 p2) b == ((match LowParse.Spec.Base.parse p1 b with | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ x1 consumed1) -> let b' = FStar.Seq.Base.slice b consumed1 (FStar.Seq.Base.length b) in (match LowParse.Spec.Base.parse p2 b' with | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ x2 consumed2) -> FStar.Pervasives.Native.Some ((x1, x2), consumed1 + consumed2) | _ -> FStar.Pervasives.Native.None) <: FStar.Pervasives.Native.option ((t1 * t2) * LowParse.Spec.Base.consumed_length b) | _ -> FStar.Pervasives.Native.None) <: FStar.Pervasives.Native.option ((t1 * t2) * LowParse.Spec.Base.consumed_length b)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.Base.parser_kind", "LowParse.Tot.Base.parser", "LowParse.Bytes.bytes", "LowParse.Spec.Combinators.nondep_then_eq", "Prims.unit" ]
[]
true
false
true
false
false
let nondep_then_eq #k1 #t1 p1 #k2 #t2 p2 b =
nondep_then_eq #k1 p1 #k2 p2 b
false
Lib.IntVector.Transpose.fsti
Lib.IntVector.Transpose.transpose8x8_lseq
val transpose8x8_lseq (#t: v_inttype{t = U32}) (vs: lseq (vec_t t 8) 8) : lseq (vec_t t 8) 8
val transpose8x8_lseq (#t: v_inttype{t = U32}) (vs: lseq (vec_t t 8) 8) : lseq (vec_t t 8) 8
let transpose8x8_lseq (#t:v_inttype{t = U32}) (vs:lseq (vec_t t 8) 8) : lseq (vec_t t 8) 8 = let (v0,v1,v2,v3,v4,v5,v6,v7) = (vs.[0],vs.[1],vs.[2],vs.[3],vs.[4],vs.[5],vs.[6],vs.[7]) in let (r0,r1,r2,r3,r4,r5,r6,r7) = transpose8x8 (v0,v1,v2,v3,v4,v5,v6,v7) in create8 r0 r1 r2 r3 r4 r5 r6 r7
{ "file_name": "lib/Lib.IntVector.Transpose.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 33, "end_line": 34, "start_col": 0, "start_line": 31 }
module Lib.IntVector.Transpose open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" inline_for_extraction let vec_t4 (t:v_inttype) = vec_t t 4 & vec_t t 4 & vec_t t 4 & vec_t t 4 inline_for_extraction let vec_t8 (t:v_inttype) = vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 & vec_t t 8 inline_for_extraction val transpose4x4: #t:v_inttype{t = U32 \/ t = U64} -> vec_t4 t -> vec_t4 t inline_for_extraction val transpose8x8: #t:v_inttype{t = U32} -> vec_t8 t -> vec_t8 t inline_for_extraction let transpose4x4_lseq (#t:v_inttype{t = U32 \/ t = U64}) (vs:lseq (vec_t t 4) 4) : lseq (vec_t t 4) 4 = let (v0,v1,v2,v3) = (vs.[0],vs.[1],vs.[2],vs.[3]) in let (r0,r1,r2,r3) = transpose4x4 (v0,v1,v2,v3) in create4 r0 r1 r2 r3
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Lib.IntVector.Transpose.fsti" }
[ { "abbrev": true, "full_module": "Lib.LoopCombinators", "short_module": "Loops" }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
vs: Lib.Sequence.lseq (Lib.IntVector.vec_t t 8) 8 -> Lib.Sequence.lseq (Lib.IntVector.vec_t t 8) 8
Prims.Tot
[ "total" ]
[]
[ "Lib.IntVector.v_inttype", "Prims.b2t", "Prims.op_Equality", "Lib.IntTypes.inttype", "Lib.IntTypes.U32", "Lib.Sequence.lseq", "Lib.IntVector.vec_t", "Lib.Sequence.create8", "Lib.IntVector.Transpose.vec_t8", "Lib.IntVector.Transpose.transpose8x8", "FStar.Pervasives.Native.Mktuple8", "FStar.Pervasives.Native.tuple8", "Lib.Sequence.op_String_Access" ]
[]
false
false
false
false
false
let transpose8x8_lseq (#t: v_inttype{t = U32}) (vs: lseq (vec_t t 8) 8) : lseq (vec_t t 8) 8 =
let v0, v1, v2, v3, v4, v5, v6, v7 = (vs.[ 0 ], vs.[ 1 ], vs.[ 2 ], vs.[ 3 ], vs.[ 4 ], vs.[ 5 ], vs.[ 6 ], vs.[ 7 ]) in let r0, r1, r2, r3, r4, r5, r6, r7 = transpose8x8 (v0, v1, v2, v3, v4, v5, v6, v7) in create8 r0 r1 r2 r3 r4 r5 r6 r7
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.aff_point_mul_lambda
val aff_point_mul_lambda (p: S.aff_point) : S.aff_point
val aff_point_mul_lambda (p: S.aff_point) : S.aff_point
let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py)
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 42, "end_line": 55, "start_col": 0, "start_line": 54 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: Spec.K256.PointOps.aff_point -> Spec.K256.PointOps.aff_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.aff_point", "Spec.K256.PointOps.felem", "FStar.Pervasives.Native.Mktuple2", "Spec.K256.PointOps.op_Star_Percent", "Hacl.Spec.K256.GLV.beta" ]
[]
false
false
false
true
false
let aff_point_mul_lambda (p: S.aff_point) : S.aff_point =
let px, py = p in (S.(beta *% px), py)
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.aff_point_mul
val aff_point_mul : a: Prims.nat -> p: Spec.K256.PointOps.aff_point -> Spec.K256.PointOps.aff_point
let aff_point_mul = S.aff_point_mul
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 35, "end_line": 51, "start_col": 0, "start_line": 51 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
a: Prims.nat -> p: Spec.K256.PointOps.aff_point -> Spec.K256.PointOps.aff_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.aff_point_mul" ]
[]
false
false
false
true
false
let aff_point_mul =
S.aff_point_mul
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.point_mul_lambda
val point_mul_lambda (p: S.proj_point) : S.proj_point
val point_mul_lambda (p: S.proj_point) : S.proj_point
let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z)
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 50, "end_line": 59, "start_col": 0, "start_line": 58 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py)
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: Spec.K256.PointOps.proj_point -> Spec.K256.PointOps.proj_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.proj_point", "Spec.K256.PointOps.felem", "FStar.Pervasives.Native.Mktuple3", "Spec.K256.PointOps.op_Star_Percent", "Hacl.Spec.K256.GLV.beta" ]
[]
false
false
false
true
false
let point_mul_lambda (p: S.proj_point) : S.proj_point =
let _X, _Y, _Z = p in (S.(beta *% _X), _Y, _Z)
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.aff_point_negate_cond
val aff_point_negate_cond (p: S.aff_point) (is_negate: bool) : S.aff_point
val aff_point_negate_cond (p: S.aff_point) (is_negate: bool) : S.aff_point
let aff_point_negate_cond (p:S.aff_point) (is_negate:bool) : S.aff_point = if is_negate then S.aff_point_negate p else p
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 47, "end_line": 129, "start_col": 0, "start_line": 128 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x let qmul_shift_384 a b = a * b / pow2 384 + (a * b / pow2 383 % 2) val qmul_shift_384_lemma (a b:S.qelem) : Lemma (qmul_shift_384 a b < S.q) let qmul_shift_384_lemma a b = assert_norm (S.q < pow2 256); Math.Lemmas.lemma_mult_lt_sqr a b (pow2 256); Math.Lemmas.pow2_plus 256 256; assert (a * b < pow2 512); Math.Lemmas.lemma_div_lt_nat (a * b) 512 384; assert (a * b / pow2 384 < pow2 128); assert_norm (pow2 128 < S.q) let scalar_split_lambda (k:S.qelem) : S.qelem & S.qelem = qmul_shift_384_lemma k g1; qmul_shift_384_lemma k g2; let c1 : S.qelem = qmul_shift_384 k g1 in let c2 : S.qelem = qmul_shift_384 k g2 in let c1 = S.(c1 *^ minus_b1) in let c2 = S.(c2 *^ minus_b2) in let r2 = S.(c1 +^ c2) in let r1 = S.(k +^ r2 *^ minus_lambda) in r1, r2 (** Fast computation of [k]P in affine coordinates *)
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: Spec.K256.PointOps.aff_point -> is_negate: Prims.bool -> Spec.K256.PointOps.aff_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.aff_point", "Prims.bool", "Spec.K256.PointOps.aff_point_negate" ]
[]
false
false
false
true
false
let aff_point_negate_cond (p: S.aff_point) (is_negate: bool) : S.aff_point =
if is_negate then S.aff_point_negate p else p
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.aff_negate_point_and_scalar_cond
val aff_negate_point_and_scalar_cond (k: S.qelem) (p: S.aff_point) : S.qelem & S.aff_point
val aff_negate_point_and_scalar_cond (k: S.qelem) (p: S.aff_point) : S.qelem & S.aff_point
let aff_negate_point_and_scalar_cond (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.aff_point_negate p in k_neg, p_neg end else k, p
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 11, "end_line": 136, "start_col": 0, "start_line": 131 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x let qmul_shift_384 a b = a * b / pow2 384 + (a * b / pow2 383 % 2) val qmul_shift_384_lemma (a b:S.qelem) : Lemma (qmul_shift_384 a b < S.q) let qmul_shift_384_lemma a b = assert_norm (S.q < pow2 256); Math.Lemmas.lemma_mult_lt_sqr a b (pow2 256); Math.Lemmas.pow2_plus 256 256; assert (a * b < pow2 512); Math.Lemmas.lemma_div_lt_nat (a * b) 512 384; assert (a * b / pow2 384 < pow2 128); assert_norm (pow2 128 < S.q) let scalar_split_lambda (k:S.qelem) : S.qelem & S.qelem = qmul_shift_384_lemma k g1; qmul_shift_384_lemma k g2; let c1 : S.qelem = qmul_shift_384 k g1 in let c2 : S.qelem = qmul_shift_384 k g2 in let c1 = S.(c1 *^ minus_b1) in let c2 = S.(c2 *^ minus_b2) in let r2 = S.(c1 +^ c2) in let r1 = S.(k +^ r2 *^ minus_lambda) in r1, r2 (** Fast computation of [k]P in affine coordinates *) let aff_point_negate_cond (p:S.aff_point) (is_negate:bool) : S.aff_point = if is_negate then S.aff_point_negate p else p
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k: Spec.K256.PointOps.qelem -> p: Spec.K256.PointOps.aff_point -> Spec.K256.PointOps.qelem * Spec.K256.PointOps.aff_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.qelem", "Spec.K256.PointOps.aff_point", "Spec.K256.PointOps.scalar_is_high", "FStar.Pervasives.Native.Mktuple2", "Spec.K256.PointOps.aff_point_negate", "Spec.K256.PointOps.qnegate", "Prims.bool", "FStar.Pervasives.Native.tuple2" ]
[]
false
false
false
true
false
let aff_negate_point_and_scalar_cond (k: S.qelem) (p: S.aff_point) : S.qelem & S.aff_point =
if S.scalar_is_high k then let k_neg = S.qnegate k in let p_neg = S.aff_point_negate p in k_neg, p_neg else k, p
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.point_negate_cond
val point_negate_cond (p: S.proj_point) (is_negate: bool) : S.proj_point
val point_negate_cond (p: S.proj_point) (is_negate: bool) : S.proj_point
let point_negate_cond (p:S.proj_point) (is_negate:bool) : S.proj_point = if is_negate then S.point_negate p else p
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 43, "end_line": 160, "start_col": 0, "start_line": 159 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x let qmul_shift_384 a b = a * b / pow2 384 + (a * b / pow2 383 % 2) val qmul_shift_384_lemma (a b:S.qelem) : Lemma (qmul_shift_384 a b < S.q) let qmul_shift_384_lemma a b = assert_norm (S.q < pow2 256); Math.Lemmas.lemma_mult_lt_sqr a b (pow2 256); Math.Lemmas.pow2_plus 256 256; assert (a * b < pow2 512); Math.Lemmas.lemma_div_lt_nat (a * b) 512 384; assert (a * b / pow2 384 < pow2 128); assert_norm (pow2 128 < S.q) let scalar_split_lambda (k:S.qelem) : S.qelem & S.qelem = qmul_shift_384_lemma k g1; qmul_shift_384_lemma k g2; let c1 : S.qelem = qmul_shift_384 k g1 in let c2 : S.qelem = qmul_shift_384 k g2 in let c1 = S.(c1 *^ minus_b1) in let c2 = S.(c2 *^ minus_b2) in let r2 = S.(c1 +^ c2) in let r1 = S.(k +^ r2 *^ minus_lambda) in r1, r2 (** Fast computation of [k]P in affine coordinates *) let aff_point_negate_cond (p:S.aff_point) (is_negate:bool) : S.aff_point = if is_negate then S.aff_point_negate p else p let aff_negate_point_and_scalar_cond (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.aff_point_negate p in k_neg, p_neg end else k, p // https://github.com/bitcoin-core/secp256k1/blob/master/src/ecmult_impl.h // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y) let aff_ecmult_endo_split (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point = let r1, r2 = scalar_split_lambda k in let lambda_p = aff_point_mul_lambda p in let r1, p1 = aff_negate_point_and_scalar_cond r1 p in let r2, p2 = aff_negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2) // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y) // which can be computed as a double exponentiation ([a]P + [b]Q) let aff_point_mul_endo_split (k:S.qelem) (p:S.aff_point) : S.aff_point = let r1, p1, r2, p2 = aff_ecmult_endo_split k p in S.aff_point_add (aff_point_mul r1 p1) (aff_point_mul r2 p2) (** Fast computation of [k]P in projective coordinates *)
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: Spec.K256.PointOps.proj_point -> is_negate: Prims.bool -> Spec.K256.PointOps.proj_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.proj_point", "Prims.bool", "Spec.K256.PointOps.point_negate" ]
[]
false
false
false
true
false
let point_negate_cond (p: S.proj_point) (is_negate: bool) : S.proj_point =
if is_negate then S.point_negate p else p
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.aff_ecmult_endo_split
val aff_ecmult_endo_split (k: S.qelem) (p: S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point
val aff_ecmult_endo_split (k: S.qelem) (p: S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point
let aff_ecmult_endo_split (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point = let r1, r2 = scalar_split_lambda k in let lambda_p = aff_point_mul_lambda p in let r1, p1 = aff_negate_point_and_scalar_cond r1 p in let r2, p2 = aff_negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2)
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 18, "end_line": 147, "start_col": 0, "start_line": 140 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x let qmul_shift_384 a b = a * b / pow2 384 + (a * b / pow2 383 % 2) val qmul_shift_384_lemma (a b:S.qelem) : Lemma (qmul_shift_384 a b < S.q) let qmul_shift_384_lemma a b = assert_norm (S.q < pow2 256); Math.Lemmas.lemma_mult_lt_sqr a b (pow2 256); Math.Lemmas.pow2_plus 256 256; assert (a * b < pow2 512); Math.Lemmas.lemma_div_lt_nat (a * b) 512 384; assert (a * b / pow2 384 < pow2 128); assert_norm (pow2 128 < S.q) let scalar_split_lambda (k:S.qelem) : S.qelem & S.qelem = qmul_shift_384_lemma k g1; qmul_shift_384_lemma k g2; let c1 : S.qelem = qmul_shift_384 k g1 in let c2 : S.qelem = qmul_shift_384 k g2 in let c1 = S.(c1 *^ minus_b1) in let c2 = S.(c2 *^ minus_b2) in let r2 = S.(c1 +^ c2) in let r1 = S.(k +^ r2 *^ minus_lambda) in r1, r2 (** Fast computation of [k]P in affine coordinates *) let aff_point_negate_cond (p:S.aff_point) (is_negate:bool) : S.aff_point = if is_negate then S.aff_point_negate p else p let aff_negate_point_and_scalar_cond (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.aff_point_negate p in k_neg, p_neg end else k, p // https://github.com/bitcoin-core/secp256k1/blob/master/src/ecmult_impl.h
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k: Spec.K256.PointOps.qelem -> p: Spec.K256.PointOps.aff_point -> ((Spec.K256.PointOps.qelem * Spec.K256.PointOps.aff_point) * Spec.K256.PointOps.qelem) * Spec.K256.PointOps.aff_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.qelem", "Spec.K256.PointOps.aff_point", "FStar.Pervasives.Native.Mktuple4", "FStar.Pervasives.Native.tuple4", "FStar.Pervasives.Native.tuple2", "Hacl.Spec.K256.GLV.aff_negate_point_and_scalar_cond", "Hacl.Spec.K256.GLV.aff_point_mul_lambda", "Hacl.Spec.K256.GLV.scalar_split_lambda" ]
[]
false
false
false
true
false
let aff_ecmult_endo_split (k: S.qelem) (p: S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point =
let r1, r2 = scalar_split_lambda k in let lambda_p = aff_point_mul_lambda p in let r1, p1 = aff_negate_point_and_scalar_cond r1 p in let r2, p2 = aff_negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2)
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.aff_point_mul_endo_split
val aff_point_mul_endo_split (k: S.qelem) (p: S.aff_point) : S.aff_point
val aff_point_mul_endo_split (k: S.qelem) (p: S.aff_point) : S.aff_point
let aff_point_mul_endo_split (k:S.qelem) (p:S.aff_point) : S.aff_point = let r1, p1, r2, p2 = aff_ecmult_endo_split k p in S.aff_point_add (aff_point_mul r1 p1) (aff_point_mul r2 p2)
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 61, "end_line": 153, "start_col": 0, "start_line": 151 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x let qmul_shift_384 a b = a * b / pow2 384 + (a * b / pow2 383 % 2) val qmul_shift_384_lemma (a b:S.qelem) : Lemma (qmul_shift_384 a b < S.q) let qmul_shift_384_lemma a b = assert_norm (S.q < pow2 256); Math.Lemmas.lemma_mult_lt_sqr a b (pow2 256); Math.Lemmas.pow2_plus 256 256; assert (a * b < pow2 512); Math.Lemmas.lemma_div_lt_nat (a * b) 512 384; assert (a * b / pow2 384 < pow2 128); assert_norm (pow2 128 < S.q) let scalar_split_lambda (k:S.qelem) : S.qelem & S.qelem = qmul_shift_384_lemma k g1; qmul_shift_384_lemma k g2; let c1 : S.qelem = qmul_shift_384 k g1 in let c2 : S.qelem = qmul_shift_384 k g2 in let c1 = S.(c1 *^ minus_b1) in let c2 = S.(c2 *^ minus_b2) in let r2 = S.(c1 +^ c2) in let r1 = S.(k +^ r2 *^ minus_lambda) in r1, r2 (** Fast computation of [k]P in affine coordinates *) let aff_point_negate_cond (p:S.aff_point) (is_negate:bool) : S.aff_point = if is_negate then S.aff_point_negate p else p let aff_negate_point_and_scalar_cond (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.aff_point_negate p in k_neg, p_neg end else k, p // https://github.com/bitcoin-core/secp256k1/blob/master/src/ecmult_impl.h // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y) let aff_ecmult_endo_split (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point = let r1, r2 = scalar_split_lambda k in let lambda_p = aff_point_mul_lambda p in let r1, p1 = aff_negate_point_and_scalar_cond r1 p in let r2, p2 = aff_negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2) // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y)
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k: Spec.K256.PointOps.qelem -> p: Spec.K256.PointOps.aff_point -> Spec.K256.PointOps.aff_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.qelem", "Spec.K256.PointOps.aff_point", "Spec.K256.PointOps.aff_point_add", "Hacl.Spec.K256.GLV.aff_point_mul", "FStar.Pervasives.Native.tuple4", "Hacl.Spec.K256.GLV.aff_ecmult_endo_split" ]
[]
false
false
false
true
false
let aff_point_mul_endo_split (k: S.qelem) (p: S.aff_point) : S.aff_point =
let r1, p1, r2, p2 = aff_ecmult_endo_split k p in S.aff_point_add (aff_point_mul r1 p1) (aff_point_mul r2 p2)
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.ecmult_endo_split
val ecmult_endo_split (k: S.qelem) (p: S.proj_point) : S.qelem & S.proj_point & S.qelem & S.proj_point
val ecmult_endo_split (k: S.qelem) (p: S.proj_point) : S.qelem & S.proj_point & S.qelem & S.proj_point
let ecmult_endo_split (k:S.qelem) (p:S.proj_point) : S.qelem & S.proj_point & S.qelem & S.proj_point = let r1, r2 = scalar_split_lambda k in let lambda_p = point_mul_lambda p in let r1, p1 = negate_point_and_scalar_cond r1 p in let r2, p2 = negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2)
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 18, "end_line": 177, "start_col": 0, "start_line": 170 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x let qmul_shift_384 a b = a * b / pow2 384 + (a * b / pow2 383 % 2) val qmul_shift_384_lemma (a b:S.qelem) : Lemma (qmul_shift_384 a b < S.q) let qmul_shift_384_lemma a b = assert_norm (S.q < pow2 256); Math.Lemmas.lemma_mult_lt_sqr a b (pow2 256); Math.Lemmas.pow2_plus 256 256; assert (a * b < pow2 512); Math.Lemmas.lemma_div_lt_nat (a * b) 512 384; assert (a * b / pow2 384 < pow2 128); assert_norm (pow2 128 < S.q) let scalar_split_lambda (k:S.qelem) : S.qelem & S.qelem = qmul_shift_384_lemma k g1; qmul_shift_384_lemma k g2; let c1 : S.qelem = qmul_shift_384 k g1 in let c2 : S.qelem = qmul_shift_384 k g2 in let c1 = S.(c1 *^ minus_b1) in let c2 = S.(c2 *^ minus_b2) in let r2 = S.(c1 +^ c2) in let r1 = S.(k +^ r2 *^ minus_lambda) in r1, r2 (** Fast computation of [k]P in affine coordinates *) let aff_point_negate_cond (p:S.aff_point) (is_negate:bool) : S.aff_point = if is_negate then S.aff_point_negate p else p let aff_negate_point_and_scalar_cond (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.aff_point_negate p in k_neg, p_neg end else k, p // https://github.com/bitcoin-core/secp256k1/blob/master/src/ecmult_impl.h // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y) let aff_ecmult_endo_split (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point = let r1, r2 = scalar_split_lambda k in let lambda_p = aff_point_mul_lambda p in let r1, p1 = aff_negate_point_and_scalar_cond r1 p in let r2, p2 = aff_negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2) // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y) // which can be computed as a double exponentiation ([a]P + [b]Q) let aff_point_mul_endo_split (k:S.qelem) (p:S.aff_point) : S.aff_point = let r1, p1, r2, p2 = aff_ecmult_endo_split k p in S.aff_point_add (aff_point_mul r1 p1) (aff_point_mul r2 p2) (** Fast computation of [k]P in projective coordinates *) let point_negate_cond (p:S.proj_point) (is_negate:bool) : S.proj_point = if is_negate then S.point_negate p else p let negate_point_and_scalar_cond (k:S.qelem) (p:S.proj_point) : S.qelem & S.proj_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.point_negate p in k_neg, p_neg end else k, p
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k: Spec.K256.PointOps.qelem -> p: Spec.K256.PointOps.proj_point -> ((Spec.K256.PointOps.qelem * Spec.K256.PointOps.proj_point) * Spec.K256.PointOps.qelem) * Spec.K256.PointOps.proj_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.qelem", "Spec.K256.PointOps.proj_point", "FStar.Pervasives.Native.Mktuple4", "FStar.Pervasives.Native.tuple4", "FStar.Pervasives.Native.tuple2", "Hacl.Spec.K256.GLV.negate_point_and_scalar_cond", "Hacl.Spec.K256.GLV.point_mul_lambda", "Hacl.Spec.K256.GLV.scalar_split_lambda" ]
[]
false
false
false
true
false
let ecmult_endo_split (k: S.qelem) (p: S.proj_point) : S.qelem & S.proj_point & S.qelem & S.proj_point =
let r1, r2 = scalar_split_lambda k in let lambda_p = point_mul_lambda p in let r1, p1 = negate_point_and_scalar_cond r1 p in let r2, p2 = negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2)
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.negate_point_and_scalar_cond
val negate_point_and_scalar_cond (k: S.qelem) (p: S.proj_point) : S.qelem & S.proj_point
val negate_point_and_scalar_cond (k: S.qelem) (p: S.proj_point) : S.qelem & S.proj_point
let negate_point_and_scalar_cond (k:S.qelem) (p:S.proj_point) : S.qelem & S.proj_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.point_negate p in k_neg, p_neg end else k, p
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 11, "end_line": 167, "start_col": 0, "start_line": 162 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x let qmul_shift_384 a b = a * b / pow2 384 + (a * b / pow2 383 % 2) val qmul_shift_384_lemma (a b:S.qelem) : Lemma (qmul_shift_384 a b < S.q) let qmul_shift_384_lemma a b = assert_norm (S.q < pow2 256); Math.Lemmas.lemma_mult_lt_sqr a b (pow2 256); Math.Lemmas.pow2_plus 256 256; assert (a * b < pow2 512); Math.Lemmas.lemma_div_lt_nat (a * b) 512 384; assert (a * b / pow2 384 < pow2 128); assert_norm (pow2 128 < S.q) let scalar_split_lambda (k:S.qelem) : S.qelem & S.qelem = qmul_shift_384_lemma k g1; qmul_shift_384_lemma k g2; let c1 : S.qelem = qmul_shift_384 k g1 in let c2 : S.qelem = qmul_shift_384 k g2 in let c1 = S.(c1 *^ minus_b1) in let c2 = S.(c2 *^ minus_b2) in let r2 = S.(c1 +^ c2) in let r1 = S.(k +^ r2 *^ minus_lambda) in r1, r2 (** Fast computation of [k]P in affine coordinates *) let aff_point_negate_cond (p:S.aff_point) (is_negate:bool) : S.aff_point = if is_negate then S.aff_point_negate p else p let aff_negate_point_and_scalar_cond (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point = if S.scalar_is_high k then begin let k_neg = S.qnegate k in let p_neg = S.aff_point_negate p in k_neg, p_neg end else k, p // https://github.com/bitcoin-core/secp256k1/blob/master/src/ecmult_impl.h // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y) let aff_ecmult_endo_split (k:S.qelem) (p:S.aff_point) : S.qelem & S.aff_point & S.qelem & S.aff_point = let r1, r2 = scalar_split_lambda k in let lambda_p = aff_point_mul_lambda p in let r1, p1 = aff_negate_point_and_scalar_cond r1 p in let r2, p2 = aff_negate_point_and_scalar_cond r2 lambda_p in (r1, p1, r2, p2) // [k]P = [r1 + r2 * lambda]P = [r1]P + [r2]([lambda]P) = [r1](x,y) + [r2](beta*x,y) // which can be computed as a double exponentiation ([a]P + [b]Q) let aff_point_mul_endo_split (k:S.qelem) (p:S.aff_point) : S.aff_point = let r1, p1, r2, p2 = aff_ecmult_endo_split k p in S.aff_point_add (aff_point_mul r1 p1) (aff_point_mul r2 p2) (** Fast computation of [k]P in projective coordinates *) let point_negate_cond (p:S.proj_point) (is_negate:bool) : S.proj_point = if is_negate then S.point_negate p else p
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
k: Spec.K256.PointOps.qelem -> p: Spec.K256.PointOps.proj_point -> Spec.K256.PointOps.qelem * Spec.K256.PointOps.proj_point
Prims.Tot
[ "total" ]
[]
[ "Spec.K256.PointOps.qelem", "Spec.K256.PointOps.proj_point", "Spec.K256.PointOps.scalar_is_high", "FStar.Pervasives.Native.Mktuple2", "Spec.K256.PointOps.point_negate", "Spec.K256.PointOps.qnegate", "Prims.bool", "FStar.Pervasives.Native.tuple2" ]
[]
false
false
false
true
false
let negate_point_and_scalar_cond (k: S.qelem) (p: S.proj_point) : S.qelem & S.proj_point =
if S.scalar_is_high k then let k_neg = S.qnegate k in let p_neg = S.point_negate p in k_neg, p_neg else k, p
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.lambda
val lambda:S.qelem
val lambda:S.qelem
let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 89, "end_line": 46, "start_col": 0, "start_line": 46 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *)
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
false
let lambda:S.qelem =
0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.minus_b1
val minus_b1:S.qelem
val minus_b1:S.qelem
let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 59, "end_line": 67, "start_col": 0, "start_line": 67 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *)
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
false
let minus_b1:S.qelem =
0xe4437ed6010e88286f547fa90abfe4c3
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.a1
val a1:S.qelem
val a1:S.qelem
let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 53, "end_line": 66, "start_col": 0, "start_line": 66 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *)
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
false
let a1:S.qelem =
0x3086d221a7d46bcde86c90e49284eb15
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.minus_lambda
val minus_lambda:S.qelem
val minus_lambda:S.qelem
let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 3, "end_line": 74, "start_col": 0, "start_line": 71 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.b2t", "Prims.op_Equality", "Prims.int", "Prims.op_Modulus", "Prims.op_Minus", "Hacl.Spec.K256.GLV.lambda", "Spec.K256.PointOps.q" ]
[]
false
false
false
true
false
let minus_lambda:S.qelem =
let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.a2
val a2:S.qelem
val a2:S.qelem
let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 54, "end_line": 68, "start_col": 0, "start_line": 68 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
false
let a2:S.qelem =
0x114ca50f7a8e2f3f657c1108d9d44cfd8
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.beta
val beta:S.felem
val beta:S.felem
let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 87, "end_line": 48, "start_col": 0, "start_line": 48 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.felem
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
false
let beta:S.felem =
0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.minus_b2
val minus_b2:S.qelem
val minus_b2:S.qelem
let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 3, "end_line": 84, "start_col": 0, "start_line": 81 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.b2t", "Prims.op_Equality", "Prims.int", "Prims.op_Modulus", "Prims.op_Minus", "Hacl.Spec.K256.GLV.b2", "Spec.K256.PointOps.q" ]
[]
false
false
false
true
false
let minus_b2:S.qelem =
let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.b1
val b1:S.qelem
val b1:S.qelem
let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 3, "end_line": 79, "start_col": 0, "start_line": 76 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.b2t", "Prims.op_Equality", "Prims.int", "Prims.op_Modulus", "Prims.op_Minus", "Hacl.Spec.K256.GLV.minus_b1", "Spec.K256.PointOps.q" ]
[]
false
false
false
true
false
let b1:S.qelem =
let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.g2
val g2:S.qelem
val g2:S.qelem
let g2 : S.qelem = let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 3, "end_line": 94, "start_col": 0, "start_line": 91 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.b2t", "Prims.op_Equality", "Prims.int", "Prims.op_Division", "FStar.Mul.op_Star", "Prims.pow2", "Hacl.Spec.K256.GLV.minus_b1", "Spec.K256.PointOps.q" ]
[]
false
false
false
true
false
let g2:S.qelem =
let x = 0xE4437ED6010E88286F547FA90ABFE4C4221208AC9DF506C61571B4AE8AC47F71 in assert_norm (pow2 384 * minus_b1 / S.q = x); x
false
Hacl.Spec.K256.GLV.fst
Hacl.Spec.K256.GLV.g1
val g1:S.qelem
val g1:S.qelem
let g1 : S.qelem = let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x
{ "file_name": "code/k256/Hacl.Spec.K256.GLV.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 3, "end_line": 89, "start_col": 0, "start_line": 86 }
module Hacl.Spec.K256.GLV open FStar.Mul module S = Spec.K256 #set-options "--z3rlimit 50 --fuel 0 --ifuel 0" (** This module implements the following two functions from libsecp256k1: secp256k1_scalar_split_lambda [1] and secp256k1_ecmult_endo_split [2]. For the secp256k1 curve, we can replace the EC scalar multiplication by `lambda` with one modular multiplication by `beta`: [lambda](px, py) = (beta *% px, py) for any point on the curve P = (px, py), where `lambda` and `beta` are primitive cube roots of unity and can be fixed for the curve. The main idea is to slit a 256-bit scalar k into k1 and k2 s.t. k = (k1 + lambda * k2) % q, where k1 and k2 are 128-bit numbers: [k]P = [(k1 + lambda * k2) % q]P = [k1]P + [k2]([lambda]P) = [k1](px, py) + [k2](beta *% px, py). Using a double fixed-window method, we can save 128 point_double: | before | after ---------------------------------------------------------------------- point_double | 256 | 128 point_add | 256 / 5 = 51 | 128 / 5 + 128 / 5 + 1 = 25 + 25 + 1 = 51 Note that one precomputed table is enough for [k]P, as [r_small]([lambda]P) can be obtained via [r_small]P. [1]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/scalar_impl.h#L123 [2]https://github.com/bitcoin-core/secp256k1/blob/a43e982bca580f4fba19d7ffaf9b5ee3f51641cb/src/ecmult_impl.h#L618 *) (** Fast computation of [lambda]P as (beta * x, y) in affine and projective coordinates *) let lambda : S.qelem = 0x5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72 let beta : S.felem = 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee // [a]P in affine coordinates let aff_point_mul = S.aff_point_mul // fast computation of [lambda]P in affine coordinates let aff_point_mul_lambda (p:S.aff_point) : S.aff_point = let (px, py) = p in (S.(beta *% px), py) // fast computation of [lambda]P in projective coordinates let point_mul_lambda (p:S.proj_point) : S.proj_point = let (_X, _Y, _Z) = p in (S.(beta *% _X), _Y, _Z) (** Representing a scalar k as (r1 + r2 * lambda) mod S.q, s.t. r1 and r2 are ~128 bits long *) let a1 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_b1 : S.qelem = 0xe4437ed6010e88286f547fa90abfe4c3 let a2 : S.qelem = 0x114ca50f7a8e2f3f657c1108d9d44cfd8 let b2 : S.qelem = 0x3086d221a7d46bcde86c90e49284eb15 let minus_lambda : S.qelem = let x = 0xac9c52b33fa3cf1f5ad9e3fd77ed9ba4a880b9fc8ec739c2e0cfc810b51283cf in assert_norm (x = (- lambda) % S.q); x let b1 : S.qelem = let x = 0xfffffffffffffffffffffffffffffffdd66b5e10ae3a1813507ddee3c5765c7e in assert_norm (x = (- minus_b1) % S.q); x let minus_b2 : S.qelem = let x = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8A280AC50774346DD765CDA83DB1562C in assert_norm (x = (- b2) % S.q); x
{ "checked_file": "/", "dependencies": [ "Spec.K256.fst.checked", "prims.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.K256.GLV.fst" }
[ { "abbrev": true, "full_module": "Spec.K256", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.K256", "short_module": null }, { "abbrev": false, "full_module": "FStar.Pervasives", "short_module": null }, { "abbrev": false, "full_module": "Prims", "short_module": null }, { "abbrev": false, "full_module": "FStar", "short_module": null } ]
{ "detail_errors": false, "detail_hint_replay": false, "initial_fuel": 0, "initial_ifuel": 0, "max_fuel": 0, "max_ifuel": 0, "no_plugins": false, "no_smt": false, "no_tactics": false, "quake_hi": 1, "quake_keep": false, "quake_lo": 1, "retry": false, "reuse_hint_for": null, "smtencoding_elim_box": false, "smtencoding_l_arith_repr": "boxwrap", "smtencoding_nl_arith_repr": "boxwrap", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Spec.K256.PointOps.qelem
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.b2t", "Prims.op_Equality", "Prims.int", "Prims.op_Addition", "Prims.op_Division", "FStar.Mul.op_Star", "Prims.pow2", "Hacl.Spec.K256.GLV.b2", "Spec.K256.PointOps.q" ]
[]
false
false
false
true
false
let g1:S.qelem =
let x = 0x3086D221A7D46BCDE86C90E49284EB153DAA8A1471E8CA7FE893209A45DBB031 in assert_norm (pow2 384 * b2 / S.q + 1 = x); x
false