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
LowParse.Spec.DER.fst
LowParse.Spec.DER.serialize_der_length_payload
val serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x))
val serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x))
let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 6, "end_line": 567, "start_col": 0, "start_line": 534 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt8.t -> LowParse.Spec.Base.serializer (LowParse.Spec.DER.parse_der_length_payload x)
Prims.Tot
[ "total" ]
[]
[ "FStar.UInt8.t", "Prims.op_LessThan", "LowParse.Spec.Combinators.serialize_weaken", "LowParse.Spec.Combinators.parse_ret_kind", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.DER.der_length_t", "LowParse.Spec.DER.tag_of_der_length", "LowParse.Spec.DER.parse_der_length_payload_kind", "LowParse.Spec.Combinators.parse_ret", "LowParse.Spec.Combinators.serialize_ret", "LowParse.Spec.DER.tag_of_der_length_lt_128_eta", "Prims.bool", "Prims.op_BarBar", "Prims.op_Equality", "FStar.UInt8.__uint_to_t", "LowParse.Spec.Combinators.fail_serializer", "LowParse.Spec.DER.tag_of_der_length_invalid_eta", "LowParse.Spec.Combinators.parse_filter_kind", "LowParse.Spec.Int.parse_u8_kind", "LowParse.Spec.Combinators.parse_synth", "LowParse.Spec.Combinators.parse_filter_refine", "Prims.op_GreaterThanOrEqual", "FStar.UInt8.v", "LowParse.Spec.Combinators.parse_filter", "LowParse.Spec.Int.parse_u8", "LowParse.Spec.DER.synth_der_length_129", "LowParse.Spec.Combinators.serialize_synth", "LowParse.Spec.Combinators.serialize_filter", "LowParse.Spec.Int.serialize_u8", "LowParse.Spec.DER.synth_der_length_129_recip", "LowParse.Spec.Combinators.synth_inverse_intro'", "Prims.b2t", "LowParse.Spec.DER.tag_of_der_length_eq_129_eta", "LowParse.Spec.Base.total_constant_size_parser_kind", "LowParse.Spec.DER.lint", "Prims.pow2", "FStar.Mul.op_Star", "Prims.op_Subtraction", "FStar.Seq.Properties.lseq", "LowParse.Bytes.byte", "LowParse.Spec.SeqBytes.Base.parse_seq_flbytes", "LowParse.Spec.DER.synth_be_int", "LowParse.Spec.DER.synth_der_length_greater", "LowParse.Spec.DER.serialize_der_length_payload_greater", "Prims.unit", "LowParse.Spec.DER.synth_be_int_injective", "Prims.nat", "LowParse.Spec.Base.serializer", "LowParse.Spec.DER.parse_der_length_payload", "Prims._assert", "Prims.op_LessThanOrEqual", "LowParse.Spec.DER.der_length_max", "FStar.Pervasives.assert_norm", "Prims.eq2", "Prims.int" ]
[]
false
false
false
false
false
let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) =
assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let x':der_length_t = U8.v x in if x' < 128 then serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) else let len:nat = U8.v x - 128 in synth_be_int_injective len; serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len)
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_st_comp
val elab_st_comp (c: st_comp) : R.universe & R.term & R.term & R.term
val elab_st_comp (c: st_comp) : R.universe & R.term & R.term & R.term
let elab_st_comp (c:st_comp) : R.universe & R.term & R.term & R.term = let res = elab_term c.res in let pre = elab_term c.pre in let post = elab_term c.post in c.u, res, pre, post
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 23, "end_line": 120, "start_col": 0, "start_line": 115 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i let elab_pats (ps:list pattern) : Tot (list R.pattern) = L.map elab_pat ps
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
c: Pulse.Syntax.Base.st_comp -> ((FStar.Stubs.Reflection.Types.universe * FStar.Stubs.Reflection.Types.term) * FStar.Stubs.Reflection.Types.term) * FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.st_comp", "FStar.Pervasives.Native.Mktuple4", "FStar.Stubs.Reflection.Types.universe", "FStar.Stubs.Reflection.Types.term", "Pulse.Syntax.Base.__proj__Mkst_comp__item__u", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.__proj__Mkst_comp__item__post", "Pulse.Syntax.Base.__proj__Mkst_comp__item__pre", "Pulse.Syntax.Base.__proj__Mkst_comp__item__res", "FStar.Pervasives.Native.tuple4" ]
[]
false
false
false
true
false
let elab_st_comp (c: st_comp) : R.universe & R.term & R.term & R.term =
let res = elab_term c.res in let pre = elab_term c.pre in let post = elab_term c.post in c.u, res, pre, post
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.block_state_t
val block_state_t : Type0
let block_state_t = Common.s Spec.Blake2S Core.M32
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 50, "end_line": 18, "start_col": 0, "start_line": 18 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Type0
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32" ]
[]
false
false
false
true
true
let block_state_t =
Common.s Spec.Blake2S Core.M32
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_pats
val elab_pats (ps: list pattern) : Tot (list R.pattern)
val elab_pats (ps: list pattern) : Tot (list R.pattern)
let elab_pats (ps:list pattern) : Tot (list R.pattern) = L.map elab_pat ps
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 74, "end_line": 113, "start_col": 0, "start_line": 113 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
ps: Prims.list Pulse.Syntax.Base.pattern -> Prims.list FStar.Stubs.Reflection.V2.Data.pattern
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Pulse.Syntax.Base.pattern", "FStar.List.Tot.Base.map", "FStar.Stubs.Reflection.V2.Data.pattern", "Pulse.Elaborate.Pure.elab_pat" ]
[]
false
false
false
true
false
let elab_pats (ps: list pattern) : Tot (list R.pattern) =
L.map elab_pat ps
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.synth_der_length_payload32
val synth_der_length_payload32 (x: U8.t{der_length_payload_size_of_tag x <= 4}) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x)
val synth_der_length_payload32 (x: U8.t{der_length_payload_size_of_tag x <= 4}) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x)
let synth_der_length_payload32 (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x) = let _ = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end in U32.uint_to_t y
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 17, "end_line": 802, "start_col": 0, "start_line": 788 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64" let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; () #pop-options let serialize_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length_weak min max)) = serialize_synth _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () let serialize_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length min max)) = Classical.forall_intro (parse_bounded_der_length_eq min max); serialize_ext _ (serialize_bounded_der_length_weak min max) (parse_bounded_der_length min max) let serialize_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (y: bounded_int min max) : Lemma (let res = serialize (serialize_bounded_der_length min max) y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = serialize_synth_eq _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () y; serialize_der_length_weak_unfold y (* 32-bit spec *) module U32 = FStar.UInt32 let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures ( tag_of_der_length x == ( if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy ))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt8.t{LowParse.Spec.DER.der_length_payload_size_of_tag x <= 4} -> y: LowParse.Spec.Base.refine_with_tag LowParse.Spec.DER.tag_of_der_length x -> Prims.GTot (LowParse.Spec.Base.refine_with_tag LowParse.Spec.DER.tag_of_der_length32 x)
Prims.GTot
[ "sometrivial" ]
[]
[ "FStar.UInt8.t", "Prims.b2t", "Prims.op_LessThanOrEqual", "LowParse.Spec.DER.der_length_payload_size_of_tag", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.DER.der_length_t", "LowParse.Spec.DER.tag_of_der_length", "FStar.UInt32.uint_to_t", "Prims.unit", "Prims.op_GreaterThanOrEqual", "Prims._assert", "Prims.eq2", "Prims.int", "FStar.UInt8.v", "Prims.op_Addition", "LowParse.Spec.DER.log256", "LowParse.Math.pow2_lt_recip", "FStar.Mul.op_Star", "Prims.op_Subtraction", "Prims.bool", "FStar.Pervasives.assert_norm", "Prims.pow2", "LowParse.Spec.DER.der_length_max", "FStar.UInt32.t", "LowParse.Spec.DER.tag_of_der_length32" ]
[]
false
false
false
false
false
let synth_der_length_payload32 (x: U8.t{der_length_payload_size_of_tag x <= 4}) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x) =
let _ = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in if y >= 128 then (Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y)) in U32.uint_to_t y
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.der_length_payload_size_of_tag_inv32
val der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures (tag_of_der_length x == (if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy)))
val der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures (tag_of_der_length x == (if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy)))
let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures ( tag_of_der_length x == ( if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy ))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 23, "end_line": 786, "start_col": 0, "start_line": 750 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64" let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; () #pop-options let serialize_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length_weak min max)) = serialize_synth _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () let serialize_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length min max)) = Classical.forall_intro (parse_bounded_der_length_eq min max); serialize_ext _ (serialize_bounded_der_length_weak min max) (parse_bounded_der_length min max) let serialize_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (y: bounded_int min max) : Lemma (let res = serialize (serialize_bounded_der_length min max) y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = serialize_synth_eq _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () y; serialize_der_length_weak_unfold y (* 32-bit spec *) module U32 = FStar.UInt32
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: LowParse.Spec.DER.der_length_t -> FStar.Pervasives.Lemma (requires x < 4294967296) (ensures LowParse.Spec.DER.tag_of_der_length x == (match x < 128 with | true -> FStar.UInt8.uint_to_t x | _ -> (match x < 256 with | true -> 129uy | _ -> (match x < 65536 with | true -> 130uy | _ -> (match x < 16777216 with | true -> 131uy | _ -> 132uy) <: FStar.UInt8.t) <: FStar.UInt8.t) <: FStar.UInt8.t))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.DER.der_length_t", "Prims.op_LessThan", "Prims.bool", "LowParse.Spec.DER.log256_unique", "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.eq2", "Prims.int", "Prims.pow2", "FStar.Mul.op_Star", "LowParse.Math.pow2_lt_recip", "Prims.op_Subtraction", "LowParse.Spec.DER.der_length_max", "Prims.nat", "Prims.l_and", "Prims.b2t", "Prims.op_GreaterThan", "Prims.op_LessThanOrEqual", "Prims.op_Multiply", "LowParse.Spec.DER.log256", "Prims.squash", "FStar.UInt8.t", "LowParse.Spec.DER.tag_of_der_length", "FStar.UInt8.uint_to_t", "FStar.UInt8.__uint_to_t", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
false
false
true
false
false
let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures (tag_of_der_length x == (if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy))) =
if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.hash_with_key
val hash_with_key:Impl.blake2_st Spec.Blake2S Core.M32
val hash_with_key:Impl.blake2_st Spec.Blake2S Core.M32
let hash_with_key : Impl.blake2_st Spec.Blake2S Core.M32 = Impl.blake2 #Spec.Blake2S #Core.M32 Blake2s32.init Blake2s32.update Blake2s32.finish
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 86, "end_line": 60, "start_col": 0, "start_line": 59 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code let block_state_t = Common.s Spec.Blake2S Core.M32 let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) /// The incremental hash functions instantiations. Note that we can't write a /// generic one, because the normalization then performed by KaRaMeL explodes. /// All those implementations are for non-keyed hash. inline_for_extraction noextract let alloca = F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " State allocation function when there is no key")] let malloc = F.malloc (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Re-initialization function when there is no key")] let reset = F.reset (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Update function when there is no key; 0 = success, 1 = max length exceeded")] let update = F.update (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Finish function when there is no key")] let digest = F.digest (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Free state function when there is no key")] let free = F.free (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) (* The one-shot hash *) [@@ Comment "Write the BLAKE2s digest of message `input` using key `key` into `output`. @param output Pointer to `output_len` bytes of memory where the digest is written to. @param output_len Length of the to-be-generated digest with 1 <= `output_len` <= 32. @param input Pointer to `input_len` bytes of memory where the input message is read from. @param input_len Length of the input message. @param key Pointer to `key_len` bytes of memory where the key is read from.
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Hacl.Impl.Blake2.Generic.blake2_st Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32
Prims.Tot
[ "total" ]
[]
[ "Hacl.Impl.Blake2.Generic.blake2", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Blake2s_32.init", "Hacl.Blake2s_32.update", "Hacl.Blake2s_32.finish" ]
[]
false
false
false
true
false
let hash_with_key:Impl.blake2_st Spec.Blake2S Core.M32 =
Impl.blake2 #Spec.Blake2S #Core.M32 Blake2s32.init Blake2s32.update Blake2s32.finish
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.synth_der_length_payload32_injective
val synth_der_length_payload32_injective (x: U8.t{der_length_payload_size_of_tag x <= 4}) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))]
val synth_der_length_payload32_injective (x: U8.t{der_length_payload_size_of_tag x <= 4}) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))]
let synth_der_length_payload32_injective (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))] = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in synth_injective_intro' (synth_der_length_payload32 x) (fun (y1 y2: refine_with_tag tag_of_der_length x) -> if y1 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y1 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y1) == 128 + log256 y1) end; if y2 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y2 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y2) == 128 + log256 y2) end )
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 3, "end_line": 822, "start_col": 0, "start_line": 804 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64" let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; () #pop-options let serialize_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length_weak min max)) = serialize_synth _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () let serialize_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length min max)) = Classical.forall_intro (parse_bounded_der_length_eq min max); serialize_ext _ (serialize_bounded_der_length_weak min max) (parse_bounded_der_length min max) let serialize_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (y: bounded_int min max) : Lemma (let res = serialize (serialize_bounded_der_length min max) y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = serialize_synth_eq _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () y; serialize_der_length_weak_unfold y (* 32-bit spec *) module U32 = FStar.UInt32 let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures ( tag_of_der_length x == ( if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy ))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4 let synth_der_length_payload32 (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x) = let _ = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end in U32.uint_to_t y
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt8.t{LowParse.Spec.DER.der_length_payload_size_of_tag x <= 4} -> FStar.Pervasives.Lemma (ensures LowParse.Spec.Combinators.synth_injective (LowParse.Spec.DER.synth_der_length_payload32 x)) [ SMTPat (LowParse.Spec.Combinators.synth_injective (LowParse.Spec.DER.synth_der_length_payload32 x)) ]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.UInt8.t", "Prims.b2t", "Prims.op_LessThanOrEqual", "LowParse.Spec.DER.der_length_payload_size_of_tag", "LowParse.Spec.Combinators.synth_injective_intro'", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.DER.der_length_t", "LowParse.Spec.DER.tag_of_der_length", "FStar.UInt32.t", "LowParse.Spec.DER.tag_of_der_length32", "LowParse.Spec.DER.synth_der_length_payload32", "Prims.op_GreaterThanOrEqual", "Prims._assert", "Prims.eq2", "Prims.int", "FStar.UInt8.v", "Prims.op_Addition", "LowParse.Spec.DER.log256", "Prims.unit", "LowParse.Math.pow2_lt_recip", "FStar.Mul.op_Star", "Prims.op_Subtraction", "Prims.bool", "FStar.Pervasives.assert_norm", "Prims.pow2", "LowParse.Spec.DER.der_length_max", "Prims.l_True", "Prims.squash", "LowParse.Spec.Combinators.synth_injective", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.Nil" ]
[]
false
false
true
false
false
let synth_der_length_payload32_injective (x: U8.t{der_length_payload_size_of_tag x <= 4}) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))] =
assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in synth_injective_intro' (synth_der_length_payload32 x) (fun (y1: refine_with_tag tag_of_der_length x) (y2: refine_with_tag tag_of_der_length x) -> if y1 >= 128 then (Math.pow2_lt_recip (8 * (log256 y1 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y1) == 128 + log256 y1)); if y2 >= 128 then (Math.pow2_lt_recip (8 * (log256 y2 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y2) == 128 + log256 y2)))
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.parse_der_length_payload_unfold
val parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma (let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ (if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len:nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ (let res:option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ (if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None))))
val parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma (let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ (if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len:nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ (let res:option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ (if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None))))
let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 5, "end_line": 211, "start_col": 0, "start_line": 135 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt8.t -> input: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (ensures (let y = LowParse.Spec.Base.parse (LowParse.Spec.DER.parse_der_length_payload x) input in 256 < LowParse.Spec.DER.der_length_max /\ (match FStar.UInt8.v x < 128 with | true -> LowParse.Spec.DER.tag_of_der_length (FStar.UInt8.v x) == x /\ y == FStar.Pervasives.Native.Some (FStar.UInt8.v x, 0) | _ -> (match x = 128uy || x = 255uy with | true -> y == FStar.Pervasives.Native.None | _ -> (match x = 129uy with | true -> (match LowParse.Spec.Base.parse LowParse.Spec.Int.parse_u8 input with | FStar.Pervasives.Native.None #_ -> y == FStar.Pervasives.Native.None | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ z consumed) -> (match FStar.UInt8.v z < 128 with | true -> y == FStar.Pervasives.Native.None | _ -> LowParse.Spec.DER.tag_of_der_length (FStar.UInt8.v z) == x /\ y == FStar.Pervasives.Native.Some (FStar.UInt8.v z, consumed)) <: Prims.logical) <: Prims.logical | _ -> let len = FStar.UInt8.v x - 128 in LowParse.Spec.Combinators.synth_injective (LowParse.Spec.DER.synth_be_int len) /\ (let res = LowParse.Spec.Base.parse (LowParse.Spec.Combinators.parse_synth (LowParse.Spec.SeqBytes.Base.parse_seq_flbytes len) (LowParse.Spec.DER.synth_be_int len)) input in (match res with | FStar.Pervasives.Native.None #_ -> y == FStar.Pervasives.Native.None | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ z consumed) -> len > 0 /\ (match z >= Prims.pow2 (8 * (len - 1)) with | true -> z <= LowParse.Spec.DER.der_length_max /\ LowParse.Spec.DER.tag_of_der_length z == x /\ y == FStar.Pervasives.Native.Some (z, consumed) | _ -> y == FStar.Pervasives.Native.None)) <: Prims.logical)) <: Prims.logical) <: Prims.logical)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.UInt8.t", "LowParse.Bytes.bytes", "Prims.op_LessThan", "Prims.bool", "Prims.op_Equality", "FStar.UInt8.__uint_to_t", "LowParse.Spec.Base.parse", "LowParse.Spec.Int.parse_u8", "LowParse.Spec.Base.consumed_length", "Prims.op_GreaterThanOrEqual", "FStar.UInt8.v", "LowParse.Spec.DER.log256_unique", "Prims.unit", "LowParse.Spec.Combinators.parse_filter_eq", "LowParse.Spec.Int.parse_u8_kind", "LowParse.Spec.Combinators.parse_synth_eq", "LowParse.Spec.Combinators.parse_filter_kind", "LowParse.Spec.Combinators.parse_filter_refine", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.DER.der_length_t", "LowParse.Spec.DER.tag_of_der_length", "LowParse.Spec.Combinators.parse_filter", "LowParse.Spec.DER.synth_der_length_129", "LowParse.Spec.DER.lint", "Prims.pow2", "FStar.Mul.op_Star", "Prims.op_Subtraction", "FStar.Math.Lemmas.pow2_le_compat", "Prims.b2t", "Prims.op_Multiply", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.tuple2", "LowParse.Spec.Combinators.parse_synth", "LowParse.Spec.Base.total_constant_size_parser_kind", "FStar.Seq.Properties.lseq", "LowParse.Bytes.byte", "LowParse.Spec.SeqBytes.Base.parse_seq_flbytes", "LowParse.Spec.DER.synth_be_int", "Prims._assert", "Prims.op_GreaterThan", "LowParse.Spec.DER.synth_der_length_greater", "LowParse.Spec.DER.synth_be_int_injective", "Prims.nat", "Prims.op_LessThanOrEqual", "LowParse.Spec.DER.der_length_max", "FStar.Pervasives.assert_norm", "Prims.eq2", "Prims.int", "Prims.l_True", "Prims.squash", "Prims.l_and", "FStar.Pervasives.Native.Some", "FStar.Pervasives.Native.Mktuple2", "Prims.op_BarBar", "FStar.Pervasives.Native.None", "Prims.logical", "LowParse.Spec.Combinators.synth_injective", "LowParse.Spec.DER.parse_der_length_payload", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
false
false
true
false
false
let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma (let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ (if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len:nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ (let res:option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ (if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None)))) =
assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let x':der_length_t = U8.v x in if x' < 128 then () else if x = 128uy then () else if x = 255uy then () else if x = 129uy then (parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then log256_unique (U8.v y) 1) else let len:nat = U8.v x - 128 in synth_be_int_injective len; parse_synth_eq (((parse_seq_flbytes len) `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq ((parse_seq_flbytes len) `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res:option (lint len & consumed_length input) = parse ((parse_seq_flbytes len) `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then let y:y: lint len {y >= pow2 (8 * (len - 1))} = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len
false
Alg.fst
Alg.sublist
val sublist : l1: Alg.ops -> l2: Alg.ops -> Prims.logical
let sublist (l1 l2 : ops) = forall x. memP x l1 ==> memP x l2
{ "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": 46, "start_col": 0, "start_line": 46 }
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
{ "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.ops -> l2: Alg.ops -> Prims.logical
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Prims.l_Forall", "Alg.op", "Prims.l_imp", "FStar.List.Tot.Base.memP", "Prims.logical" ]
[]
false
false
false
true
true
let sublist (l1 l2: ops) =
forall x. memP x l1 ==> memP x l2
false
EverCrypt.DRBG.fst
EverCrypt.DRBG.mk_reseed
val mk_reseed: #a:supported_alg -> EverCrypt.HMAC.compute_st a -> reseed_st a
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
{ "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": 174, "start_col": 0, "start_line": 152 }
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
{ "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.reseed_st a
Prims.Tot
[ "total" ]
[]
[ "Hacl.HMAC_DRBG.supported_alg", "EverCrypt.HMAC.compute_st", "EverCrypt.DRBG.state", "LowStar.Buffer.buffer", "Lib.IntTypes.uint8", "Lib.IntTypes.size_t", "Lib.IntTypes.op_Greater_Dot", "Lib.IntTypes.U32", "Hacl.HMAC_DRBG.max_additional_input_length", "Prims.bool", "Prims.unit", "FStar.HyperStack.ST.pop_frame", "Prims.op_Negation", "Hacl.HMAC_DRBG.mk_reseed", "EverCrypt.DRBG.p", "EverCrypt.DRBG.state_s", "LowStar.BufferOps.op_Bang_Star", "LowStar.Buffer.trivial_preorder", "Spec.HMAC_DRBG.hmac_input_bound", "Lib.RandomBuffer.System.randombytes", "LowStar.Monotonic.Buffer.mbuffer", "Lib.IntTypes.int_t", "Lib.IntTypes.U8", "Lib.IntTypes.SEC", "Prims.l_and", "Prims.eq2", "Prims.nat", "LowStar.Monotonic.Buffer.length", "FStar.UInt32.v", "Prims.b2t", "LowStar.Monotonic.Buffer.g_is_null", "LowStar.Buffer.alloca", "Lib.IntTypes.u8", "FStar.HyperStack.ST.push_frame", "Lib.IntTypes.PUB", "Prims.int", "Lib.IntTypes.v", "Spec.HMAC_DRBG.min_length", "Hacl.HMAC_DRBG.min_length" ]
[]
false
false
false
false
false
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 (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) in pop_frame (); result
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.serialize_bounded_der_length32_size
val serialize_bounded_der_length32_size (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (y': bounded_int32 min max) : Lemma ( Seq.length (serialize (serialize_bounded_der_length32 min max) y') == ( if y' `U32.lt` 128ul then 1 else if y' `U32.lt` 256ul then 2 else if y' `U32.lt` 65536ul then 3 else if y' `U32.lt` 16777216ul then 4 else 5 ))
val serialize_bounded_der_length32_size (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (y': bounded_int32 min max) : Lemma ( Seq.length (serialize (serialize_bounded_der_length32 min max) y') == ( if y' `U32.lt` 128ul then 1 else if y' `U32.lt` 256ul then 2 else if y' `U32.lt` 65536ul then 3 else if y' `U32.lt` 16777216ul then 4 else 5 ))
let serialize_bounded_der_length32_size min max y' = serialize_bounded_der_length32_unfold min max y'
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 50, "end_line": 1008, "start_col": 0, "start_line": 1006 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64" let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; () #pop-options let serialize_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length_weak min max)) = serialize_synth _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () let serialize_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length min max)) = Classical.forall_intro (parse_bounded_der_length_eq min max); serialize_ext _ (serialize_bounded_der_length_weak min max) (parse_bounded_der_length min max) let serialize_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (y: bounded_int min max) : Lemma (let res = serialize (serialize_bounded_der_length min max) y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = serialize_synth_eq _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () y; serialize_der_length_weak_unfold y (* 32-bit spec *) module U32 = FStar.UInt32 let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures ( tag_of_der_length x == ( if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy ))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4 let synth_der_length_payload32 (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x) = let _ = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end in U32.uint_to_t y let synth_der_length_payload32_injective (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))] = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in synth_injective_intro' (synth_der_length_payload32 x) (fun (y1 y2: refine_with_tag tag_of_der_length x) -> if y1 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y1 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y1) == 128 + log256 y1) end; if y2 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y2 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y2) == 128 + log256 y2) end ) let parse_der_length_payload32 x : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length32 x)) = parse_der_length_payload x `parse_synth` synth_der_length_payload32 x let be_int_of_bounded_integer (len: integer_size) (x: nat { x < pow2 (8 * len) } ) : GTot (bounded_integer len) = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); U32.uint_to_t x let be_int_of_bounded_integer_injective (len: integer_size) : Lemma (synth_injective (be_int_of_bounded_integer len)) [SMTPat (synth_injective (be_int_of_bounded_integer len))] // FIXME: WHY WHY WHY does this pattern NEVER trigger? = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296) #push-options "--max_ifuel 4 --z3rlimit 16" let parse_seq_flbytes_synth_be_int_eq (len: integer_size) (input: bytes) : Lemma ( let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse ( parse_synth #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len) ) (be_int_of_bounded_integer len) ) input == parse (parse_bounded_integer len) input) = let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_synth_eq (parse_seq_flbytes len `parse_synth` synth_be_int len) (be_int_of_bounded_integer len) input; parse_synth_eq (parse_seq_flbytes len) (synth_be_int len) input; parser_kind_prop_equiv (parse_bounded_integer_kind len) (parse_bounded_integer len); parse_bounded_integer_spec len input let parse_der_length_payload32_unfold x input = parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 (8 * 1) == 256); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in begin match parse (parse_der_length_payload x) input with | None -> () | Some (y, _) -> if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end end; parse_der_length_payload_unfold x input; if U8.v x < 128 then () // tag_of_der_length (U8.v x) == x /\ y == Some (Cast.uint8_to_uint32 x, 0) else if x = 128uy || x = 255uy then () // y == None else if x = 129uy then () else begin let len : nat = U8.v x - 128 in assert (2 <= len /\ len <= 4); let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_seq_flbytes_synth_be_int_eq len input; integer_size_values len; parse_synth_eq #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len)) (be_int_of_bounded_integer len) input end #pop-options let log256_eq x = log256_unique x (log256' x) let synth_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (x: bounded_int min max) : Tot (bounded_int32 min max) = U32.uint_to_t x let parse_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) : Tot (parser (parse_bounded_der_length32_kind min max) (bounded_int32 min max)) = parse_bounded_der_length min max `parse_synth` synth_bounded_der_length32 min max #push-options "--z3rlimit 50" let parse_bounded_der_length32_unfold min max input = parse_synth_eq (parse_bounded_der_length min max) (synth_bounded_der_length32 min max) input; parse_bounded_der_length_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in assert_norm (4294967296 <= der_length_max); der_length_payload_size_le max 4294967295; assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); log256_unique 4294967295 4; parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input' ; match parse (parse_der_length_payload x) input' with | None -> () | Some (y, _) -> if y >= 128 then begin assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end else () #pop-options let synth_bounded_der_length32_recip (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (x: bounded_int32 min max) : GTot (bounded_int min max) = U32.v x let serialize_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) : Tot (serializer (parse_bounded_der_length32 min max)) = serialize_synth _ (synth_bounded_der_length32 min max) (serialize_bounded_der_length min max) (synth_bounded_der_length32_recip min max) () let serialize_bounded_der_length32_unfold min max y' = serialize_synth_eq _ (synth_bounded_der_length32 min max) (serialize_bounded_der_length min max) (synth_bounded_der_length32_recip min max) () y'; serialize_bounded_der_length_unfold min max (U32.v y'); let x = tag_of_der_length32_impl y' in if x `U8.lt` 128uy then () else if x = 129uy then FStar.Math.Lemmas.small_modulo_lemma_1 (U32.v y') 256 else begin assert (x <> 128uy /\ x <> 255uy); let len = log256' (U32.v y') in log256_eq (U32.v y'); serialize_bounded_integer_spec len y' end
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 20, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
min: LowParse.Spec.DER.der_length_t -> max: LowParse.Spec.DER.der_length_t{min <= max /\ max < 4294967296} -> y': LowParse.Spec.BoundedInt.bounded_int32 min max -> FStar.Pervasives.Lemma (ensures FStar.Seq.Base.length (LowParse.Spec.Base.serialize (LowParse.Spec.DER.serialize_bounded_der_length32 min max) y') == (match FStar.UInt32.lt y' 128ul with | true -> 1 | _ -> (match FStar.UInt32.lt y' 256ul with | true -> 2 | _ -> (match FStar.UInt32.lt y' 65536ul with | true -> 3 | _ -> (match FStar.UInt32.lt y' 16777216ul with | true -> 4 | _ -> 5) <: Prims.int) <: Prims.int) <: Prims.int))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.DER.der_length_t", "Prims.l_and", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.op_LessThan", "LowParse.Spec.BoundedInt.bounded_int32", "LowParse.Spec.DER.serialize_bounded_der_length32_unfold", "Prims.unit" ]
[]
true
false
true
false
false
let serialize_bounded_der_length32_size min max y' =
serialize_bounded_der_length32_unfold min max y'
false
Alg.fst
Alg.abides_sublist
val 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)]
val 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)]
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 32, "end_line": 97, "start_col": 0, "start_line": 93 }
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
{ "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.ops -> l2: Alg.ops -> c: Alg.tree0 a -> FStar.Pervasives.Lemma (requires Alg.abides l1 c /\ Alg.sublist l1 l2) (ensures Alg.abides l2 c) [SMTPat (Alg.abides l2 c); SMTPat (Alg.sublist l1 l2)]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.ops", "Alg.tree0", "Alg.abides_sublist_nopat", "Prims.unit", "Prims.l_and", "Alg.abides", "Alg.sublist", "Prims.squash", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.prop", "Prims.logical", "Prims.Nil" ]
[]
true
false
true
false
false
let abides_sublist #a (l1: ops) (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
false
Alg.fst
Alg.handle_tree
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
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 39, "end_line": 148, "start_col": 0, "start_line": 148 }
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)
{ "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 labs0 -> v: (_: a -> Alg.tree b labs1) -> h: Alg.handler_tree labs0 b labs1 -> Alg.tree b labs1
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.tree", "Alg.handler_tree", "Alg.fold_with" ]
[]
false
false
false
false
false
let handle_tree f v h =
fold_with f v h
false
Alg.fst
Alg.handler_tree_op
val handler_tree_op : o: Alg.op -> b: Type -> labs: Alg.ops -> Type
let handler_tree_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> tree b labs) -> tree b labs
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 54, "end_line": 135, "start_col": 0, "start_line": 134 }
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'
{ "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 -> b: Type -> labs: Alg.ops -> Type
Prims.Tot
[ "total" ]
[]
[ "Alg.op", "Alg.ops", "Alg.op_inp", "Alg.op_out", "Alg.tree" ]
[]
false
false
false
true
true
let handler_tree_op (o: op) (b: Type) (labs: ops) =
op_inp o -> (op_out o -> tree b labs) -> tree b labs
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_comp
val elab_comp (c: comp) : R.term
val elab_comp (c: comp) : R.term
let elab_comp (c:comp) : R.term = match c with | C_Tot t -> elab_term t | C_ST c -> let u, res, pre, post = elab_st_comp c in mk_stt_comp u res pre (mk_abs res R.Q_Explicit post) | C_STAtomic inames obs c -> let inames = elab_term inames in let u, res, pre, post = elab_st_comp c in let post = mk_abs res R.Q_Explicit post in mk_stt_atomic_comp (elab_observability obs) u res inames pre post | C_STGhost c -> let u, res, pre, post = elab_st_comp c in mk_stt_ghost_comp u res pre (mk_abs res R.Q_Explicit post)
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 64, "end_line": 140, "start_col": 0, "start_line": 122 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i let elab_pats (ps:list pattern) : Tot (list R.pattern) = L.map elab_pat ps let elab_st_comp (c:st_comp) : R.universe & R.term & R.term & R.term = let res = elab_term c.res in let pre = elab_term c.pre in let post = elab_term c.post in c.u, res, pre, post
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
c: Pulse.Syntax.Base.comp -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.comp", "Pulse.Syntax.Base.term", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.st_comp", "FStar.Stubs.Reflection.Types.universe", "FStar.Stubs.Reflection.Types.term", "Pulse.Reflection.Util.mk_stt_comp", "Pulse.Reflection.Util.mk_abs", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "FStar.Pervasives.Native.tuple4", "Pulse.Elaborate.Pure.elab_st_comp", "Pulse.Syntax.Base.observability", "Pulse.Reflection.Util.mk_stt_atomic_comp", "Pulse.Elaborate.Pure.elab_observability", "Pulse.Reflection.Util.mk_stt_ghost_comp" ]
[]
false
false
false
true
false
let elab_comp (c: comp) : R.term =
match c with | C_Tot t -> elab_term t | C_ST c -> let u, res, pre, post = elab_st_comp c in mk_stt_comp u res pre (mk_abs res R.Q_Explicit post) | C_STAtomic inames obs c -> let inames = elab_term inames in let u, res, pre, post = elab_st_comp c in let post = mk_abs res R.Q_Explicit post in mk_stt_atomic_comp (elab_observability obs) u res inames pre post | C_STGhost c -> let u, res, pre, post = elab_st_comp c in mk_stt_ghost_comp u res pre (mk_abs res R.Q_Explicit post)
false
Pulse.Typing.Metatheory.Base.fsti
Pulse.Typing.Metatheory.Base.inames_of_comp_st
val inames_of_comp_st : c: Pulse.Syntax.Base.comp_st -> Pulse.Syntax.Base.term
let inames_of_comp_st (c:comp_st) = match c with | C_STAtomic _ _ _ -> comp_inames c | _ -> tm_emp_inames
{ "file_name": "lib/steel/pulse/Pulse.Typing.Metatheory.Base.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 22, "end_line": 41, "start_col": 0, "start_line": 38 }
(* Copyright 2023 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 Pulse.Typing.Metatheory.Base open Pulse.Syntax open Pulse.Syntax.Naming open Pulse.Typing module RU = Pulse.RuntimeUtils module T = FStar.Tactics.V2 val admit_comp_typing (g:env) (c:comp_st) : comp_typing_u g c module RT = FStar.Reflection.Typing let rt_equiv_typing (#g:_) (#t0 #t1:_) (d:RT.equiv g t0 t1) (#k:_) (d1:Ghost.erased (RT.tot_typing g t0 k)) : Ghost.erased (RT.tot_typing g t1 k) = admit() val st_typing_correctness_ctot (#g:env) (#t:st_term) (#c:comp{C_Tot? c}) (_:st_typing g t c) : (u:Ghost.erased universe & universe_of g (comp_res c) u)
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.Naming.fsti.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Stubs.TypeChecker.Core.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Pulse.Typing.Metatheory.Base.fsti" }
[ { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Naming", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Naming", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing.Metatheory", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing.Metatheory", "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
c: Pulse.Syntax.Base.comp_st -> Pulse.Syntax.Base.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.comp_st", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.observability", "Pulse.Syntax.Base.st_comp", "Pulse.Syntax.Base.comp_inames", "Pulse.Syntax.Base.comp", "Pulse.Syntax.Base.tm_emp_inames" ]
[]
false
false
false
true
false
let inames_of_comp_st (c: comp_st) =
match c with | C_STAtomic _ _ _ -> comp_inames c | _ -> tm_emp_inames
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_pat
val elab_pat (p: pattern) : Tot R.pattern
val elab_pat (p: pattern) : Tot R.pattern
let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 15, "end_line": 111, "start_col": 0, "start_line": 96 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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: Pulse.Syntax.Base.pattern -> FStar.Stubs.Reflection.V2.Data.pattern
Prims.Tot
[ "total" ]
[ "elab_pat", "elab_sub_pat" ]
[ "Pulse.Syntax.Base.pattern", "Pulse.Syntax.Base.constant", "FStar.Stubs.Reflection.V2.Data.Pat_Constant", "FStar.Reflection.Typing.pp_name_t", "FStar.Reflection.Typing.sort_t", "FStar.Stubs.Reflection.V2.Data.Pat_Var", "FStar.Reflection.Typing.sort_default", "Pulse.Syntax.Base.fv", "Prims.list", "FStar.Pervasives.Native.tuple2", "Prims.bool", "FStar.Stubs.Reflection.V2.Data.Pat_Cons", "FStar.Pervasives.Native.None", "FStar.Stubs.Reflection.V2.Data.universes", "Pulse.Common.map_dec", "FStar.Stubs.Reflection.V2.Data.pattern", "Pulse.Elaborate.Pure.elab_sub_pat", "FStar.Stubs.Reflection.V2.Data.Pat_Dot_Term", "FStar.Stubs.Reflection.Types.term", "Pulse.Syntax.Base.term", "FStar.Pervasives.Native.Some", "Pulse.Elaborate.Pure.elab_term", "FStar.Stubs.Reflection.Types.fv", "FStar.Stubs.Reflection.V2.Builtins.pack_fv", "Pulse.Syntax.Base.__proj__Mkfv__item__fv_name" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec elab_pat (p: pattern) : Tot R.pattern =
let elab_fv (f: fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t))
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.free
val free : Hacl.Streaming.Functor.free_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) (FStar.Ghost.reveal (FStar.Ghost.hide ())) (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
let free = F.free (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 100, "end_line": 48, "start_col": 0, "start_line": 47 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code let block_state_t = Common.s Spec.Blake2S Core.M32 let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) /// The incremental hash functions instantiations. Note that we can't write a /// generic one, because the normalization then performed by KaRaMeL explodes. /// All those implementations are for non-keyed hash. inline_for_extraction noextract let alloca = F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " State allocation function when there is no key")] let malloc = F.malloc (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Re-initialization function when there is no key")] let reset = F.reset (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Update function when there is no key; 0 = success, 1 = max length exceeded")] let update = F.update (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Finish function when there is no key")] let digest = F.digest (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Hacl.Streaming.Functor.free_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) (FStar.Ghost.reveal (FStar.Ghost.hide ())) (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Functor.free", "Prims.unit", "Hacl.Streaming.Blake2s_32.blake2s_32", "FStar.Ghost.hide", "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Streaming.Blake2.Common.empty_key" ]
[]
false
false
false
false
false
let free =
F.free (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.state_t
val state_t : Type0
let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 106, "end_line": 19, "start_col": 0, "start_line": 19 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Type0
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Functor.state_s", "Prims.unit", "Hacl.Streaming.Blake2s_32.blake2s_32", "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Streaming.Blake2.Common.empty_key" ]
[]
false
false
false
true
true
let state_t =
F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_qual
val elab_qual : _: FStar.Pervasives.Native.option Pulse.Syntax.Base.qualifier -> FStar.Stubs.Reflection.V2.Data.aqualv
let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 33, "end_line": 34, "start_col": 0, "start_line": 32 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
_: FStar.Pervasives.Native.option Pulse.Syntax.Base.qualifier -> FStar.Stubs.Reflection.V2.Data.aqualv
Prims.Tot
[ "total" ]
[]
[ "FStar.Pervasives.Native.option", "Pulse.Syntax.Base.qualifier", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "FStar.Stubs.Reflection.V2.Data.Q_Implicit", "FStar.Stubs.Reflection.V2.Data.aqualv" ]
[]
false
false
false
true
false
let elab_qual =
function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit
false
Alg.fst
Alg.abides
val abides (#a: _) (labs: ops) (f: tree0 a) : prop
val abides (#a: _) (labs: ops) (f: tree0 a) : prop
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 5, "end_line": 53, "start_col": 0, "start_line": 49 }
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
{ "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
labs: Alg.ops -> f: Alg.tree0 a -> Prims.prop
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.tree0", "Alg.op", "Alg.op_inp", "Alg.op_out", "Prims.l_and", "FStar.List.Tot.Base.memP", "Prims.l_Forall", "Alg.abides", "Prims.l_True", "Prims.prop" ]
[ "recursion" ]
false
false
false
true
true
let rec abides #a (labs: ops) (f: tree0 a) : prop =
match f with | Op a i k -> a `memP` labs /\ (forall o. abides labs (k o)) | Return _ -> True
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_observability
val elab_observability : _: Pulse.Syntax.Base.observability -> FStar.Stubs.Reflection.Types.term
let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid))
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 61, "end_line": 41, "start_col": 0, "start_line": 36 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
_: Pulse.Syntax.Base.observability -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.observability", "FStar.Stubs.Reflection.V2.Builtins.pack_ln", "FStar.Stubs.Reflection.V2.Data.Tv_FVar", "FStar.Stubs.Reflection.V2.Builtins.pack_fv", "Pulse.Reflection.Util.neutral_lid", "Pulse.Reflection.Util.unobservable_lid", "Pulse.Reflection.Util.observable_lid", "FStar.Stubs.Reflection.Types.term" ]
[]
false
false
false
true
false
let elab_observability =
let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid))
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_term
val elab_term (top: term) : R.term
val elab_term (top: term) : R.term
let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 9, "end_line": 93, "start_col": 0, "start_line": 43 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid))
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
top: Pulse.Syntax.Base.term -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.__proj__Mkterm__item__t", "FStar.Stubs.Reflection.V2.Builtins.pack_ln", "FStar.Stubs.Reflection.V2.Data.Tv_FVar", "FStar.Stubs.Reflection.V2.Builtins.pack_fv", "Pulse.Reflection.Util.vprop_lid", "Pulse.Reflection.Util.emp_lid", "FStar.Stubs.Reflection.V2.Data.Tv_App", "FStar.Pervasives.Native.Mktuple2", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Reflection.Util.inv_lid", "Pulse.Elaborate.Pure.elab_term", "Pulse.Reflection.Util.pure_lid", "Pulse.Reflection.Util.mk_star", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.binder", "Pulse.Syntax.Base.uu___is_Tm_ExistsSL", "Pulse.Reflection.Util.mk_exists", "Pulse.Reflection.Util.mk_abs_with_name_and_range", "Pulse.Syntax.Base.__proj__Mkppname__item__name", "Pulse.Syntax.Base.__proj__Mkbinder__item__binder_ppname", "Pulse.Syntax.Base.__proj__Mkppname__item__range", "Prims.bool", "Pulse.Reflection.Util.mk_forall", "range", "binder_ppname", "Pulse.Syntax.Base.__proj__Mkbinder__item__binder_ty", "Pulse.Reflection.Util.inames_lid", "Pulse.Reflection.Util.emp_inames_tm", "Pulse.Reflection.Util.add_inv_tm", "FStar.Stubs.Reflection.V2.Data.Tv_Unknown", "Pulse.Syntax.Base.host_term", "Prims.eq2", "Pulse.RuntimeUtils.set_range", "Pulse.Syntax.Base.__proj__Mkterm__item__range" ]
[ "recursion" ]
false
false
false
true
false
let rec elab_term (top: term) : R.term =
let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body )) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body )) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.blake2s_32
val blake2s_32 : kk: Hacl.Streaming.Blake2.Common.key_size Spec.Blake2.Definitions.Blake2S -> Hacl.Streaming.Interface.block Prims.unit
let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 47, "end_line": 14, "start_col": 0, "start_line": 12 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
kk: Hacl.Streaming.Blake2.Common.key_size Spec.Blake2.Definitions.Blake2S -> Hacl.Streaming.Interface.block Prims.unit
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Blake2.Common.key_size", "Spec.Blake2.Definitions.Blake2S", "Hacl.Streaming.Blake2.Common.blake2", "Hacl.Impl.Blake2.Core.M32", "Hacl.Blake2s_32.init", "Hacl.Blake2s_32.update_multi", "Hacl.Blake2s_32.update_last", "Hacl.Blake2s_32.finish", "Hacl.Streaming.Interface.block", "Prims.unit" ]
[]
false
false
false
true
false
let blake2s_32 kk =
Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_sub_pat
val elab_sub_pat (pi: pattern & bool) : R.pattern & bool
val elab_sub_pat (pi: pattern & bool) : R.pattern & bool
let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 15, "end_line": 111, "start_col": 0, "start_line": 96 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
pi: (Pulse.Syntax.Base.pattern * Prims.bool) -> FStar.Stubs.Reflection.V2.Data.pattern * Prims.bool
Prims.Tot
[ "total" ]
[ "elab_pat", "elab_sub_pat" ]
[ "FStar.Pervasives.Native.tuple2", "Pulse.Syntax.Base.pattern", "Prims.bool", "FStar.Pervasives.Native.Mktuple2", "FStar.Stubs.Reflection.V2.Data.pattern", "Pulse.Elaborate.Pure.elab_pat" ]
[ "mutual recursion" ]
false
false
false
true
false
let rec elab_sub_pat (pi: pattern & bool) : R.pattern & bool =
let p, i = pi in elab_pat p, i
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_statomic_equiv
val elab_statomic_equiv (g: R.env) (c: comp{C_STAtomic? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STAtomic inames obs { u = u ; res = res } = c in mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post) (elab_comp c)
val elab_statomic_equiv (g: R.env) (c: comp{C_STAtomic? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STAtomic inames obs { u = u ; res = res } = c in mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post) (elab_comp c)
let elab_statomic_equiv (g:R.env) (c:comp{C_STAtomic? c}) (pre:R.term) (post:R.term) (eq_pre:RT.equiv g pre (elab_term (comp_pre c))) (eq_post:RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STAtomic inames obs {u;res} = c in mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post) (elab_comp c) = let C_STAtomic inames obs {u;res} = c in let c' = mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post in mk_stt_atomic_comp_equiv _ (elab_observability obs) (comp_u c) (elab_term (comp_res c)) (elab_term inames) _ _ _ _ eq_pre eq_post
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 28, "end_line": 184, "start_col": 0, "start_line": 159 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i let elab_pats (ps:list pattern) : Tot (list R.pattern) = L.map elab_pat ps let elab_st_comp (c:st_comp) : R.universe & R.term & R.term & R.term = let res = elab_term c.res in let pre = elab_term c.pre in let post = elab_term c.post in c.u, res, pre, post let elab_comp (c:comp) : R.term = match c with | C_Tot t -> elab_term t | C_ST c -> let u, res, pre, post = elab_st_comp c in mk_stt_comp u res pre (mk_abs res R.Q_Explicit post) | C_STAtomic inames obs c -> let inames = elab_term inames in let u, res, pre, post = elab_st_comp c in let post = mk_abs res R.Q_Explicit post in mk_stt_atomic_comp (elab_observability obs) u res inames pre post | C_STGhost c -> let u, res, pre, post = elab_st_comp c in mk_stt_ghost_comp u res pre (mk_abs res R.Q_Explicit post) let elab_stt_equiv (g:R.env) (c:comp{C_ST? c}) (pre:R.term) (post:R.term) (eq_pre:RT.equiv g pre (elab_term (comp_pre c))) (eq_post:RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_ST {u;res} = c in mk_stt_comp u (elab_term res) pre post) (elab_comp c) = mk_stt_comp_equiv _ (comp_u c) (elab_term (comp_res c)) _ _ _ _ _ (RT.Rel_refl _ _ _) eq_pre eq_post
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
g: FStar.Stubs.Reflection.Types.env -> c: Pulse.Syntax.Base.comp{C_STAtomic? c} -> pre: FStar.Stubs.Reflection.Types.term -> post: FStar.Stubs.Reflection.Types.term -> eq_pre: FStar.Reflection.Typing.equiv g pre (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_pre c)) -> eq_post: FStar.Reflection.Typing.equiv g post (Pulse.Reflection.Util.mk_abs (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_res c) ) FStar.Stubs.Reflection.V2.Data.Q_Explicit (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_post c))) -> FStar.Reflection.Typing.equiv g (let _ = c in (let Pulse.Syntax.Base.C_STAtomic inames obs { u = u60 ; res = res ; pre = _ ; post = _ } = _ in Pulse.Reflection.Util.mk_stt_atomic_comp (Pulse.Elaborate.Pure.elab_observability obs) u60 (Pulse.Elaborate.Pure.elab_term res) (Pulse.Elaborate.Pure.elab_term inames) pre post) <: FStar.Stubs.Reflection.Types.term) (Pulse.Elaborate.Pure.elab_comp c)
Prims.Tot
[ "total" ]
[]
[ "FStar.Stubs.Reflection.Types.env", "Pulse.Syntax.Base.comp", "Prims.b2t", "Pulse.Syntax.Base.uu___is_C_STAtomic", "FStar.Stubs.Reflection.Types.term", "FStar.Reflection.Typing.equiv", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_pre", "Pulse.Reflection.Util.mk_abs", "Pulse.Syntax.Base.comp_res", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.observability", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.vprop", "Pulse.Reflection.Util.mk_stt_atomic_comp_equiv", "Pulse.Elaborate.Pure.elab_observability", "Pulse.Syntax.Base.comp_u", "Pulse.Reflection.Util.mk_stt_atomic_comp", "Pulse.Elaborate.Pure.elab_comp" ]
[]
false
false
false
false
false
let elab_statomic_equiv (g: R.env) (c: comp{C_STAtomic? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STAtomic inames obs { u = u ; res = res } = c in mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post) (elab_comp c) =
let C_STAtomic inames obs { u = u ; res = res } = c in let c' = mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post in mk_stt_atomic_comp_equiv _ (elab_observability obs) (comp_u c) (elab_term (comp_res c)) (elab_term inames) _ _ _ _ eq_pre eq_post
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.reset
val reset : Hacl.Streaming.Functor.reset_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) (FStar.Ghost.hide (FStar.Ghost.reveal (FStar.Ghost.hide ()))) (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
let reset = F.reset (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 92, "end_line": 36, "start_col": 0, "start_line": 35 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code let block_state_t = Common.s Spec.Blake2S Core.M32 let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) /// The incremental hash functions instantiations. Note that we can't write a /// generic one, because the normalization then performed by KaRaMeL explodes. /// All those implementations are for non-keyed hash. inline_for_extraction noextract let alloca = F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " State allocation function when there is no key")] let malloc = F.malloc (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Hacl.Streaming.Functor.reset_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) (FStar.Ghost.hide (FStar.Ghost.reveal (FStar.Ghost.hide ()))) (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Functor.reset", "Prims.unit", "Hacl.Streaming.Blake2s_32.blake2s_32", "FStar.Ghost.hide", "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Streaming.Blake2.Common.empty_key" ]
[]
false
false
false
false
false
let reset =
F.reset (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
false
Alg.fst
Alg.abides_app
val 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)]
val 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)]
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 20, "end_line": 112, "start_col": 0, "start_line": 108 }
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)
{ "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.ops -> l2: Alg.ops -> c: Alg.tree0 a -> FStar.Pervasives.Lemma (requires Alg.abides l1 c \/ Alg.abides l2 c) (ensures Alg.abides (l1 @ l2) c) [SMTPat (Alg.abides (l1 @ l2) c)]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.ops", "Alg.tree0", "Alg.sublist_at", "Prims.unit", "Prims.l_or", "Alg.abides", "Prims.squash", "FStar.List.Tot.Base.op_At", "Alg.op", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.prop", "Prims.Nil" ]
[]
true
false
true
false
false
let abides_app #a (l1: ops) (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
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.malloc
val malloc : Hacl.Streaming.Functor.malloc_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) () (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
let malloc = F.malloc (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 93, "end_line": 32, "start_col": 0, "start_line": 31 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code let block_state_t = Common.s Spec.Blake2S Core.M32 let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) /// The incremental hash functions instantiations. Note that we can't write a /// generic one, because the normalization then performed by KaRaMeL explodes. /// All those implementations are for non-keyed hash. inline_for_extraction noextract let alloca = F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Hacl.Streaming.Functor.malloc_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) () (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Functor.malloc", "Prims.unit", "Hacl.Streaming.Blake2s_32.blake2s_32", "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Streaming.Blake2.Common.empty_key" ]
[]
false
false
false
false
false
let malloc =
F.malloc (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
false
Alg.fst
Alg.abides_sublist_nopat
val abides_sublist_nopat (#a: _) (l1 l2: ops) (c: tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c)
val abides_sublist_nopat (#a: _) (l1 l2: ops) (c: tree0 a) : Lemma (requires (abides l1 c) /\ sublist l1 l2) (ensures (abides l2) c)
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 32, "end_line": 91, "start_col": 0, "start_line": 82 }
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))] = ()
{ "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.ops -> l2: Alg.ops -> c: Alg.tree0 a -> FStar.Pervasives.Lemma (requires Alg.abides l1 c /\ Alg.sublist l1 l2) (ensures Alg.abides l2 c)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.ops", "Alg.tree0", "Alg.op", "Alg.op_inp", "Alg.op_out", "FStar.Classical.forall_intro", "Alg.abides", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.Nil", "FStar.Pervasives.pattern", "Alg.abides_sublist_nopat", "Prims.l_and", "Alg.sublist" ]
[ "recursion" ]
false
false
true
false
false
let rec abides_sublist_nopat #a (l1: ops) (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
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_stghost_equiv
val elab_stghost_equiv (g: R.env) (c: comp{C_STGhost? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STGhost { u = u ; res = res } = c in mk_stt_ghost_comp u (elab_term res) pre post) (elab_comp c)
val elab_stghost_equiv (g: R.env) (c: comp{C_STGhost? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STGhost { u = u ; res = res } = c in mk_stt_ghost_comp u (elab_term res) pre post) (elab_comp c)
let elab_stghost_equiv (g:R.env) (c:comp{C_STGhost? c}) (pre:R.term) (post:R.term) (eq_pre:RT.equiv g pre (elab_term (comp_pre c))) (eq_post:RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STGhost {u;res} = c in mk_stt_ghost_comp u (elab_term res) pre post) (elab_comp c) = let C_STGhost _ = c in mk_stt_ghost_comp_equiv _ (comp_u c) (elab_term (comp_res c)) _ _ _ _ eq_pre eq_post
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 26, "end_line": 202, "start_col": 0, "start_line": 186 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i let elab_pats (ps:list pattern) : Tot (list R.pattern) = L.map elab_pat ps let elab_st_comp (c:st_comp) : R.universe & R.term & R.term & R.term = let res = elab_term c.res in let pre = elab_term c.pre in let post = elab_term c.post in c.u, res, pre, post let elab_comp (c:comp) : R.term = match c with | C_Tot t -> elab_term t | C_ST c -> let u, res, pre, post = elab_st_comp c in mk_stt_comp u res pre (mk_abs res R.Q_Explicit post) | C_STAtomic inames obs c -> let inames = elab_term inames in let u, res, pre, post = elab_st_comp c in let post = mk_abs res R.Q_Explicit post in mk_stt_atomic_comp (elab_observability obs) u res inames pre post | C_STGhost c -> let u, res, pre, post = elab_st_comp c in mk_stt_ghost_comp u res pre (mk_abs res R.Q_Explicit post) let elab_stt_equiv (g:R.env) (c:comp{C_ST? c}) (pre:R.term) (post:R.term) (eq_pre:RT.equiv g pre (elab_term (comp_pre c))) (eq_post:RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_ST {u;res} = c in mk_stt_comp u (elab_term res) pre post) (elab_comp c) = mk_stt_comp_equiv _ (comp_u c) (elab_term (comp_res c)) _ _ _ _ _ (RT.Rel_refl _ _ _) eq_pre eq_post #push-options "--query_stats" let elab_statomic_equiv (g:R.env) (c:comp{C_STAtomic? c}) (pre:R.term) (post:R.term) (eq_pre:RT.equiv g pre (elab_term (comp_pre c))) (eq_post:RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STAtomic inames obs {u;res} = c in mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post) (elab_comp c) = let C_STAtomic inames obs {u;res} = c in let c' = mk_stt_atomic_comp (elab_observability obs) u (elab_term res) (elab_term inames) pre post in mk_stt_atomic_comp_equiv _ (elab_observability obs) (comp_u c) (elab_term (comp_res c)) (elab_term inames) _ _ _ _ eq_pre eq_post
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
g: FStar.Stubs.Reflection.Types.env -> c: Pulse.Syntax.Base.comp{C_STGhost? c} -> pre: FStar.Stubs.Reflection.Types.term -> post: FStar.Stubs.Reflection.Types.term -> eq_pre: FStar.Reflection.Typing.equiv g pre (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_pre c)) -> eq_post: FStar.Reflection.Typing.equiv g post (Pulse.Reflection.Util.mk_abs (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_res c) ) FStar.Stubs.Reflection.V2.Data.Q_Explicit (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_post c))) -> FStar.Reflection.Typing.equiv g (let _ = c in (let Pulse.Syntax.Base.C_STGhost { u = u70 ; res = res ; pre = _ ; post = _ } = _ in Pulse.Reflection.Util.mk_stt_ghost_comp u70 (Pulse.Elaborate.Pure.elab_term res) pre post) <: FStar.Stubs.Reflection.Types.term) (Pulse.Elaborate.Pure.elab_comp c)
Prims.Tot
[ "total" ]
[]
[ "FStar.Stubs.Reflection.Types.env", "Pulse.Syntax.Base.comp", "Prims.b2t", "Pulse.Syntax.Base.uu___is_C_STGhost", "FStar.Stubs.Reflection.Types.term", "FStar.Reflection.Typing.equiv", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_pre", "Pulse.Reflection.Util.mk_abs", "Pulse.Syntax.Base.comp_res", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.st_comp", "Pulse.Reflection.Util.mk_stt_ghost_comp_equiv", "Pulse.Syntax.Base.comp_u", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.vprop", "Pulse.Reflection.Util.mk_stt_ghost_comp", "Pulse.Elaborate.Pure.elab_comp" ]
[]
false
false
false
false
false
let elab_stghost_equiv (g: R.env) (c: comp{C_STGhost? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_STGhost { u = u ; res = res } = c in mk_stt_ghost_comp u (elab_term res) pre post) (elab_comp c) =
let C_STGhost _ = c in mk_stt_ghost_comp_equiv _ (comp_u c) (elab_term (comp_res c)) _ _ _ _ eq_pre eq_post
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.serialize_bounded_der_length32_unfold
val serialize_bounded_der_length32_unfold (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (y': bounded_int32 min max) : Lemma ( let res = serialize (serialize_bounded_der_length32 min max) y' in let x = tag_of_der_length32_impl y' in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then U32.v y' <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (Cast.uint32_to_uint8 y')) else let len = log256' (U32.v y') in res `Seq.equal` (s1 `Seq.append` serialize (serialize_bounded_integer len) y') )
val serialize_bounded_der_length32_unfold (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (y': bounded_int32 min max) : Lemma ( let res = serialize (serialize_bounded_der_length32 min max) y' in let x = tag_of_der_length32_impl y' in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then U32.v y' <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (Cast.uint32_to_uint8 y')) else let len = log256' (U32.v y') in res `Seq.equal` (s1 `Seq.append` serialize (serialize_bounded_integer len) y') )
let serialize_bounded_der_length32_unfold min max y' = serialize_synth_eq _ (synth_bounded_der_length32 min max) (serialize_bounded_der_length min max) (synth_bounded_der_length32_recip min max) () y'; serialize_bounded_der_length_unfold min max (U32.v y'); let x = tag_of_der_length32_impl y' in if x `U8.lt` 128uy then () else if x = 129uy then FStar.Math.Lemmas.small_modulo_lemma_1 (U32.v y') 256 else begin assert (x <> 128uy /\ x <> 255uy); let len = log256' (U32.v y') in log256_eq (U32.v y'); serialize_bounded_integer_spec len y' end
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 7, "end_line": 1003, "start_col": 0, "start_line": 983 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64" let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; () #pop-options let serialize_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length_weak min max)) = serialize_synth _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () let serialize_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length min max)) = Classical.forall_intro (parse_bounded_der_length_eq min max); serialize_ext _ (serialize_bounded_der_length_weak min max) (parse_bounded_der_length min max) let serialize_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (y: bounded_int min max) : Lemma (let res = serialize (serialize_bounded_der_length min max) y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = serialize_synth_eq _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () y; serialize_der_length_weak_unfold y (* 32-bit spec *) module U32 = FStar.UInt32 let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures ( tag_of_der_length x == ( if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy ))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4 let synth_der_length_payload32 (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x) = let _ = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end in U32.uint_to_t y let synth_der_length_payload32_injective (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))] = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in synth_injective_intro' (synth_der_length_payload32 x) (fun (y1 y2: refine_with_tag tag_of_der_length x) -> if y1 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y1 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y1) == 128 + log256 y1) end; if y2 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y2 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y2) == 128 + log256 y2) end ) let parse_der_length_payload32 x : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length32 x)) = parse_der_length_payload x `parse_synth` synth_der_length_payload32 x let be_int_of_bounded_integer (len: integer_size) (x: nat { x < pow2 (8 * len) } ) : GTot (bounded_integer len) = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); U32.uint_to_t x let be_int_of_bounded_integer_injective (len: integer_size) : Lemma (synth_injective (be_int_of_bounded_integer len)) [SMTPat (synth_injective (be_int_of_bounded_integer len))] // FIXME: WHY WHY WHY does this pattern NEVER trigger? = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296) #push-options "--max_ifuel 4 --z3rlimit 16" let parse_seq_flbytes_synth_be_int_eq (len: integer_size) (input: bytes) : Lemma ( let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse ( parse_synth #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len) ) (be_int_of_bounded_integer len) ) input == parse (parse_bounded_integer len) input) = let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_synth_eq (parse_seq_flbytes len `parse_synth` synth_be_int len) (be_int_of_bounded_integer len) input; parse_synth_eq (parse_seq_flbytes len) (synth_be_int len) input; parser_kind_prop_equiv (parse_bounded_integer_kind len) (parse_bounded_integer len); parse_bounded_integer_spec len input let parse_der_length_payload32_unfold x input = parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 (8 * 1) == 256); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in begin match parse (parse_der_length_payload x) input with | None -> () | Some (y, _) -> if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end end; parse_der_length_payload_unfold x input; if U8.v x < 128 then () // tag_of_der_length (U8.v x) == x /\ y == Some (Cast.uint8_to_uint32 x, 0) else if x = 128uy || x = 255uy then () // y == None else if x = 129uy then () else begin let len : nat = U8.v x - 128 in assert (2 <= len /\ len <= 4); let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_seq_flbytes_synth_be_int_eq len input; integer_size_values len; parse_synth_eq #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len)) (be_int_of_bounded_integer len) input end #pop-options let log256_eq x = log256_unique x (log256' x) let synth_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (x: bounded_int min max) : Tot (bounded_int32 min max) = U32.uint_to_t x let parse_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) : Tot (parser (parse_bounded_der_length32_kind min max) (bounded_int32 min max)) = parse_bounded_der_length min max `parse_synth` synth_bounded_der_length32 min max #push-options "--z3rlimit 50" let parse_bounded_der_length32_unfold min max input = parse_synth_eq (parse_bounded_der_length min max) (synth_bounded_der_length32 min max) input; parse_bounded_der_length_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in assert_norm (4294967296 <= der_length_max); der_length_payload_size_le max 4294967295; assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); log256_unique 4294967295 4; parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input' ; match parse (parse_der_length_payload x) input' with | None -> () | Some (y, _) -> if y >= 128 then begin assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end else () #pop-options let synth_bounded_der_length32_recip (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (x: bounded_int32 min max) : GTot (bounded_int min max) = U32.v x let serialize_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) : Tot (serializer (parse_bounded_der_length32 min max)) = serialize_synth _ (synth_bounded_der_length32 min max) (serialize_bounded_der_length min max) (synth_bounded_der_length32_recip min max) ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
min: LowParse.Spec.DER.der_length_t -> max: LowParse.Spec.DER.der_length_t{min <= max /\ max < 4294967296} -> y': LowParse.Spec.BoundedInt.bounded_int32 min max -> FStar.Pervasives.Lemma (ensures (let res = LowParse.Spec.Base.serialize (LowParse.Spec.DER.serialize_bounded_der_length32 min max) y' in let x = LowParse.Spec.DER.tag_of_der_length32_impl y' in let s1 = FStar.Seq.Base.create 1 x in (match FStar.UInt8.lt x 128uy with | true -> FStar.Seq.Base.equal res s1 | _ -> (match x = 129uy with | true -> FStar.UInt32.v y' <= 255 /\ FStar.Seq.Base.equal res (FStar.Seq.Base.append s1 (FStar.Seq.Base.create 1 (FStar.Int.Cast.uint32_to_uint8 y'))) | _ -> let len = LowParse.Spec.BoundedInt.log256' (FStar.UInt32.v y') in FStar.Seq.Base.equal res (FStar.Seq.Base.append s1 (LowParse.Spec.Base.serialize (LowParse.Spec.BoundedInt.serialize_bounded_integer len) y'))) <: Type0) <: Type0))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.DER.der_length_t", "Prims.l_and", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.op_LessThan", "LowParse.Spec.BoundedInt.bounded_int32", "FStar.UInt8.lt", "FStar.UInt8.__uint_to_t", "Prims.bool", "Prims.op_Equality", "FStar.UInt8.t", "FStar.Math.Lemmas.small_modulo_lemma_1", "FStar.UInt32.v", "LowParse.Spec.BoundedInt.serialize_bounded_integer_spec", "Prims.unit", "LowParse.Spec.DER.log256_eq", "LowParse.Spec.BoundedInt.integer_size", "LowParse.Spec.BoundedInt.log256'", "Prims._assert", "Prims.op_disEquality", "LowParse.Spec.DER.der_length_max", "Prims.eq2", "LowParse.Spec.DER.tag_of_der_length", "LowParse.Spec.DER.tag_of_der_length32_impl", "LowParse.Spec.DER.serialize_bounded_der_length_unfold", "LowParse.Spec.Combinators.serialize_synth_eq", "LowParse.Spec.DER.parse_bounded_der_length_kind", "LowParse.Spec.DER.bounded_int", "LowParse.Spec.DER.parse_bounded_der_length", "LowParse.Spec.DER.synth_bounded_der_length32", "LowParse.Spec.DER.serialize_bounded_der_length", "LowParse.Spec.DER.synth_bounded_der_length32_recip" ]
[]
false
false
true
false
false
let serialize_bounded_der_length32_unfold min max y' =
serialize_synth_eq _ (synth_bounded_der_length32 min max) (serialize_bounded_der_length min max) (synth_bounded_der_length32_recip min max) () y'; serialize_bounded_der_length_unfold min max (U32.v y'); let x = tag_of_der_length32_impl y' in if x `U8.lt` 128uy then () else if x = 129uy then FStar.Math.Lemmas.small_modulo_lemma_1 (U32.v y') 256 else (assert (x <> 128uy /\ x <> 255uy); let len = log256' (U32.v y') in log256_eq (U32.v y'); serialize_bounded_integer_spec len y')
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.update
val update : Hacl.Streaming.Functor.update_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) (FStar.Ghost.reveal (FStar.Ghost.hide ())) (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
let update = F.update (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 102, "end_line": 40, "start_col": 0, "start_line": 39 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code let block_state_t = Common.s Spec.Blake2S Core.M32 let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) /// The incremental hash functions instantiations. Note that we can't write a /// generic one, because the normalization then performed by KaRaMeL explodes. /// All those implementations are for non-keyed hash. inline_for_extraction noextract let alloca = F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " State allocation function when there is no key")] let malloc = F.malloc (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Re-initialization function when there is no key")] let reset = F.reset (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Hacl.Streaming.Functor.update_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) (FStar.Ghost.reveal (FStar.Ghost.hide ())) (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Functor.update", "Prims.unit", "Hacl.Streaming.Blake2s_32.blake2s_32", "FStar.Ghost.hide", "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Streaming.Blake2.Common.empty_key" ]
[]
false
false
false
false
false
let update =
F.update (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
false
Alg.fst
Alg.abides_at_self
val abides_at_self (#a: _) (l: ops) (c: tree0 a) : Lemma (abides (l @ l) c <==> abides l c) [SMTPat (abides (l @ l) c)]
val abides_at_self (#a: _) (l: ops) (c: tree0 a) : Lemma (abides (l @ l) c <==> abides l c) [SMTPat (abides (l @ l) 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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 28, "end_line": 106, "start_col": 0, "start_line": 99 }
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
{ "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.ops -> c: Alg.tree0 a -> FStar.Pervasives.Lemma (ensures Alg.abides (l @ l) c <==> Alg.abides l c) [SMTPat (Alg.abides (l @ l) c)]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.ops", "Alg.tree0", "Prims._assert", "Alg.sublist", "FStar.List.Tot.Base.op_At", "Alg.op", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.l_iff", "Alg.abides", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.prop", "Prims.Nil" ]
[]
true
false
true
false
false
let abides_at_self #a (l: ops) (c: tree0 a) : Lemma (abides (l @ l) c <==> abides l c) [SMTPat (abides (l @ l) c)] =
assert (sublist l (l @ l)); assert (sublist (l @ l) l)
false
Alg.fst
Alg.sublist_at
val 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))]]]
val 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))]]]
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
{ "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": 75, "start_col": 0, "start_line": 68 }
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
{ "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.ops -> l2: Alg.ops -> FStar.Pervasives.Lemma (ensures Alg.sublist l1 (l1 @ l2) /\ Alg.sublist l2 (l1 @ l2)) [SMTPatOr [[SMTPat (Alg.sublist l1 (l1 @ l2))]; [SMTPat (Alg.sublist l2 (l1 @ l2))]]]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.ops", "Alg.op", "Prims.list", "Alg.sublist_at", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.l_and", "Alg.sublist", "FStar.List.Tot.Base.op_At", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat_or", "FStar.Pervasives.smt_pat", "Prims.logical", "Prims.Nil" ]
[ "recursion" ]
false
false
true
false
false
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
false
Alg.fst
Alg.bind
val bind (a b: Type) (#labs1 #labs2: ops) (c: tree a labs1) (f: (x: a -> tree b labs2)) : Tot (tree b (labs1 @ labs2))
val bind (a b: Type) (#labs1 #labs2: ops) (c: tree a labs1) (f: (x: a -> tree b labs2)) : Tot (tree b (labs1 @ labs2))
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 71, "end_line": 159, "start_col": 0, "start_line": 154 }
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
{ "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 -> b: Type -> c: Alg.tree a labs1 -> f: (x: a -> Alg.tree b labs2) -> Alg.tree b (labs1 @ labs2)
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.tree", "Alg.handle_tree", "FStar.List.Tot.Base.op_At", "Alg.op", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.Op" ]
[]
false
false
false
false
false
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)
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.digest
val digest : Hacl.Streaming.Functor.digest_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) () (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
let digest = F.digest (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 93, "end_line": 44, "start_col": 0, "start_line": 43 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code let block_state_t = Common.s Spec.Blake2S Core.M32 let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) /// The incremental hash functions instantiations. Note that we can't write a /// generic one, because the normalization then performed by KaRaMeL explodes. /// All those implementations are for non-keyed hash. inline_for_extraction noextract let alloca = F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " State allocation function when there is no key")] let malloc = F.malloc (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Re-initialization function when there is no key")] let reset = F.reset (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) [@ (Comment " Update function when there is no key; 0 = success, 1 = max length exceeded")] let update = F.update (blake2s_32 0) (G.hide ()) (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Hacl.Streaming.Functor.digest_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) () (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Functor.digest", "Prims.unit", "Hacl.Streaming.Blake2s_32.blake2s_32", "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Streaming.Blake2.Common.empty_key" ]
[]
false
false
false
false
false
let digest =
F.digest (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
false
Alg.fst
Alg.fold_with
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
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'
{ "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": 131, "start_col": 0, "start_line": 124 }
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))
{ "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 labs -> v: (_: a -> b) -> h: (o: Alg.op{FStar.List.Tot.Base.memP o labs} -> _: Alg.op_inp o -> _: (_: Alg.op_out o -> b) -> b) -> b
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.tree", "Alg.op", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Alg.fold_with" ]
[ "recursion" ]
false
false
false
false
false
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'
false
Alg.fst
Alg.subcomp
val subcomp (a: Type) (#labs1 #labs2: ops) (f: tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True))
val subcomp (a: Type) (#labs1 #labs2: ops) (f: tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True))
let subcomp (a:Type) (#labs1 #labs2 : ops) (f : tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) = f
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 5, "end_line": 167, "start_col": 0, "start_line": 161 }
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)
{ "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 -> f: Alg.tree a labs1 -> Prims.Pure (Alg.tree a labs2)
Prims.Pure
[]
[]
[ "Alg.ops", "Alg.tree", "Alg.sublist", "Prims.l_True" ]
[]
false
false
false
false
false
let subcomp (a: Type) (#labs1 #labs2: ops) (f: tree a labs1) : Pure (tree a labs2) (requires (sublist labs1 labs2)) (ensures (fun _ -> True)) =
f
false
Alg.fst
Alg.run
val run (#a: _) (f: (unit -> Alg a [])) : a
val run (#a: _) (f: (unit -> Alg a [])) : a
let run #a (f : unit -> Alg a []) : a = frompure (reify (f ()))
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 63, "end_line": 229, "start_col": 0, "start_line": 229 }
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
{ "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) -> a
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Nil", "Alg.op", "Alg.frompure" ]
[]
false
false
false
false
false
let run #a (f: (unit -> Alg a [])) : a =
frompure (reify (f ()))
false
Alg.fst
Alg.return
val return (a: Type) (x: a) : tree a []
val return (a: Type) (x: a) : tree a []
let return (a:Type) (x:a) : tree a [] = Return x
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 12, "end_line": 152, "start_col": 0, "start_line": 150 }
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
{ "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 -> x: a -> Alg.tree a []
Prims.Tot
[ "total" ]
[]
[ "Alg.Return", "Alg.tree", "Prims.Nil", "Alg.op" ]
[]
false
false
false
true
false
let return (a: Type) (x: a) : tree a [] =
Return x
false
Alg.fst
Alg.memP_at
val memP_at (l1 l2: ops) (l: op) : Lemma (memP l (l1 @ l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1 @ l2))]
val memP_at (l1 l2: ops) (l: op) : Lemma (memP l (l1 @ l2) <==> (memP l l1 \/ memP l l2)) [SMTPat (memP l (l1 @ l2))]
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 30, "end_line": 66, "start_col": 0, "start_line": 61 }
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 *****)
{ "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.ops -> l2: Alg.ops -> l: Alg.op -> FStar.Pervasives.Lemma (ensures FStar.List.Tot.Base.memP l (l1 @ l2) <==> FStar.List.Tot.Base.memP l l1 \/ FStar.List.Tot.Base.memP l l2) [SMTPat (FStar.List.Tot.Base.memP l (l1 @ l2))]
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Alg.ops", "Alg.op", "Prims.list", "Alg.memP_at", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.l_iff", "FStar.List.Tot.Base.memP", "FStar.List.Tot.Base.op_At", "Prims.l_or", "Prims.Cons", "FStar.Pervasives.pattern", "FStar.Pervasives.smt_pat", "Prims.Nil" ]
[ "recursion" ]
false
false
true
false
false
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
false
Pulse.Elaborate.Pure.fst
Pulse.Elaborate.Pure.elab_stt_equiv
val elab_stt_equiv (g: R.env) (c: comp{C_ST? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_ST { u = u ; res = res } = c in mk_stt_comp u (elab_term res) pre post) (elab_comp c)
val elab_stt_equiv (g: R.env) (c: comp{C_ST? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_ST { u = u ; res = res } = c in mk_stt_comp u (elab_term res) pre post) (elab_comp c)
let elab_stt_equiv (g:R.env) (c:comp{C_ST? c}) (pre:R.term) (post:R.term) (eq_pre:RT.equiv g pre (elab_term (comp_pre c))) (eq_post:RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_ST {u;res} = c in mk_stt_comp u (elab_term res) pre post) (elab_comp c) = mk_stt_comp_equiv _ (comp_u c) (elab_term (comp_res c)) _ _ _ _ _ (RT.Rel_refl _ _ _) eq_pre eq_post
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Pure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 48, "end_line": 157, "start_col": 0, "start_line": 142 }
(* Copyright 2023 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 Pulse.Elaborate.Pure module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module RU = Pulse.RuntimeUtils open FStar.List.Tot open Pulse.Syntax.Base open Pulse.Reflection.Util let (let!) (f:option 'a) (g: 'a -> option 'b) : option 'b = match f with | None -> None | Some x -> g x let elab_qual = function | None -> R.Q_Explicit | Some Implicit -> R.Q_Implicit let elab_observability = let open R in function | Neutral -> pack_ln (Tv_FVar (pack_fv neutral_lid)) | Unobservable -> pack_ln (Tv_FVar (pack_fv unobservable_lid)) | Observable -> pack_ln (Tv_FVar (pack_fv observable_lid)) let rec elab_term (top:term) : R.term = let open R in let w t' = RU.set_range t' top.range in match top.t with | Tm_VProp -> w (pack_ln (Tv_FVar (pack_fv vprop_lid))) | Tm_Emp -> w (pack_ln (Tv_FVar (pack_fv emp_lid))) | Tm_Inv p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv inv_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Pure p -> let p = elab_term p in let head = pack_ln (Tv_FVar (pack_fv pure_lid)) in w (pack_ln (Tv_App head (p, Q_Explicit))) | Tm_Star l r -> let l = elab_term l in let r = elab_term r in w (mk_star l r) | Tm_ExistsSL u b body | Tm_ForallSL u b body -> let t = elab_term b.binder_ty in let body = elab_term body in let t = set_range_of t b.binder_ppname.range in if Tm_ExistsSL? top.t then w (mk_exists u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) else w (mk_forall u t (mk_abs_with_name_and_range b.binder_ppname.name b.binder_ppname.range t R.Q_Explicit body)) | Tm_Inames -> w (pack_ln (Tv_FVar (pack_fv inames_lid))) | Tm_EmpInames -> w (emp_inames_tm) | Tm_AddInv i is -> let i = elab_term i in let is = elab_term is in w (add_inv_tm (`_) is i) // Careful on the order flip | Tm_Unknown -> w (pack_ln R.Tv_Unknown) | Tm_FStar t -> w t let rec elab_pat (p:pattern) : Tot R.pattern = let elab_fv (f:fv) : R.fv = R.pack_fv f.fv_name in match p with | Pat_Constant c -> R.Pat_Constant c | Pat_Var v ty -> R.Pat_Var RT.sort_default v | Pat_Cons fv vs -> R.Pat_Cons (elab_fv fv) None (Pulse.Common.map_dec p vs elab_sub_pat) | Pat_Dot_Term None -> R.Pat_Dot_Term None | Pat_Dot_Term (Some t) -> R.Pat_Dot_Term (Some (elab_term t)) and elab_sub_pat (pi : pattern & bool) : R.pattern & bool = let (p, i) = pi in elab_pat p, i let elab_pats (ps:list pattern) : Tot (list R.pattern) = L.map elab_pat ps let elab_st_comp (c:st_comp) : R.universe & R.term & R.term & R.term = let res = elab_term c.res in let pre = elab_term c.pre in let post = elab_term c.post in c.u, res, pre, post let elab_comp (c:comp) : R.term = match c with | C_Tot t -> elab_term t | C_ST c -> let u, res, pre, post = elab_st_comp c in mk_stt_comp u res pre (mk_abs res R.Q_Explicit post) | C_STAtomic inames obs c -> let inames = elab_term inames in let u, res, pre, post = elab_st_comp c in let post = mk_abs res R.Q_Explicit post in mk_stt_atomic_comp (elab_observability obs) u res inames pre post | C_STGhost c -> let u, res, pre, post = elab_st_comp c in mk_stt_ghost_comp u res pre (mk_abs res R.Q_Explicit post)
{ "checked_file": "/", "dependencies": [ "Pulse.Syntax.Base.fsti.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Common.fst.checked", "prims.fst.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Pure.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Base", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
g: FStar.Stubs.Reflection.Types.env -> c: Pulse.Syntax.Base.comp{C_ST? c} -> pre: FStar.Stubs.Reflection.Types.term -> post: FStar.Stubs.Reflection.Types.term -> eq_pre: FStar.Reflection.Typing.equiv g pre (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_pre c)) -> eq_post: FStar.Reflection.Typing.equiv g post (Pulse.Reflection.Util.mk_abs (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_res c) ) FStar.Stubs.Reflection.V2.Data.Q_Explicit (Pulse.Elaborate.Pure.elab_term (Pulse.Syntax.Base.comp_post c))) -> FStar.Reflection.Typing.equiv g (let _ = c in (let Pulse.Syntax.Base.C_ST { u = u46 ; res = res ; pre = _ ; post = _ } = _ in Pulse.Reflection.Util.mk_stt_comp u46 (Pulse.Elaborate.Pure.elab_term res) pre post) <: FStar.Stubs.Reflection.Types.term) (Pulse.Elaborate.Pure.elab_comp c)
Prims.Tot
[ "total" ]
[]
[ "FStar.Stubs.Reflection.Types.env", "Pulse.Syntax.Base.comp", "Prims.b2t", "Pulse.Syntax.Base.uu___is_C_ST", "FStar.Stubs.Reflection.Types.term", "FStar.Reflection.Typing.equiv", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_pre", "Pulse.Reflection.Util.mk_abs", "Pulse.Syntax.Base.comp_res", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Syntax.Base.comp_post", "Pulse.Reflection.Util.mk_stt_comp_equiv", "Pulse.Syntax.Base.comp_u", "FStar.Reflection.Typing.Rel_refl", "FStar.Reflection.Typing.R_Eq", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.vprop", "Pulse.Reflection.Util.mk_stt_comp", "Pulse.Elaborate.Pure.elab_comp" ]
[]
false
false
false
false
false
let elab_stt_equiv (g: R.env) (c: comp{C_ST? c}) (pre post: R.term) (eq_pre: RT.equiv g pre (elab_term (comp_pre c))) (eq_post: RT.equiv g post (mk_abs (elab_term (comp_res c)) R.Q_Explicit (elab_term (comp_post c)))) : RT.equiv g (let C_ST { u = u ; res = res } = c in mk_stt_comp u (elab_term res) pre post) (elab_comp c) =
mk_stt_comp_equiv _ (comp_u c) (elab_term (comp_res c)) _ _ _ _ _ (RT.Rel_refl _ _ _) eq_pre eq_post
false
Pulse.Typing.Metatheory.Base.fsti
Pulse.Typing.Metatheory.Base.veq_weakening
val veq_weakening: g: env -> g': env{disjoint g g'} -> #v1: vprop -> #v2: vprop -> vprop_equiv (push_env g g') v1 v2 -> g1: env{pairwise_disjoint g g1 g'} -> vprop_equiv (push_env (push_env g g1) g') v1 v2
val veq_weakening: g: env -> g': env{disjoint g g'} -> #v1: vprop -> #v2: vprop -> vprop_equiv (push_env g g') v1 v2 -> g1: env{pairwise_disjoint g g1 g'} -> vprop_equiv (push_env (push_env g g1) g') v1 v2
let veq_weakening (g:env) (g':env { disjoint g g' }) (#v1 #v2:vprop) (_:vprop_equiv (push_env g g') v1 v2) (g1:env { pairwise_disjoint g g1 g' }) : vprop_equiv (push_env (push_env g g1) g') v1 v2 = RU.magic ()
{ "file_name": "lib/steel/pulse/Pulse.Typing.Metatheory.Base.fsti", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 65, "end_line": 111, "start_col": 0, "start_line": 107 }
(* Copyright 2023 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 Pulse.Typing.Metatheory.Base open Pulse.Syntax open Pulse.Syntax.Naming open Pulse.Typing module RU = Pulse.RuntimeUtils module T = FStar.Tactics.V2 val admit_comp_typing (g:env) (c:comp_st) : comp_typing_u g c module RT = FStar.Reflection.Typing let rt_equiv_typing (#g:_) (#t0 #t1:_) (d:RT.equiv g t0 t1) (#k:_) (d1:Ghost.erased (RT.tot_typing g t0 k)) : Ghost.erased (RT.tot_typing g t1 k) = admit() val st_typing_correctness_ctot (#g:env) (#t:st_term) (#c:comp{C_Tot? c}) (_:st_typing g t c) : (u:Ghost.erased universe & universe_of g (comp_res c) u) let inames_of_comp_st (c:comp_st) = match c with | C_STAtomic _ _ _ -> comp_inames c | _ -> tm_emp_inames let iname_typing (g:env) (c:comp_st) = tot_typing g (inames_of_comp_st c) tm_inames val st_typing_correctness (#g:env) (#t:st_term) (#c:comp_st) (d:st_typing g t c) : comp_typing_u g c val comp_typing_inversion (#g:env) (#c:comp_st) (ct:comp_typing_u g c) : st_comp_typing g (st_comp_of_comp c) & iname_typing g c val st_comp_typing_inversion_cofinite (#g:env) (#st:_) (ct:st_comp_typing g st) : (universe_of g st.res st.u & tot_typing g st.pre tm_vprop & (x:var{fresh_wrt x g (freevars st.post)} -> //this part is tricky, to get the quantification on x tot_typing (push_binding g x ppname_default st.res) (open_term st.post x) tm_vprop)) val st_comp_typing_inversion (#g:env) (#st:_) (ct:st_comp_typing g st) : (universe_of g st.res st.u & tot_typing g st.pre tm_vprop & x:var{fresh_wrt x g (freevars st.post)} & tot_typing (push_binding g x ppname_default st.res) (open_term st.post x) tm_vprop) val tm_exists_inversion (#g:env) (#u:universe) (#ty:term) (#p:term) (_:tot_typing g (tm_exists_sl u (as_binder ty) p) tm_vprop) (x:var { fresh_wrt x g (freevars p) } ) : universe_of g ty u & tot_typing (push_binding g x ppname_default ty) p tm_vprop val pure_typing_inversion (#g:env) (#p:term) (_:tot_typing g (tm_pure p) tm_vprop) : tot_typing g p (tm_fstar FStar.Reflection.Typing.tm_prop Range.range_0) module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module C = FStar.Stubs.TypeChecker.Core open FStar.Ghost val typing_correctness (#g:R.env) (#t:R.term) (#ty:R.typ) (#eff:_) (_:erased (RT.typing g t (eff, ty))) : erased (u:R.universe & RT.typing g ty (C.E_Total, RT.tm_type u)) let renaming x y = [NT x (tm_var {nm_index=y; nm_ppname=ppname_default})] val tot_typing_renaming1 (g:env) (x:var {None? (lookup g x)}) (tx e ty:term) (_:tot_typing (push_binding g x ppname_default tx) e ty) (y:var { None? (lookup g y) /\ x <> y }) : tot_typing (push_binding g y ppname_default tx) (subst_term e (renaming x y)) (subst_term ty (renaming x y)) val tot_typing_weakening (g:env) (g':env { disjoint g g' }) (t:term) (ty:typ) (_:tot_typing (push_env g g') t ty) (g1:env { pairwise_disjoint g g1 g' }) : tot_typing (push_env (push_env g g1) g') t ty val st_typing_weakening (g:env) (g':env { disjoint g g' }) (t:st_term) (c:comp) (_:st_typing (push_env g g') t c) (g1:env { pairwise_disjoint g g1 g' }) : st_typing (push_env (push_env g g1) g') t c
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.Naming.fsti.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Stubs.TypeChecker.Core.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Pulse.Typing.Metatheory.Base.fsti" }
[ { "abbrev": false, "full_module": "FStar.Ghost", "short_module": null }, { "abbrev": true, "full_module": "FStar.Stubs.TypeChecker.Core", "short_module": "C" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Naming", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax.Naming", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing.Metatheory", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing.Metatheory", "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
g: Pulse.Typing.Env.env -> g': Pulse.Typing.Env.env{Pulse.Typing.Env.disjoint g g'} -> _: Pulse.Typing.vprop_equiv (Pulse.Typing.Env.push_env g g') v1 v2 -> g1: Pulse.Typing.Env.env{Pulse.Typing.Env.pairwise_disjoint g g1 g'} -> Pulse.Typing.vprop_equiv (Pulse.Typing.Env.push_env (Pulse.Typing.Env.push_env g g1) g') v1 v2
Prims.Tot
[ "total" ]
[]
[ "Pulse.Typing.Env.env", "Pulse.Typing.Env.disjoint", "Pulse.Syntax.Base.vprop", "Pulse.Typing.vprop_equiv", "Pulse.Typing.Env.push_env", "Pulse.Typing.Env.pairwise_disjoint", "Pulse.RuntimeUtils.magic" ]
[]
false
false
false
false
false
let veq_weakening (g: env) (g': env{disjoint g g'}) (#v1: vprop) (#v2: vprop) (_: vprop_equiv (push_env g g') v1 v2) (g1: env{pairwise_disjoint g g1 g'}) : vprop_equiv (push_env (push_env g g1) g') v1 v2 =
RU.magic ()
false
Alg.fst
Alg.handler_op
val handler_op : o: Alg.op -> b: Type -> labs: Alg.ops -> Type
let handler_op (o:op) (b:Type) (labs:ops) = op_inp o -> (op_out o -> Alg b labs) -> Alg b labs
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 94, "end_line": 303, "start_col": 0, "start_line": 303 }
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 *****)
{ "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 -> b: Type -> labs: Alg.ops -> Type
Prims.Tot
[ "total" ]
[]
[ "Alg.op", "Alg.ops", "Alg.op_inp", "Alg.op_out" ]
[]
false
false
false
true
true
let handler_op (o: op) (b: Type) (labs: ops) =
op_inp o -> (op_out o -> Alg b labs) -> Alg b labs
false
Alg.fst
Alg.lift_pure_alg
val lift_pure_alg (a: Type) (wp: pure_wp a) (f: (unit -> PURE a wp)) : Pure (tree a []) (requires (wp (fun _ -> True))) (ensures (fun _ -> True))
val 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 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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 11, "end_line": 194, "start_col": 0, "start_line": 186 }
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} }
{ "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 -> wp: Prims.pure_wp a -> f: (_: Prims.unit -> Prims.PURE a) -> Prims.Pure (Alg.tree a [])
Prims.Pure
[]
[]
[ "Prims.pure_wp", "Prims.unit", "Alg.Return", "FStar.Monotonic.Pure.elim_pure", "Prims.l_True", "Alg.tree", "Prims.Nil", "Alg.op" ]
[]
false
false
false
false
false
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
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.serialize_der_length_weak_unfold
val serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` (Seq.create 1 (U8.uint_to_t y))) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` (E.n_to_be len y)))
val serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` (Seq.create 1 (U8.uint_to_t y))) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` (E.n_to_be len y)))
let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; ()
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 4, "end_line": 689, "start_col": 0, "start_line": 577 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": 6, "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": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 64, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
y: LowParse.Spec.DER.der_length_t -> FStar.Pervasives.Lemma (ensures (let res = LowParse.Spec.Base.serialize LowParse.Spec.DER.serialize_der_length_weak y in let x = LowParse.Spec.DER.tag_of_der_length y in let s1 = FStar.Seq.Base.create 1 x in (match FStar.UInt8.lt x 128uy with | true -> FStar.Seq.Base.equal res s1 | _ -> (match x = 129uy with | true -> y <= 255 /\ FStar.Seq.Base.equal res (FStar.Seq.Base.append s1 (FStar.Seq.Base.create 1 (FStar.UInt8.uint_to_t y))) | _ -> let len = LowParse.Spec.DER.log256 y in FStar.Seq.Base.equal res (FStar.Seq.Base.append s1 (FStar.Endianness.n_to_be len y)) ) <: Type0) <: Type0))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.DER.der_length_t", "Prims.unit", "Prims.op_LessThan", "Prims.bool", "Prims.op_BarBar", "Prims.op_Equality", "FStar.UInt8.t", "FStar.UInt8.__uint_to_t", "LowParse.Spec.DER.tag_of_der_length_invalid", "LowParse.Spec.Int.serialize_u8_spec", "FStar.UInt8.uint_to_t", "LowParse.Spec.Combinators.serialize_synth_eq'", "LowParse.Spec.Combinators.parse_filter_kind", "LowParse.Spec.Int.parse_u8_kind", "LowParse.Spec.Combinators.parse_filter_refine", "Prims.op_GreaterThanOrEqual", "FStar.UInt8.v", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.DER.tag_of_der_length", "LowParse.Spec.Combinators.parse_filter", "LowParse.Spec.Int.parse_u8", "LowParse.Spec.DER.synth_der_length_129", "LowParse.Spec.Combinators.serialize_filter", "LowParse.Spec.Int.serialize_u8", "LowParse.Spec.DER.synth_der_length_129_recip", "LowParse.Spec.Combinators.synth_inverse_intro'", "Prims.b2t", "LowParse.Spec.DER.tag_of_der_length_eq_129_eta", "LowParse.Spec.Base.serialize", "LowParse.Bytes.bytes", "LowParse.Spec.Combinators.parse_synth", "LowParse.Spec.Combinators.serialize_synth", "Prims._assert", "Prims.eq2", "Prims.int", "Prims.l_or", "Prims.l_and", "Prims.op_LessThanOrEqual", "LowParse.Spec.DER.der_length_max", "FStar.UInt.size", "FStar.UInt8.n", "LowParse.Spec.DER.tag_of_der_length_eq_129", "LowParse.Math.pow2_lt_recip", "FStar.Mul.op_Star", "Prims.op_Subtraction", "LowParse.Spec.DER.log256", "LowParse.Spec.Combinators.serialize_synth_eq", "LowParse.Spec.Base.total_constant_size_parser_kind", "FStar.Seq.Properties.lseq", "LowParse.Bytes.byte", "LowParse.Spec.DER.lint", "LowParse.Spec.SeqBytes.Base.parse_seq_flbytes", "LowParse.Spec.DER.synth_be_int", "LowParse.Spec.SeqBytes.Base.serialize_seq_flbytes", "LowParse.Spec.DER.synth_be_int_recip", "LowParse.Spec.DER.synth_der_length_greater_recip", "Prims.pow2", "LowParse.Spec.DER.synth_der_length_greater", "LowParse.Spec.DER.serialize_der_length_payload_greater", "LowParse.Spec.DER.parse_der_length_payload_kind", "LowParse.Spec.DER.parse_der_length_payload", "LowParse.Spec.DER.serialize_der_length_payload", "LowParse.Spec.DER.synth_be_int_injective", "Prims.nat", "FStar.Pervasives.assert_norm", "Prims.l_True", "Prims.squash", "FStar.UInt8.lt", "FStar.Seq.Base.equal", "FStar.Seq.Base.append", "FStar.Seq.Base.create", "FStar.Endianness.n_to_be", "Prims.op_GreaterThan", "Prims.op_Multiply", "FStar.Seq.Base.seq", "LowParse.Spec.DER.parse_der_length_weak_kind", "LowParse.Spec.DER.parse_der_length_weak", "LowParse.Spec.DER.serialize_der_length_weak", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
false
false
true
false
false
let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` (Seq.create 1 (U8.uint_to_t y))) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` (E.n_to_be len y))) =
let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let x':der_length_t = U8.v x in if x' < 128 then () else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then (tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize (serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) (); serialize_u8_spec (U8.uint_to_t y); ()) else (let len:nat = U8.v x - 128 in synth_be_int_injective len; assert (serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) ()) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (FStar.Tactics.Effect.synth_by_tactic (fun _ -> (FStar.Tactics.trefl ()))) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) ()) (synth_der_length_greater_recip x len y)) (); serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); ()); ()
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.parse_bounded_der_length32_unfold
val parse_bounded_der_length32_unfold (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (input: bytes) : Lemma (let res = parse (parse_bounded_der_length32 min max) input in match parse parse_u8 input with | None -> res == None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in len <= 4 /\ ( match parse (parse_der_length_payload32 x) input' with | Some (y, consumed_y) -> if min <= U32.v y && U32.v y <= max then res == Some (y, consumed_x + consumed_y) else res == None | None -> res == None ) else res == None )
val parse_bounded_der_length32_unfold (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (input: bytes) : Lemma (let res = parse (parse_bounded_der_length32 min max) input in match parse parse_u8 input with | None -> res == None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in len <= 4 /\ ( match parse (parse_der_length_payload32 x) input' with | Some (y, consumed_y) -> if min <= U32.v y && U32.v y <= max then res == Some (y, consumed_x + consumed_y) else res == None | None -> res == None ) else res == None )
let parse_bounded_der_length32_unfold min max input = parse_synth_eq (parse_bounded_der_length min max) (synth_bounded_der_length32 min max) input; parse_bounded_der_length_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in assert_norm (4294967296 <= der_length_max); der_length_payload_size_le max 4294967295; assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); log256_unique 4294967295 4; parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input' ; match parse (parse_der_length_payload x) input' with | None -> () | Some (y, _) -> if y >= 128 then begin assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end else ()
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 12, "end_line": 962, "start_col": 0, "start_line": 936 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64" let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; () #pop-options let serialize_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length_weak min max)) = serialize_synth _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () let serialize_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length min max)) = Classical.forall_intro (parse_bounded_der_length_eq min max); serialize_ext _ (serialize_bounded_der_length_weak min max) (parse_bounded_der_length min max) let serialize_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (y: bounded_int min max) : Lemma (let res = serialize (serialize_bounded_der_length min max) y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = serialize_synth_eq _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () y; serialize_der_length_weak_unfold y (* 32-bit spec *) module U32 = FStar.UInt32 let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures ( tag_of_der_length x == ( if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy ))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4 let synth_der_length_payload32 (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x) = let _ = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end in U32.uint_to_t y let synth_der_length_payload32_injective (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))] = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in synth_injective_intro' (synth_der_length_payload32 x) (fun (y1 y2: refine_with_tag tag_of_der_length x) -> if y1 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y1 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y1) == 128 + log256 y1) end; if y2 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y2 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y2) == 128 + log256 y2) end ) let parse_der_length_payload32 x : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length32 x)) = parse_der_length_payload x `parse_synth` synth_der_length_payload32 x let be_int_of_bounded_integer (len: integer_size) (x: nat { x < pow2 (8 * len) } ) : GTot (bounded_integer len) = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); U32.uint_to_t x let be_int_of_bounded_integer_injective (len: integer_size) : Lemma (synth_injective (be_int_of_bounded_integer len)) [SMTPat (synth_injective (be_int_of_bounded_integer len))] // FIXME: WHY WHY WHY does this pattern NEVER trigger? = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296) #push-options "--max_ifuel 4 --z3rlimit 16" let parse_seq_flbytes_synth_be_int_eq (len: integer_size) (input: bytes) : Lemma ( let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse ( parse_synth #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len) ) (be_int_of_bounded_integer len) ) input == parse (parse_bounded_integer len) input) = let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_synth_eq (parse_seq_flbytes len `parse_synth` synth_be_int len) (be_int_of_bounded_integer len) input; parse_synth_eq (parse_seq_flbytes len) (synth_be_int len) input; parser_kind_prop_equiv (parse_bounded_integer_kind len) (parse_bounded_integer len); parse_bounded_integer_spec len input let parse_der_length_payload32_unfold x input = parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 (8 * 1) == 256); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in begin match parse (parse_der_length_payload x) input with | None -> () | Some (y, _) -> if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end end; parse_der_length_payload_unfold x input; if U8.v x < 128 then () // tag_of_der_length (U8.v x) == x /\ y == Some (Cast.uint8_to_uint32 x, 0) else if x = 128uy || x = 255uy then () // y == None else if x = 129uy then () else begin let len : nat = U8.v x - 128 in assert (2 <= len /\ len <= 4); let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_seq_flbytes_synth_be_int_eq len input; integer_size_values len; parse_synth_eq #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len)) (be_int_of_bounded_integer len) input end #pop-options let log256_eq x = log256_unique x (log256' x) let synth_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) (x: bounded_int min max) : Tot (bounded_int32 min max) = U32.uint_to_t x let parse_bounded_der_length32 (min: der_length_t) (max: der_length_t { min <= max /\ max < 4294967296 }) : Tot (parser (parse_bounded_der_length32_kind min max) (bounded_int32 min max)) = parse_bounded_der_length min max `parse_synth` synth_bounded_der_length32 min max
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": true, "z3cliopt": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
min: LowParse.Spec.DER.der_length_t -> max: LowParse.Spec.DER.der_length_t{min <= max /\ max < 4294967296} -> input: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (ensures (let res = LowParse.Spec.Base.parse (LowParse.Spec.DER.parse_bounded_der_length32 min max) input in (match LowParse.Spec.Base.parse LowParse.Spec.Int.parse_u8 input with | FStar.Pervasives.Native.None #_ -> res == FStar.Pervasives.Native.None | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ x consumed_x) -> let len = LowParse.Spec.DER.der_length_payload_size_of_tag x in (match LowParse.Spec.DER.der_length_payload_size min <= len && len <= LowParse.Spec.DER.der_length_payload_size max with | true -> let input' = FStar.Seq.Base.slice input consumed_x (FStar.Seq.Base.length input) in len <= 4 /\ (match LowParse.Spec.Base.parse (LowParse.Spec.DER.parse_der_length_payload32 x) input' with | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ y consumed_y) -> (match min <= FStar.UInt32.v y && FStar.UInt32.v y <= max with | true -> res == FStar.Pervasives.Native.Some (y, consumed_x + consumed_y) | _ -> res == FStar.Pervasives.Native.None) <: Prims.logical | FStar.Pervasives.Native.None #_ -> res == FStar.Pervasives.Native.None) | _ -> res == FStar.Pervasives.Native.None) <: Type0) <: Type0))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "LowParse.Spec.DER.der_length_t", "Prims.l_and", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.op_LessThan", "LowParse.Bytes.bytes", "LowParse.Spec.Base.parse", "FStar.UInt8.t", "LowParse.Spec.Int.parse_u8", "LowParse.Spec.Base.consumed_length", "Prims.op_AmpAmp", "LowParse.Spec.DER.der_length_payload_size", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.DER.tag_of_der_length", "LowParse.Spec.DER.parse_der_length_payload", "Prims.op_GreaterThanOrEqual", "Prims._assert", "Prims.eq2", "Prims.int", "FStar.UInt8.v", "Prims.op_Addition", "LowParse.Spec.DER.log256", "Prims.unit", "LowParse.Math.pow2_lt_recip", "FStar.Mul.op_Star", "Prims.op_Subtraction", "FStar.Pervasives.assert_norm", "LowParse.Spec.DER.der_length_max", "Prims.pow2", "Prims.bool", "LowParse.Spec.Combinators.parse_synth_eq", "LowParse.Spec.DER.parse_der_length_payload_kind", "FStar.UInt32.t", "LowParse.Spec.DER.tag_of_der_length32", "LowParse.Spec.DER.synth_der_length_payload32", "LowParse.Spec.DER.log256_unique", "LowParse.Spec.DER.der_length_payload_size_le", "FStar.Seq.Base.seq", "LowParse.Bytes.byte", "FStar.Seq.Base.slice", "FStar.Seq.Base.length", "Prims.nat", "LowParse.Spec.DER.der_length_payload_size_of_tag", "LowParse.Spec.DER.parse_bounded_der_length_unfold", "LowParse.Spec.DER.parse_bounded_der_length_kind", "LowParse.Spec.DER.bounded_int", "LowParse.Spec.BoundedInt.bounded_int32", "LowParse.Spec.DER.parse_bounded_der_length", "LowParse.Spec.DER.synth_bounded_der_length32" ]
[]
false
false
true
false
false
let parse_bounded_der_length32_unfold min max input =
parse_synth_eq (parse_bounded_der_length min max) (synth_bounded_der_length32 min max) input; parse_bounded_der_length_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in assert_norm (4294967296 <= der_length_max); der_length_payload_size_le max 4294967295; assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); log256_unique 4294967295 4; parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input'; match parse (parse_der_length_payload x) input' with | None -> () | Some (y, _) -> if y >= 128 then (assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y))
false
EverCrypt.DRBG.fst
EverCrypt.DRBG.mk_instantiate
val mk_instantiate: #a:supported_alg -> EverCrypt.HMAC.compute_st a -> instantiate_st a
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
{ "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": 124, "start_col": 0, "start_line": 96 }
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
{ "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.instantiate_st a
Prims.Tot
[ "total" ]
[]
[ "Hacl.HMAC_DRBG.supported_alg", "EverCrypt.HMAC.compute_st", "EverCrypt.DRBG.state", "LowStar.Buffer.buffer", "Lib.IntTypes.uint8", "Lib.IntTypes.size_t", "Lib.IntTypes.op_Greater_Dot", "Lib.IntTypes.U32", "Hacl.HMAC_DRBG.max_personalization_string_length", "Prims.bool", "Prims.unit", "FStar.HyperStack.ST.pop_frame", "Prims.op_Negation", "Hacl.HMAC_DRBG.mk_instantiate", "EverCrypt.DRBG.p", "EverCrypt.DRBG.state_s", "LowStar.BufferOps.op_Bang_Star", "LowStar.Buffer.trivial_preorder", "Spec.HMAC_DRBG.hmac_input_bound", "LowStar.Monotonic.Buffer.mbuffer", "Lib.IntTypes.int_t", "Lib.IntTypes.U8", "Lib.IntTypes.SEC", "LowStar.Buffer.sub", "FStar.Ghost.hide", "FStar.UInt32.t", "FStar.UInt32.__uint_to_t", "Lib.RandomBuffer.System.randombytes", "Prims.l_and", "Prims.eq2", "Prims.nat", "LowStar.Monotonic.Buffer.length", "FStar.UInt32.v", "Prims.b2t", "LowStar.Monotonic.Buffer.g_is_null", "LowStar.Buffer.alloca", "Lib.IntTypes.u8", "FStar.Pervasives.assert_norm", "Lib.IntTypes.range", "Lib.IntTypes.v", "Lib.IntTypes.PUB", "FStar.HyperStack.ST.push_frame", "Lib.IntTypes.op_Plus_Bang", "Lib.IntTypes.op_Slash_Dot", "Hacl.HMAC_DRBG.min_length", "Prims.int", "Spec.HMAC_DRBG.min_length" ]
[]
false
false
false
false
false
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 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 in pop_frame (); result
false
Alg.fst
Alg.geneff
val geneff (o: op) (i: op_inp o) : Alg (op_out o) [o]
val geneff (o: op) (i: op_inp o) : Alg (op_out o) [o]
let geneff (o : op) (i : op_inp o) : Alg (op_out o) [o] = Alg?.reflect (Op o i Return)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 32, "end_line": 201, "start_col": 0, "start_line": 199 }
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
{ "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 -> i: Alg.op_inp o -> Alg.Alg (Alg.op_out o)
Alg.Alg
[]
[]
[ "Alg.op", "Alg.op_inp", "Alg.Op", "Alg.op_out", "Alg.Return", "Prims.Cons", "Prims.Nil" ]
[]
false
true
false
false
false
let geneff (o: op) (i: op_inp o) : Alg (op_out o) [o] =
Alg?.reflect (Op o i Return)
false
Hacl.Streaming.Blake2s_32.fst
Hacl.Streaming.Blake2s_32.alloca
val alloca : Hacl.Streaming.Functor.alloca_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) () (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
let alloca = F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
{ "file_name": "code/streaming/Hacl.Streaming.Blake2s_32.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 93, "end_line": 28, "start_col": 0, "start_line": 27 }
module Hacl.Streaming.Blake2s_32 module Blake2s32 = Hacl.Blake2s_32 module Common = Hacl.Streaming.Blake2.Common module Core = Hacl.Impl.Blake2.Core module F = Hacl.Streaming.Functor module G = FStar.Ghost module Impl = Hacl.Impl.Blake2.Generic module Spec = Spec.Blake2 inline_for_extraction noextract let blake2s_32 kk = Common.blake2 Spec.Blake2S Core.M32 kk Blake2s32.init Blake2s32.update_multi Blake2s32.update_last Blake2s32.finish /// Type abbreviations - makes Karamel use pretty names in the generated code let block_state_t = Common.s Spec.Blake2S Core.M32 let state_t = F.state_s (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S) /// The incremental hash functions instantiations. Note that we can't write a /// generic one, because the normalization then performed by KaRaMeL explodes. /// All those implementations are for non-keyed hash.
{ "checked_file": "/", "dependencies": [ "Spec.Blake2.fst.checked", "prims.fst.checked", "Hacl.Streaming.Functor.fsti.checked", "Hacl.Streaming.Blake2.Common.fst.checked", "Hacl.Impl.Blake2.Generic.fst.checked", "Hacl.Impl.Blake2.Core.fsti.checked", "Hacl.Blake2s_32.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Hacl.Streaming.Blake2s_32.fst" }
[ { "abbrev": true, "full_module": "Spec.Blake2", "short_module": "Spec" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Generic", "short_module": "Impl" }, { "abbrev": true, "full_module": "FStar.Ghost", "short_module": "G" }, { "abbrev": true, "full_module": "Hacl.Streaming.Functor", "short_module": "F" }, { "abbrev": true, "full_module": "Hacl.Impl.Blake2.Core", "short_module": "Core" }, { "abbrev": true, "full_module": "Hacl.Streaming.Blake2.Common", "short_module": "Common" }, { "abbrev": true, "full_module": "Hacl.Blake2s_32", "short_module": "Blake2s32" }, { "abbrev": false, "full_module": "Hacl.Streaming", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Streaming", "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Hacl.Streaming.Functor.alloca_st (Hacl.Streaming.Blake2s_32.blake2s_32 0) () (Hacl.Streaming.Blake2.Common.s Spec.Blake2.Definitions.Blake2S Hacl.Impl.Blake2.Core.M32) (Hacl.Streaming.Blake2.Common.empty_key Spec.Blake2.Definitions.Blake2S)
Prims.Tot
[ "total" ]
[]
[ "Hacl.Streaming.Functor.alloca", "Prims.unit", "Hacl.Streaming.Blake2s_32.blake2s_32", "Hacl.Streaming.Blake2.Common.s", "Spec.Blake2.Definitions.Blake2S", "Hacl.Impl.Blake2.Core.M32", "Hacl.Streaming.Blake2.Common.empty_key" ]
[]
false
false
false
false
false
let alloca =
F.alloca (blake2s_32 0) () (Common.s Spec.Blake2S Core.M32) (Common.empty_key Spec.Blake2S)
false
Alg.fst
Alg.put
val put: state -> Alg unit [Write]
val put: state -> Alg unit [Write]
let put : state -> Alg unit [Write] = geneff Write
{ "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": 204, "start_col": 0, "start_line": 204 }
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)
{ "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.state -> Alg.Alg Prims.unit
Alg.Alg
[]
[]
[ "Alg.geneff", "Alg.Write" ]
[]
false
true
false
false
false
let put: state -> Alg unit [Write] =
geneff Write
false
Alg.fst
Alg.listmap
val listmap (#a #b #labs: _) (f: (a -> Alg b labs)) (l: list a) : Alg (list b) labs
val listmap (#a #b #labs: _) (f: (a -> Alg b labs)) (l: list a) : Alg (list b) labs
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 44, "end_line": 217, "start_col": 0, "start_line": 213 }
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)
{ "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: (_: a -> Alg.Alg b) -> l: Prims.list a -> Alg.Alg (Prims.list b)
Alg.Alg
[]
[]
[ "Alg.ops", "Prims.list", "Prims.Nil", "Prims.Cons", "Alg.listmap" ]
[ "recursion" ]
false
true
false
false
false
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
false
LowParse.Spec.DER.fst
LowParse.Spec.DER.parse_der_length_payload32_unfold
val parse_der_length_payload32_unfold (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload32 x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (Cast.uint8_to_uint32 x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (Cast.uint8_to_uint32 z, consumed) else let len : nat = U8.v x - 128 in 2 <= len /\ len <= 4 /\ ( let res : option (bounded_integer len & consumed_length input) = parse (parse_bounded_integer len) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if U32.v z >= pow2 (8 * (len - 1)) then U32.v z <= der_length_max /\ tag_of_der_length32 z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length32 x), consumed) else y == None ))))
val parse_der_length_payload32_unfold (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload32 x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (Cast.uint8_to_uint32 x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (Cast.uint8_to_uint32 z, consumed) else let len : nat = U8.v x - 128 in 2 <= len /\ len <= 4 /\ ( let res : option (bounded_integer len & consumed_length input) = parse (parse_bounded_integer len) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if U32.v z >= pow2 (8 * (len - 1)) then U32.v z <= der_length_max /\ tag_of_der_length32 z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length32 x), consumed) else y == None ))))
let parse_der_length_payload32_unfold x input = parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 (8 * 1) == 256); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in begin match parse (parse_der_length_payload x) input with | None -> () | Some (y, _) -> if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end end; parse_der_length_payload_unfold x input; if U8.v x < 128 then () // tag_of_der_length (U8.v x) == x /\ y == Some (Cast.uint8_to_uint32 x, 0) else if x = 128uy || x = 255uy then () // y == None else if x = 129uy then () else begin let len : nat = U8.v x - 128 in assert (2 <= len /\ len <= 4); let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_seq_flbytes_synth_be_int_eq len input; integer_size_values len; parse_synth_eq #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len)) (be_int_of_bounded_integer len) input end
{ "file_name": "src/lowparse/LowParse.Spec.DER.fst", "git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa", "git_url": "https://github.com/project-everest/everparse.git", "project_name": "everparse" }
{ "end_col": 7, "end_line": 914, "start_col": 0, "start_line": 876 }
module LowParse.Spec.DER open LowParse.Spec.Combinators open LowParse.Spec.SeqBytes.Base // include LowParse.Spec.VLData // for in_bounds open FStar.Mul module U8 = FStar.UInt8 module UInt = FStar.UInt module Math = LowParse.Math module E = FStar.Endianness module Seq = FStar.Seq #reset-options "--z3cliopt smt.arith.nl=false --max_fuel 0 --max_ifuel 0" // let _ : unit = _ by (FStar.Tactics.(print (string_of_int der_length_max); exact (`()))) let der_length_max_eq = assert_norm (der_length_max == pow2 (8 * 126) - 1) let rec log256 (x: nat { x > 0 }) : Tot (y: nat { y > 0 /\ pow2 (8 * (y - 1)) <= x /\ x < pow2 (8 * y)}) = assert_norm (pow2 8 == 256); if x < 256 then 1 else begin let n = log256 (x / 256) in Math.pow2_plus (8 * (n - 1)) 8; Math.pow2_plus (8 * n) 8; n + 1 end let log256_unique x y = Math.pow2_lt_recip (8 * (y - 1)) (8 * log256 x); Math.pow2_lt_recip (8 * (log256 x - 1)) (8 * y) let log256_le x1 x2 = Math.pow2_lt_recip (8 * (log256 x1 - 1)) (8 * log256 x2) let der_length_payload_size_le x1 x2 = if x1 < 128 || x2 < 128 then () else let len_len2 = log256 x2 in let len_len1 = log256 x1 in log256_le x1 x2; assert_norm (pow2 7 == 128); assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len2 - 1)) (8 * 126) let synth_be_int (len: nat) (b: Seq.lseq byte len) : Tot (lint len) = E.lemma_be_to_n_is_bounded b; E.be_to_n b let synth_be_int_injective (len: nat) : Lemma (synth_injective (synth_be_int len)) [SMTPat (synth_injective (synth_be_int len))] = synth_injective_intro' (synth_be_int len) (fun (x x' : Seq.lseq byte len) -> E.be_to_n_inj x x' ) let synth_der_length_129 (x: U8.t { x == 129uy } ) (y: U8.t { U8.v y >= 128 } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); log256_unique (U8.v y) 1; U8.v y let synth_der_length_greater (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x - 128 } ) (y: lint len { y >= pow2 (8 * (len - 1)) } ) : Tot (refine_with_tag tag_of_der_length x) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len; y let parse_der_length_payload (x: U8.t) : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin weaken (parse_der_length_payload_kind x) (parse_ret (x' <: refine_with_tag tag_of_der_length x)) end else if x = 128uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // DER representation of 0 is covered by the x<128 case else if x = 255uy then fail_parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) // forbidden in BER already else if x = 129uy then weaken (parse_der_length_payload_kind x) ((parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) `parse_synth` synth_der_length_129 x) else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? weaken (parse_der_length_payload_kind x) (((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) `parse_synth` synth_der_length_greater x len) end let parse_der_length_payload_unfold (x: U8.t) (input: bytes) : Lemma ( let y = parse (parse_der_length_payload x) input in (256 < der_length_max) /\ ( if U8.v x < 128 then tag_of_der_length (U8.v x) == x /\ y == Some (U8.v x, 0) else if x = 128uy || x = 255uy then y == None else if x = 129uy then match parse parse_u8 input with | None -> y == None | Some (z, consumed) -> if U8.v z < 128 then y == None else tag_of_der_length (U8.v z) == x /\ y == Some (U8.v z, consumed) else let len : nat = U8.v x - 128 in synth_injective (synth_be_int len) /\ ( let res : option (lint len & consumed_length input) = parse (parse_synth (parse_seq_flbytes len) (synth_be_int len)) input in match res with | None -> y == None | Some (z, consumed) -> len > 0 /\ ( if z >= pow2 (8 * (len - 1)) then z <= der_length_max /\ tag_of_der_length z == x /\ y == Some ((z <: refine_with_tag tag_of_der_length x), consumed) else y == None )))) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy then () else if x = 255uy then () else if x = 129uy then begin parse_synth_eq (parse_u8 `parse_filter` (fun y -> U8.v y >= 128)) (synth_der_length_129 x) input; parse_filter_eq parse_u8 (fun y -> U8.v y >= 128) input; match parse parse_u8 input with | None -> () | Some (y, _) -> if U8.v y >= 128 then begin log256_unique (U8.v y) 1 end else () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? parse_synth_eq ((parse_seq_flbytes len `parse_synth` (synth_be_int len)) `parse_filter` (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) (synth_der_length_greater x len) input; parse_filter_eq (parse_seq_flbytes len `parse_synth` (synth_be_int len)) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) input; assert (len > 1); let res : option (lint len & consumed_length input) = parse (parse_seq_flbytes len `parse_synth` (synth_be_int len)) input in match res with | None -> () | Some (y, _) -> if y >= pow2 (8 * (len - 1)) then begin let (y: lint len { y >= pow2 (8 * (len - 1)) } ) = y in Math.pow2_le_compat (8 * 126) (8 * len); Math.pow2_le_compat (8 * (len - 1)) 7; log256_unique y len end else () end inline_for_extraction let parse_der_length_payload_kind_weak : parser_kind = strong_parser_kind 0 126 None inline_for_extraction let parse_der_length_weak_kind : parser_kind = and_then_kind parse_u8_kind parse_der_length_payload_kind_weak let parse_der_length_weak : parser parse_der_length_weak_kind der_length_t = parse_tagged_union parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) [@@(noextract_to "krml")] let parse_bounded_der_length_payload_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = [@inline_let] let _ = der_length_payload_size_le min max in strong_parser_kind (der_length_payload_size min) (der_length_payload_size max) None let bounded_int (min: der_length_t) (max: der_length_t { min <= max }) : Tot Type = (x: int { min <= x /\ x <= max }) let parse_bounded_der_length_tag_cond (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t) : Tot bool = let len = der_length_payload_size_of_tag x in der_length_payload_size min <= len && len <= der_length_payload_size max inline_for_extraction // for parser_kind let tag_of_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) (x: bounded_int min max) : Tot (y: U8.t { parse_bounded_der_length_tag_cond min max y == true } ) = [@inline_let] let _ = der_length_payload_size_le min x; der_length_payload_size_le x max in tag_of_der_length x let parse_bounded_der_length_payload (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) : Tot (parser (parse_bounded_der_length_payload_kind min max) (refine_with_tag (tag_of_bounded_der_length min max) x)) = weaken (parse_bounded_der_length_payload_kind min max) (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) `parse_synth` (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x))) [@@(noextract_to "krml")] let parse_bounded_der_length_kind (min: der_length_t) (max: der_length_t { min <= max } ) : Tot parser_kind = and_then_kind (parse_filter_kind parse_u8_kind) (parse_bounded_der_length_payload_kind min max) let parse_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_bounded_der_length_kind min max) (bounded_int min max)) = parse_tagged_union (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) (* equality *) let parse_bounded_der_length_payload_unfold (min: der_length_t) (max: der_length_t { min <= max }) (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) (input' : bytes) : Lemma (parse (parse_bounded_der_length_payload min max x) input' == ( match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_y) else None )) = parse_synth_eq (parse_der_length_payload x `parse_filter` (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max)) (fun (y: refine_with_tag tag_of_der_length x { min <= y && y <= max }) -> (y <: refine_with_tag (tag_of_bounded_der_length min max) x)) input' ; parse_filter_eq (parse_der_length_payload x) (fun (y: refine_with_tag tag_of_der_length x) -> min <= y && y <= max) input' let parse_bounded_der_length_unfold_aux (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_bounded_der_length_payload min max x) input' with | Some (y, consumed_y) -> Some (y, consumed_x + consumed_y) | None -> None else None )) = parse_tagged_union_eq (parse_u8 `parse_filter` parse_bounded_der_length_tag_cond min max) (tag_of_bounded_der_length min max) (parse_bounded_der_length_payload min max) input; parse_filter_eq parse_u8 (parse_bounded_der_length_tag_cond min max) input let parse_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length min max) input == (match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None else None )) = parse_bounded_der_length_unfold_aux min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let len = der_length_payload_size_of_tag x in if der_length_payload_size min <= len && len <= der_length_payload_size max then let input' = Seq.slice input consumed_x (Seq.length input) in parse_bounded_der_length_payload_unfold min max (x <: (x: U8.t { parse_bounded_der_length_tag_cond min max x == true } ) ) input' else () let parse_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (parser (parse_filter_kind parse_der_length_weak_kind) (bounded_int min max)) = parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max) `parse_synth` (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) let parse_bounded_der_length_weak_unfold (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (parse (parse_bounded_der_length_weak min max) input == ( match parse parse_u8 input with | None -> None | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> None | Some (y, consumed_y) -> if min <= y && y <= max then Some (y, consumed_x + consumed_y) else None end )) = parse_synth_eq (parse_der_length_weak `parse_filter` (fun y -> min <= y && y <= max)) (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) input; parse_filter_eq parse_der_length_weak (fun y -> min <= y && y <= max) input; parse_tagged_union_eq parse_u8 tag_of_der_length (fun x -> weaken parse_der_length_payload_kind_weak (parse_der_length_payload x)) input let parse_bounded_der_length_eq (min: der_length_t) (max: der_length_t { min <= max }) (input: bytes) : Lemma (ensures (parse (parse_bounded_der_length min max) input == parse (parse_bounded_der_length_weak min max) input)) = parse_bounded_der_length_unfold min max input; parse_bounded_der_length_weak_unfold min max input; match parse parse_u8 input with | None -> () | Some (x, consumed_x) -> let input' = Seq.slice input consumed_x (Seq.length input) in begin match parse (parse_der_length_payload x) input' with | None -> () | Some (y, consumed_y) -> if min <= y && y <= max then (der_length_payload_size_le min y; der_length_payload_size_le y max) else () end (* serializer *) let tag_of_der_length_lt_128 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) < 128)) (ensures (x == U8.v (tag_of_der_length x))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_invalid (x: der_length_t) : Lemma (requires (let y = U8.v (tag_of_der_length x) in y == 128 \/ y == 255)) (ensures False) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let tag_of_der_length_eq_129 (x: der_length_t) : Lemma (requires (U8.v (tag_of_der_length x) == 129)) (ensures (x >= 128 /\ x < 256)) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126) let synth_der_length_129_recip (x: U8.t { x == 129uy }) (y: refine_with_tag tag_of_der_length x) : GTot (y: U8.t {U8.v y >= 128}) = tag_of_der_length_eq_129 y; U8.uint_to_t y let synth_be_int_recip (len: nat) (x: lint len) : GTot (b: Seq.lseq byte len) = E.n_to_be len x let synth_be_int_inverse (len: nat) : Lemma (synth_inverse (synth_be_int len) (synth_be_int_recip len)) = () let synth_der_length_greater_recip (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) (y: refine_with_tag tag_of_der_length x) : Tot (y: lint len { y >= pow2 (8 * (len - 1)) } ) = assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); y let synth_der_length_greater_inverse (x: U8.t { U8.v x > 129 /\ U8.v x < 255 } ) (len: nat { len == U8.v x % 128 } ) : Lemma (synth_inverse (synth_der_length_greater x len) (synth_der_length_greater_recip x len)) = () private let serialize_der_length_payload_greater (x: U8.t { not (U8.v x < 128 || x = 128uy || x = 255uy || x = 129uy) } ) (len: nat { len == U8.v x - 128 } ) = (serialize_synth #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () ) let tag_of_der_length_lt_128_eta (x:U8.t{U8.v x < 128}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_lt_128 y <: Lemma (U8.v x == y) let tag_of_der_length_invalid_eta (x:U8.t{U8.v x == 128 \/ U8.v x == 255}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_invalid y <: Lemma False let tag_of_der_length_eq_129_eta (x:U8.t{U8.v x == 129}) = fun (y: refine_with_tag tag_of_der_length x) -> tag_of_der_length_eq_129 y <: Lemma (synth_der_length_129 x (synth_der_length_129_recip x y) == y) let serialize_der_length_payload (x: U8.t) : Tot (serializer (parse_der_length_payload x)) = assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_ret (x' <: refine_with_tag tag_of_der_length x) (tag_of_der_length_lt_128_eta x)) end else if x = 128uy || x = 255uy then fail_serializer (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length x) (tag_of_der_length_invalid_eta x) else if x = 129uy then begin serialize_weaken (parse_der_length_payload_kind x) (serialize_synth (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) ) end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? serialize_weaken (parse_der_length_payload_kind x) (serialize_der_length_payload_greater x len) end let serialize_der_length_weak : serializer parse_der_length_weak = serialize_tagged_union serialize_u8 tag_of_der_length (fun x -> serialize_weaken parse_der_length_payload_kind_weak (serialize_der_length_payload x)) #push-options "--max_ifuel 6 --z3rlimit 64" let serialize_der_length_weak_unfold (y: der_length_t) : Lemma (let res = serialize serialize_der_length_weak y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = let x = tag_of_der_length y in serialize_u8_spec x; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 7 == 128); assert_norm (pow2 8 == 256); assert_norm (256 < der_length_max); assert (U8.v x <= der_length_max); let (x' : der_length_t) = U8.v x in if x' < 128 then begin () end else if x = 128uy || x = 255uy then tag_of_der_length_invalid y else if x = 129uy then begin tag_of_der_length_eq_129 y; assert (U8.v (synth_der_length_129_recip x y) == y); let s1 = serialize ( serialize_synth #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x))) y in serialize_synth_eq' #_ #(parse_filter_refine #U8.t (fun y -> U8.v y >= 128)) #(refine_with_tag tag_of_der_length x) (parse_filter parse_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129 x) (serialize_filter serialize_u8 (fun y -> U8.v y >= 128)) (synth_der_length_129_recip x) (synth_inverse_intro' (synth_der_length_129 x) (synth_der_length_129_recip x) (tag_of_der_length_eq_129_eta x)) y s1 () (serialize serialize_u8 (synth_der_length_129_recip x y)) () ; serialize_u8_spec (U8.uint_to_t y); () end else begin let len : nat = U8.v x - 128 in synth_be_int_injective len; // FIXME: WHY WHY WHY does the pattern not trigger, even with higher rlimit? assert ( serialize (serialize_der_length_payload x) y == serialize (serialize_der_length_payload_greater x len) y ); serialize_synth_eq' #_ #(parse_filter_refine #(lint len) (fun (y: lint len) -> y >= pow2 (8 * (len - 1)))) #(refine_with_tag tag_of_der_length x) _ (synth_der_length_greater x len) (serialize_filter (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (fun (y: lint len) -> y >= pow2 (8 * (len - 1))) ) (synth_der_length_greater_recip x len) () y (serialize (serialize_der_length_payload_greater x len) y) (_ by (FStar.Tactics.trefl ())) (serialize (serialize_synth #_ #(Seq.lseq byte len) #(lint len) _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () ) (synth_der_length_greater_recip x len y) ) () ; serialize_synth_eq _ (synth_be_int len) (serialize_seq_flbytes len) (synth_be_int_recip len) () (synth_der_length_greater_recip x len y); Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); () end; () #pop-options let serialize_bounded_der_length_weak (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length_weak min max)) = serialize_synth _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () let serialize_bounded_der_length (min: der_length_t) (max: der_length_t { min <= max }) : Tot (serializer (parse_bounded_der_length min max)) = Classical.forall_intro (parse_bounded_der_length_eq min max); serialize_ext _ (serialize_bounded_der_length_weak min max) (parse_bounded_der_length min max) let serialize_bounded_der_length_unfold (min: der_length_t) (max: der_length_t { min <= max }) (y: bounded_int min max) : Lemma (let res = serialize (serialize_bounded_der_length min max) y in let x = tag_of_der_length y in let s1 = Seq.create 1 x in if x `U8.lt` 128uy then res `Seq.equal` s1 else if x = 129uy then y <= 255 /\ res `Seq.equal` (s1 `Seq.append` Seq.create 1 (U8.uint_to_t y)) else let len = log256 y in res `Seq.equal` (s1 `Seq.append` E.n_to_be len y) ) = serialize_synth_eq _ (fun (y: der_length_t {min <= y && y <= max}) -> (y <: bounded_int min max)) (serialize_filter serialize_der_length_weak (fun y -> min <= y && y <= max) ) (fun (y : bounded_int min max) -> (y <: (y: der_length_t {min <= y && y <= max}))) () y; serialize_der_length_weak_unfold y (* 32-bit spec *) module U32 = FStar.UInt32 let der_length_payload_size_of_tag_inv32 (x: der_length_t) : Lemma (requires (x < 4294967296)) (ensures ( tag_of_der_length x == ( if x < 128 then U8.uint_to_t x else if x < 256 then 129uy else if x < 65536 then 130uy else if x < 16777216 then 131uy else 132uy ))) = if x < 128 then () else let len_len = log256 x in assert_norm (der_length_max == pow2 (8 * 126) - 1); Math.pow2_lt_recip (8 * (len_len - 1)) (8 * 126); assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); if x < 256 then log256_unique x 1 else if x < 65536 then log256_unique x 2 else if x < 16777216 then log256_unique x 3 else log256_unique x 4 let synth_der_length_payload32 (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) (y: refine_with_tag tag_of_der_length x) : GTot (refine_with_tag tag_of_der_length32 x) = let _ = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in if y >= 128 then begin Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y) end in U32.uint_to_t y let synth_der_length_payload32_injective (x: U8.t { der_length_payload_size_of_tag x <= 4 } ) : Lemma (synth_injective (synth_der_length_payload32 x)) [SMTPat (synth_injective (synth_der_length_payload32 x))] = assert_norm (der_length_max == pow2 (8 * 126) - 1); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in synth_injective_intro' (synth_der_length_payload32 x) (fun (y1 y2: refine_with_tag tag_of_der_length x) -> if y1 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y1 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y1) == 128 + log256 y1) end; if y2 >= 128 then begin Math.pow2_lt_recip (8 * (log256 y2 - 1)) (8 * 126); assert (U8.v (tag_of_der_length y2) == 128 + log256 y2) end ) let parse_der_length_payload32 x : Tot (parser (parse_der_length_payload_kind x) (refine_with_tag tag_of_der_length32 x)) = parse_der_length_payload x `parse_synth` synth_der_length_payload32 x let be_int_of_bounded_integer (len: integer_size) (x: nat { x < pow2 (8 * len) } ) : GTot (bounded_integer len) = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296); U32.uint_to_t x let be_int_of_bounded_integer_injective (len: integer_size) : Lemma (synth_injective (be_int_of_bounded_integer len)) [SMTPat (synth_injective (be_int_of_bounded_integer len))] // FIXME: WHY WHY WHY does this pattern NEVER trigger? = integer_size_values len; assert_norm (pow2 (8 * 1) == 256); assert_norm (pow2 (8 * 2) == 65536); assert_norm (pow2 (8 * 3) == 16777216); assert_norm (pow2 (8 * 4) == 4294967296) #push-options "--max_ifuel 4 --z3rlimit 16" let parse_seq_flbytes_synth_be_int_eq (len: integer_size) (input: bytes) : Lemma ( let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse ( parse_synth #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len) ) (be_int_of_bounded_integer len) ) input == parse (parse_bounded_integer len) input) = let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_synth_eq (parse_seq_flbytes len `parse_synth` synth_be_int len) (be_int_of_bounded_integer len) input; parse_synth_eq (parse_seq_flbytes len) (synth_be_int len) input; parser_kind_prop_equiv (parse_bounded_integer_kind len) (parse_bounded_integer len); parse_bounded_integer_spec len input
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "LowParse.Spec.SeqBytes.Base.fst.checked", "LowParse.Spec.Combinators.fsti.checked", "LowParse.Math.fst.checked", "FStar.UInt8.fsti.checked", "FStar.UInt32.fsti.checked", "FStar.UInt.fsti.checked", "FStar.Tactics.Effect.fsti.checked", "FStar.Tactics.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Math.Lemmas.fst.checked", "FStar.Endianness.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": true, "source_file": "LowParse.Spec.DER.fst" }
[ { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.UInt32", "short_module": "U32" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.Endianness", "short_module": "E" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.SeqBytes.Base", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Combinators", "short_module": null }, { "abbrev": true, "full_module": "FStar.Int.Cast", "short_module": "Cast" }, { "abbrev": true, "full_module": "LowParse.Math", "short_module": "Math" }, { "abbrev": true, "full_module": "FStar.Seq", "short_module": "Seq" }, { "abbrev": true, "full_module": "FStar.UInt", "short_module": "UInt" }, { "abbrev": true, "full_module": "FStar.UInt8", "short_module": "U8" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.BoundedInt", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec.Int", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "short_module": null }, { "abbrev": false, "full_module": "LowParse.Spec", "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": 4, "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": [ "smt.arith.nl=false" ], "z3refresh": false, "z3rlimit": 16, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
x: FStar.UInt8.t{LowParse.Spec.DER.der_length_payload_size_of_tag x <= 4} -> input: LowParse.Bytes.bytes -> FStar.Pervasives.Lemma (ensures (let y = LowParse.Spec.Base.parse (LowParse.Spec.DER.parse_der_length_payload32 x) input in 256 < LowParse.Spec.DER.der_length_max /\ (match FStar.UInt8.v x < 128 with | true -> LowParse.Spec.DER.tag_of_der_length (FStar.UInt8.v x) == x /\ y == FStar.Pervasives.Native.Some (FStar.Int.Cast.uint8_to_uint32 x, 0) | _ -> (match x = 128uy || x = 255uy with | true -> y == FStar.Pervasives.Native.None | _ -> (match x = 129uy with | true -> (match LowParse.Spec.Base.parse LowParse.Spec.Int.parse_u8 input with | FStar.Pervasives.Native.None #_ -> y == FStar.Pervasives.Native.None | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ z consumed) -> (match FStar.UInt8.v z < 128 with | true -> y == FStar.Pervasives.Native.None | _ -> LowParse.Spec.DER.tag_of_der_length (FStar.UInt8.v z) == x /\ y == FStar.Pervasives.Native.Some (FStar.Int.Cast.uint8_to_uint32 z, consumed)) <: Prims.logical) <: Prims.logical | _ -> let len = FStar.UInt8.v x - 128 in 2 <= len /\ len <= 4 /\ (let res = LowParse.Spec.Base.parse (LowParse.Spec.BoundedInt.parse_bounded_integer len ) input in (match res with | FStar.Pervasives.Native.None #_ -> y == FStar.Pervasives.Native.None | FStar.Pervasives.Native.Some #_ (FStar.Pervasives.Native.Mktuple2 #_ #_ z consumed) -> len > 0 /\ (match FStar.UInt32.v z >= Prims.pow2 (8 * (len - 1)) with | true -> FStar.UInt32.v z <= LowParse.Spec.DER.der_length_max /\ LowParse.Spec.DER.tag_of_der_length32 z == x /\ y == FStar.Pervasives.Native.Some (z, consumed) | _ -> y == FStar.Pervasives.Native.None)) <: Prims.logical)) <: Prims.logical) <: Prims.logical)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "FStar.UInt8.t", "Prims.b2t", "Prims.op_LessThanOrEqual", "LowParse.Spec.DER.der_length_payload_size_of_tag", "LowParse.Bytes.bytes", "Prims.op_LessThan", "FStar.UInt8.v", "Prims.bool", "Prims.op_BarBar", "Prims.op_Equality", "FStar.UInt8.__uint_to_t", "LowParse.Spec.Combinators.parse_synth_eq", "LowParse.Spec.Base.total_constant_size_parser_kind", "LowParse.Spec.DER.lint", "LowParse.Spec.BoundedInt.bounded_integer", "LowParse.Spec.Combinators.parse_synth", "FStar.Seq.Properties.lseq", "LowParse.Bytes.byte", "LowParse.Spec.SeqBytes.Base.parse_seq_flbytes", "LowParse.Spec.DER.synth_be_int", "LowParse.Spec.DER.be_int_of_bounded_integer", "Prims.unit", "LowParse.Spec.BoundedInt.integer_size_values", "LowParse.Spec.DER.parse_seq_flbytes_synth_be_int_eq", "LowParse.Spec.DER.be_int_of_bounded_integer_injective", "LowParse.Spec.DER.synth_be_int_injective", "Prims._assert", "Prims.l_and", "Prims.nat", "Prims.op_Subtraction", "LowParse.Spec.DER.parse_der_length_payload_unfold", "LowParse.Spec.Base.parse", "LowParse.Spec.Base.refine_with_tag", "LowParse.Spec.DER.der_length_t", "LowParse.Spec.DER.tag_of_der_length", "LowParse.Spec.DER.parse_der_length_payload", "LowParse.Spec.Base.consumed_length", "Prims.op_GreaterThanOrEqual", "Prims.eq2", "Prims.int", "Prims.op_Addition", "LowParse.Spec.DER.log256", "LowParse.Math.pow2_lt_recip", "FStar.Mul.op_Star", "FStar.Pervasives.assert_norm", "Prims.pow2", "LowParse.Spec.DER.der_length_max", "LowParse.Spec.DER.parse_der_length_payload_kind", "FStar.UInt32.t", "LowParse.Spec.DER.tag_of_der_length32", "LowParse.Spec.DER.synth_der_length_payload32" ]
[]
false
false
true
false
false
let parse_der_length_payload32_unfold x input =
parse_synth_eq (parse_der_length_payload x) (synth_der_length_payload32 x) input; assert_norm (der_length_max == pow2 (8 * 126) - 1); assert_norm (pow2 (8 * 1) == 256); let _ = assert_norm (pow2 (8 * 2) == 65536) in let _ = assert_norm (pow2 (8 * 3) == 16777216) in let _ = assert_norm (pow2 (8 * 4) == 4294967296) in (match parse (parse_der_length_payload x) input with | None -> () | Some (y, _) -> if y >= 128 then (Math.pow2_lt_recip (8 * (log256 y - 1)) (8 * 126); assert (U8.v (tag_of_der_length y) == 128 + log256 y))); parse_der_length_payload_unfold x input; if U8.v x < 128 then () else if x = 128uy || x = 255uy then () else if x = 129uy then () else let len:nat = U8.v x - 128 in assert (2 <= len /\ len <= 4); let _ = synth_be_int_injective len in let _ = be_int_of_bounded_integer_injective len in parse_seq_flbytes_synth_be_int_eq len input; integer_size_values len; parse_synth_eq #_ #(lint len) #(bounded_integer len) (parse_synth #_ #(Seq.lseq byte len) #(lint len) (parse_seq_flbytes len) (synth_be_int len)) (be_int_of_bounded_integer len) input
false
Alg.fst
Alg.another_raise
val another_raise (#a: _) (e: exn) : Alg a [Raise]
val another_raise (#a: _) (e: exn) : Alg a [Raise]
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)
{ "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": 211, "start_col": 0, "start_line": 207 }
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
{ "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
e: Prims.exn -> Alg.Alg a
Alg.Alg
[]
[]
[ "Prims.exn", "Alg.Op", "Alg.Raise", "Alg.Return", "Prims.Cons", "Alg.op", "Prims.Nil" ]
[]
false
true
false
false
false
let another_raise #a (e: exn) : Alg a [Raise] =
Alg?.reflect (Op Raise e Return)
false
Alg.fst
Alg.raise
val raise: #a: _ -> exn -> Alg a [Raise]
val raise: #a: _ -> exn -> Alg a [Raise]
let raise : #a:_ -> exn -> Alg a [Raise] = fun e -> match geneff Raise e with
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 80, "end_line": 205, "start_col": 0, "start_line": 205 }
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
{ "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
e: Prims.exn -> Alg.Alg a
Alg.Alg
[]
[]
[ "Prims.exn", "Alg.op_out", "Alg.Raise", "Alg.geneff" ]
[]
false
true
false
false
false
let raise: #a: _ -> exn -> Alg a [Raise] =
fun e -> match geneff Raise e with
false
Alg.fst
Alg.interp_pure
val interp_pure (#a: _) (f: (unit -> Alg a [])) : Tot a
val interp_pure (#a: _) (f: (unit -> Alg a [])) : Tot a
let interp_pure #a (f : unit -> Alg a []) : Tot a = interp_pure_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": 83, "end_line": 591, "start_col": 0, "start_line": 591 }
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
{ "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) -> a
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Nil", "Alg.op", "Alg.interp_pure_tree" ]
[]
false
false
false
false
false
let interp_pure #a (f: (unit -> Alg a [])) : Tot a =
interp_pure_tree (reify (f ()))
false
Alg.fst
Alg.get
val get: unit -> Alg int [Read]
val get: unit -> Alg int [Read]
let get : unit -> Alg int [Read] = geneff Read
{ "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": 203, "start_col": 0, "start_line": 203 }
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)
{ "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 -> Alg.Alg Prims.int
Alg.Alg
[]
[]
[ "Alg.geneff", "Alg.Read" ]
[]
false
true
false
false
false
let get: unit -> Alg int [Read] =
geneff Read
false
Alg.fst
Alg.interp_rd
val interp_rd (#a: _) (f: (unit -> Alg a [Read])) (s: state) : Tot a
val interp_rd (#a: _) (f: (unit -> Alg a [Read])) (s: state) : Tot a
let interp_rd #a (f : unit -> Alg a [Read]) (s:state) : Tot a = interp_rd_tree (reify (f ())) s
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 95, "end_line": 599, "start_col": 0, "start_line": 599 }
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
{ "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 -> a
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Read", "Prims.Nil", "Alg.state", "Alg.interp_rd_tree" ]
[]
false
false
false
false
false
let interp_rd #a (f: (unit -> Alg a [Read])) (s: state) : Tot a =
interp_rd_tree (reify (f ())) s
false
Alg.fst
Alg.interp_rdwr
val interp_rdwr (#a: _) (f: (unit -> Alg a [Read; Write])) (s: state) : Tot (a & state)
val interp_rdwr (#a: _) (f: (unit -> Alg a [Read; Write])) (s: state) : Tot (a & state)
let interp_rdwr #a (f : unit -> Alg a [Read; Write]) (s:state) : Tot (a & state) = interp_rdwr_tree (reify (f ())) s
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 116, "end_line": 609, "start_col": 0, "start_line": 609 }
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
{ "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 -> a * Alg.state
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Write", "Prims.Nil", "Alg.state", "Alg.interp_rdwr_tree", "FStar.Pervasives.Native.tuple2" ]
[]
false
false
false
false
false
let interp_rdwr #a (f: (unit -> Alg a [Read; Write])) (s: state) : Tot (a & state) =
interp_rdwr_tree (reify (f ())) s
false
Alg.fst
Alg.frompure
val frompure (#a: _) (t: tree a []) : a
val frompure (#a: _) (t: tree a []) : a
let frompure #a (t : tree a []) : 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": 66, "end_line": 226, "start_col": 0, "start_line": 226 }
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
{ "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 frompure #a (t: tree a []) : a =
match t with | Return x -> x
false
Alg.fst
Alg.defh_tree
val defh_tree (#b #labs: _) (#o: op{o `memP` labs}) : handler_tree_op o b labs
val defh_tree (#b #labs: _) (#o: op{o `memP` labs}) : handler_tree_op o b labs
let defh_tree #b #labs (#o:op{o `memP` labs}) : handler_tree_op o b labs = fun i k -> Op o i k
{ "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": 337, "start_col": 0, "start_line": 335 }
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
{ "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_tree_op o b labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.tree", "Alg.Op", "Alg.handler_tree_op" ]
[]
false
false
false
false
false
let defh_tree #b #labs (#o: op{o `memP` labs}) : handler_tree_op o b labs =
fun i k -> Op o i k
false
Alg.fst
Alg.try_with
val try_with (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) (g: (unit -> Alg a labs)) : Alg a labs
val try_with (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) (g: (unit -> Alg a labs)) : Alg a labs
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 40, "end_line": 348, "start_col": 0, "start_line": 343 }
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
{ "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_with", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.defh", "Alg.handler_op" ]
[]
false
true
false
false
false
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)
false
Alg.fst
Alg.__catch1
val __catch1 (#a #labs: _) (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs
val __catch1 (#a #labs: _) (t1: tree a (Raise :: labs)) (t2: tree a labs) : tree a labs
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 56, "end_line": 277, "start_col": 0, "start_line": 273 }
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
{ "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 __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)
false
Alg.fst
Alg.interp_read_raise_exn
val interp_read_raise_exn (#a: _) (f: (unit -> Alg a [Read; Raise])) (s: state) : either exn a
val interp_read_raise_exn (#a: _) (f: (unit -> Alg a [Read; Raise])) (s: state) : either exn a
let interp_read_raise_exn #a (f : unit -> Alg a [Read; Raise]) (s:state) : either exn a = interp_read_raise_tree (reify (f ())) s
{ "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": 620, "start_col": 0, "start_line": 619 }
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
{ "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 -> FStar.Pervasives.either Prims.exn a
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Raise", "Prims.Nil", "Alg.state", "Alg.interp_read_raise_tree", "FStar.Pervasives.either", "Prims.exn" ]
[]
false
false
false
false
false
let interp_read_raise_exn #a (f: (unit -> Alg a [Read; Raise])) (s: state) : either exn a =
interp_read_raise_tree (reify (f ())) s
false
Alg.fst
Alg.test_catch2
val test_catch2 (f: (unit -> Alg int [Raise; Write])) : Alg int [Raise; Write]
val test_catch2 (f: (unit -> Alg int [Raise; Write])) : Alg int [Raise; Write]
let test_catch2 (f : unit -> Alg int [Raise; Write]) : Alg int [Raise; Write] = let g () : Alg int [] = 42 in catch f g
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 11, "end_line": 292, "start_col": 0, "start_line": 290 }
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
{ "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.catch" ]
[]
false
true
false
false
false
let test_catch2 (f: (unit -> Alg int [Raise; Write])) : Alg int [Raise; Write] =
let g () : Alg int [] = 42 in catch f g
false
Alg.fst
Alg.test0
val test0 (x y: int) : Alg int [Read; Raise]
val test0 (x y: int) : Alg int [Read; Raise]
let test0 (x y : int) : Alg int [Read; Raise] = let z = get () in if z < 0 then raise (Failure "error"); x + y + z
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 11, "end_line": 236, "start_col": 0, "start_line": 233 }
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
{ "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
x: Prims.int -> y: Prims.int -> Alg.Alg Prims.int
Alg.Alg
[]
[]
[ "Prims.int", "Prims.op_Addition", "Prims.unit", "Prims.op_LessThan", "Alg.raise", "Alg.Failure", "Prims.bool", "Alg.get", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Raise", "Prims.Nil" ]
[]
false
true
false
false
false
let test0 (x y: int) : Alg int [Read; Raise] =
let z = get () in if z < 0 then raise (Failure "error"); x + y + z
false
Alg.fst
Alg.interp_all
val interp_all (#a: _) (f: (unit -> Alg a [Read; Write; Raise])) (s: state) : Tot (option a & state)
val interp_all (#a: _) (f: (unit -> Alg a [Read; Write; Raise])) (s: state) : Tot (option a & state)
let interp_all #a (f : unit -> Alg a [Read; Write; Raise]) (s:state) : Tot (option a & state) = interp_all_tree (reify (f ())) s
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 128, "end_line": 632, "start_col": 0, "start_line": 632 }
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)
{ "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 -> FStar.Pervasives.Native.option a * Alg.state
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Write", "Alg.Raise", "Prims.Nil", "Alg.state", "Alg.interp_all_tree", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.option" ]
[]
false
false
false
false
false
let interp_all #a (f: (unit -> Alg a [Read; Write; Raise])) (s: state) : Tot (option a & state) =
interp_all_tree (reify (f ())) s
false
Alg.fst
Alg.defh
val defh (#b #labs: _) (#o: op{o `memP` labs}) : handler_op o b labs
val defh (#b #labs: _) (#o: op{o `memP` labs}) : handler_op o b labs
let defh #b #labs (#o:op{o `memP` labs}) : handler_op o b labs = fun i k -> k (geneff o i)
{ "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": 326, "start_col": 0, "start_line": 324 }
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
{ "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_op o b labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.geneff", "Alg.handler_op" ]
[]
false
false
false
false
false
let defh #b #labs (#o: op{o `memP` labs}) : handler_op o b labs =
fun i k -> k (geneff o i)
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 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
{ "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": 270, "start_col": 0, "start_line": 261 }
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 // ....
{ "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.op_inp", "Alg.op_out", "Alg.tree0", "Alg.Op", "Alg.__catch0", "Alg.Return" ]
[ "recursion" ]
false
false
false
false
false
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
false
Alg.fst
Alg.handle_with
val handle_with (#a #b: _) (#labs0 #labs1: ops) ($f: (unit -> Alg a labs0)) (v: (a -> Alg b labs1)) (h: handler labs0 b labs1) : Alg b labs1
val handle_with (#a #b: _) (#labs0 #labs1: ops) ($f: (unit -> Alg a labs0)) (v: (a -> Alg b labs1)) (h: handler labs0 b labs1) : Alg b labs1
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)))))
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 89, "end_line": 319, "start_col": 0, "start_line": 310 }
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
{ "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) -> v: (_: a -> Alg.Alg b) -> h: Alg.handler labs0 b labs1 -> Alg.Alg b
Alg.Alg
[]
[]
[ "Alg.ops", "Prims.unit", "Alg.handler", "Alg.handle_tree", "Alg.tree", "Alg.op", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out" ]
[]
false
true
false
false
false
let handle_with (#a #b: _) (#labs0 #labs1: ops) ($f: (unit -> Alg a labs0)) (v: (a -> Alg b labs1)) (h: handler 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)))))
false
Alg.fst
Alg.listmap_read
val listmap_read (#a #b #labs: _) (f: (a -> Alg b labs)) (l: list a) : Alg (list b) (Read :: labs)
val listmap_read (#a #b #labs: _) (f: (a -> Alg b labs)) (l: list a) : Alg (list b) (Read :: labs)
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 67, "end_line": 223, "start_col": 0, "start_line": 219 }
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
{ "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: (_: a -> Alg.Alg b) -> l: Prims.list a -> Alg.Alg (Prims.list b)
Alg.Alg
[]
[]
[ "Alg.ops", "Prims.list", "Prims.Nil", "Prims.int", "Alg.get", "Prims.Cons", "Alg.listmap_read", "Alg.op", "Alg.Read" ]
[ "recursion" ]
false
true
false
false
false
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
false
Alg.fst
Alg.some_as_alg
val some_as_alg: #a: Type -> #labs: _ -> a -> Alg (option a) labs
val some_as_alg: #a: Type -> #labs: _ -> a -> Alg (option a) labs
let some_as_alg (#a:Type) #labs : a -> Alg (option a) labs = fun x -> Some 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": 351, "start_col": 0, "start_line": 350 }
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)
{ "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 -> Alg.Alg (FStar.Pervasives.Native.option a)
Alg.Alg
[]
[]
[ "Alg.ops", "FStar.Pervasives.Native.Some", "FStar.Pervasives.Native.option" ]
[]
false
true
false
false
false
let some_as_alg (#a: Type) #labs : a -> Alg (option a) labs =
fun x -> Some x
false
Alg.fst
Alg.exp_defh
val exp_defh (#b #labs: _) : handler labs b labs
val exp_defh (#b #labs: _) : handler labs b labs
let exp_defh #b #labs : handler labs b labs = fun o i k -> k (geneff o i)
{ "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": 331, "start_col": 0, "start_line": 329 }
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)
{ "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 labs b labs
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.op", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.geneff", "Alg.handler" ]
[]
false
false
false
false
false
let exp_defh #b #labs : handler labs b labs =
fun o i k -> k (geneff o i)
false
Alg.fst
Alg.test1
val test1 (x y: int) : Alg int [Raise; Read; Write]
val test1 (x y: int) : Alg int [Raise; Read; Write]
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 22, "end_line": 242, "start_col": 0, "start_line": 238 }
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
{ "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
x: Prims.int -> y: Prims.int -> Alg.Alg Prims.int
Alg.Alg
[]
[]
[ "Prims.int", "Prims.op_GreaterThan", "Prims.op_Addition", "Alg.raise", "Alg.Failure", "Prims.bool", "Prims.op_Subtraction", "Prims.unit", "Alg.put", "Alg.get", "Prims.Cons", "Alg.op", "Alg.Raise", "Alg.Read", "Alg.Write", "Prims.Nil" ]
[]
false
true
false
false
false
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)
false
Alg.fst
Alg.catchE
val catchE (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) : Alg (option a) labs
val catchE (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) : Alg (option a) labs
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 51, "end_line": 355, "start_col": 0, "start_line": 353 }
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
{ "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) -> Alg.Alg (FStar.Pervasives.Native.option a)
Alg.Alg
[]
[]
[ "Prims.list", "Alg.op", "Prims.unit", "Prims.Cons", "Alg.Raise", "Alg.handle_with", "FStar.Pervasives.Native.option", "Alg.some_as_alg", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "FStar.Pervasives.Native.None", "Alg.defh", "Alg.handler_op" ]
[]
false
true
false
false
false
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)
false
Alg.fst
Alg.handle_sub
val 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
val 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
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 37, "end_line": 518, "start_col": 0, "start_line": 513 }
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
{ "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) -> v: (_: a -> Alg.Alg b) -> h: Alg.handler labs0 b labs1 -> Alg.Alg b
Alg.Alg
[]
[]
[ "Prims.list", "Alg.op", "Prims.unit", "FStar.List.Tot.Base.op_At", "Alg.handler", "Alg.handle_with", "Alg.widen_handler" ]
[]
false
true
false
false
false
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)
false
Alg.fst
Alg.labpoly
val labpoly (#labs: _) (f g: (unit -> Alg int labs)) : Alg int labs
val labpoly (#labs: _) (f g: (unit -> Alg int labs)) : Alg int labs
let labpoly #labs (f g : unit -> Alg int labs) : Alg int labs = f () + g ()
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 75, "end_line": 245, "start_col": 0, "start_line": 245 }
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)
{ "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) -> g: (_: Prims.unit -> Alg.Alg Prims.int) -> Alg.Alg Prims.int
Alg.Alg
[]
[]
[ "Alg.ops", "Prims.unit", "Prims.int", "Prims.op_Addition" ]
[]
false
true
false
false
false
let labpoly #labs (f: (unit -> Alg int labs)) (g: (unit -> Alg int labs)) : Alg int labs =
f () + g ()
false
Alg.fst
Alg.__catchST0
val __catchST0 (#a #labs: _) (t1: tree a (Read :: Write :: labs)) (s0: state) : tree (a & int) labs
val __catchST0 (#a #labs: _) (t1: tree a (Read :: Write :: labs)) (s0: state) : tree (a & int) labs
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'
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 16, "end_line": 382, "start_col": 0, "start_line": 372 }
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 *****)
{ "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.Read :: Alg.Write :: labs) -> s0: Alg.state -> Alg.tree (a * Prims.int) labs
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "Alg.op", "Alg.tree", "Prims.Cons", "Alg.Read", "Alg.Write", "Alg.state", "Alg.Return", "FStar.Pervasives.Native.tuple2", "Prims.int", "FStar.Pervasives.Native.Mktuple2", "Alg.op_inp", "Alg.op_out", "Alg.tree0", "Alg.__catchST0", "Alg.Op" ]
[ "recursion" ]
false
false
false
false
false
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 -> let k' o : tree (a & int) labs = __catchST0 #a #labs (k o) s0 in Op act i k'
false
Alg.fst
Alg.widen_handler
val widen_handler (#b #labs0 #labs1: _) (h: handler labs0 b labs1) : handler (labs0 @ labs1) b labs1
val widen_handler (#b #labs0 #labs1: _) (h: handler labs0 b labs1) : handler (labs0 @ labs1) b labs1
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 16, "end_line": 510, "start_col": 0, "start_line": 500 }
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)
{ "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
h: Alg.handler labs0 b labs1 -> Alg.handler (labs0 @ labs1) b labs1
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.handler", "Alg.op", "FStar.List.Tot.Base.memP", "FStar.List.Tot.Base.op_At", "FStar.List.Tot.Base.mem", "Prims.bool", "Alg.defh", "Alg.handler_op", "Prims.unit", "FStar.List.Tot.Properties.mem_memP" ]
[]
false
false
false
false
false
let widen_handler (#b #labs0 #labs1: _) (h: handler labs0 b labs1) : handler (labs0 @ labs1) b labs1 =
fun op -> mem_memP op labs0; if op `mem` labs0 then h op else defh
false
Alg.fst
Alg.widen_handler_1
val widen_handler_1 (#b: _) (#o: op) (#labs1: _) (h: handler_op o b labs1) : handler (o :: labs1) b labs1
val widen_handler_1 (#b: _) (#o: op) (#labs1: _) (h: handler_op o b labs1) : handler (o :: labs1) b labs1
let widen_handler_1 (#b:_) (#o:op) (#labs1:_) (h:handler_op o b labs1) : handler (o::labs1) b labs1 = widen_handler #_ #[o] (fun _ -> h)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 38, "end_line": 523, "start_col": 0, "start_line": 520 }
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)
{ "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
h: Alg.handler_op o b labs1 -> Alg.handler (o :: labs1) b labs1
Prims.Tot
[ "total" ]
[]
[ "Alg.op", "Alg.ops", "Alg.handler_op", "Alg.widen_handler", "Prims.Cons", "Prims.Nil", "FStar.List.Tot.Base.memP", "Alg.handler" ]
[]
false
false
false
false
false
let widen_handler_1 (#b: _) (#o: op) (#labs1: _) (h: handler_op o b labs1) : handler (o :: labs1) b labs1 =
widen_handler #_ #[o] (fun _ -> h)
false
Alg.fst
Alg.handle_read
val handle_read (#a: Type) (#labs: ops) (f: (unit -> Alg a (Read :: labs))) (h: handler_op Read a labs) : Alg a labs
val handle_read (#a: Type) (#labs: ops) (f: (unit -> Alg a (Read :: labs))) (h: handler_op Read a labs) : Alg a labs
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)
{ "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": 469, "start_col": 0, "start_line": 463 }
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
{ "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) -> h: Alg.handler_op Alg.Read a labs -> Alg.Alg a
Alg.Alg
[]
[]
[ "Alg.ops", "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.handler_op", "Alg.handle_with", "FStar.List.Tot.Base.memP", "Alg.defh" ]
[]
false
true
false
false
false
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)
false
Alg.fst
Alg.handle_return
val handle_return (#a: _) (x: a) : Alg (option a & state) [Write; Read]
val handle_return (#a: _) (x: a) : Alg (option a & state) [Write; Read]
let handle_return #a (x:a) : Alg (option a & state) [Write; Read] = (Some x, get ())
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 20, "end_line": 550, "start_col": 0, "start_line": 548 }
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)
{ "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
x: a -> Alg.Alg (FStar.Pervasives.Native.option a * Alg.state)
Alg.Alg
[]
[]
[ "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.option", "Prims.int", "FStar.Pervasives.Native.Some", "FStar.Pervasives.Native.tuple2", "Alg.state", "Alg.get", "Prims.Cons", "Alg.op", "Alg.Write", "Alg.Read", "Prims.Nil" ]
[]
false
true
false
false
false
let handle_return #a (x: a) : Alg (option a & state) [Write; Read] =
(Some x, get ())
false
Alg.fst
Alg.catch
val catch (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) (g: (unit -> Alg a labs)) : Alg a labs
val catch (#a #labs: _) (f: (unit -> Alg a (Raise :: labs))) (g: (unit -> Alg a labs)) : Alg a labs
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 ())))
{ "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": 282, "start_col": 0, "start_line": 280 }
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)
{ "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.__catch1" ]
[]
false
true
false
false
false
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 ())))
false
Alg.fst
Alg.baseop
val baseop : Type0
let baseop = o:op{not (Other? o)}
{ "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": 720, "start_col": 0, "start_line": 720 }
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 *)
{ "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
Type0
Prims.Tot
[ "total" ]
[]
[ "Alg.op", "Prims.b2t", "Prims.op_Negation", "Alg.uu___is_Other" ]
[]
false
false
false
true
true
let baseop =
o: op{not (Other? o)}
false
Alg.fst
Alg.trlabs'
val trlabs' : x: Prims.list Lattice.eff_label -> Prims.list Alg.op
let trlabs' = List.Tot.map trlab'
{ "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": 733, "start_col": 0, "start_line": 733 }
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
{ "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
x: Prims.list Lattice.eff_label -> Prims.list Alg.op
Prims.Tot
[ "total" ]
[]
[ "FStar.List.Tot.Base.map", "Lattice.eff_label", "Alg.op", "Alg.trlab'" ]
[]
false
false
false
true
false
let trlabs' =
List.Tot.map trlab'
false
Alg.fst
Alg.trlabs
val trlabs : x: Prims.list Alg.baseop -> Prims.list Lattice.eff_label
let trlabs = List.Tot.map trlab
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 32, "end_line": 732, "start_col": 0, "start_line": 732 }
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
{ "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
x: Prims.list Alg.baseop -> Prims.list Lattice.eff_label
Prims.Tot
[ "total" ]
[]
[ "FStar.List.Tot.Base.map", "Alg.baseop", "Lattice.eff_label", "Alg.trlab" ]
[]
false
false
false
true
false
let trlabs =
List.Tot.map trlab
false
Alg.fst
Alg._catchST
val _catchST (#a #labs: _) (f: (unit -> Alg a (Read :: Write :: labs))) (s0: state) : Alg (a & state) labs
val _catchST (#a #labs: _) (f: (unit -> Alg a (Read :: Write :: labs))) (s0: state) : Alg (a & state) labs
let _catchST #a #labs (f : unit -> Alg a (Read::Write::labs)) (s0 : state) : Alg (a & state) labs = Alg?.reflect (__catchST1 (reify (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": 410, "start_col": 0, "start_line": 406 }
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))
{ "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 (a * Alg.state)
Alg.Alg
[]
[]
[ "Prims.list", "Alg.op", "Prims.unit", "Prims.Cons", "Alg.Read", "Alg.Write", "Alg.state", "Alg.__catchST1", "FStar.Pervasives.Native.tuple2" ]
[]
false
true
false
false
false
let _catchST #a #labs (f: (unit -> Alg a (Read :: Write :: labs))) (s0: state) : Alg (a & state) labs =
Alg?.reflect (__catchST1 (reify (f ())) s0)
false
Alg.fst
Alg.catchST
val catchST (#a #labs: _) (f: (unit -> Alg a (Read :: Write :: labs))) (s0: state) : Alg (a & state) labs
val catchST (#a #labs: _) (f: (unit -> Alg a (Read :: Write :: labs))) (s0: state) : Alg (a & state) labs
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
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 45, "end_line": 425, "start_col": 0, "start_line": 419 }
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,
{ "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 (a * Alg.state)
Alg.Alg
[]
[]
[ "Prims.list", "Alg.op", "Prims.unit", "Prims.Cons", "Alg.Read", "Alg.Write", "Alg.state", "FStar.Pervasives.Native.tuple2", "Alg.handle_with", "FStar.Pervasives.Native.Mktuple2", "FStar.List.Tot.Base.memP", "Alg.op_inp", "Alg.op_out", "Alg.defh", "Alg.handler_op" ]
[]
false
true
false
false
false
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
false
Alg.fst
Alg.read_handler
val read_handler (#b: Type) (#labs: ops) (s0: state) : handler_op Read b labs
val read_handler (#b: Type) (#labs: ops) (s0: state) : handler_op Read b labs
let read_handler (#b:Type) (#labs:ops) (s0:state) : handler_op Read b labs = 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": 19, "end_line": 460, "start_col": 0, "start_line": 456 }
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. *)
{ "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
s0: Alg.state -> Alg.handler_op Alg.Read b labs
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.state", "Alg.op_inp", "Alg.Read", "Alg.op_out", "Alg.handler_op" ]
[]
false
false
false
false
false
let read_handler (#b: Type) (#labs: ops) (s0: state) : handler_op Read b labs =
fun _ k -> k s0
false
Alg.fst
Alg.handle_write
val handle_write (#a: Type) (#labs: ops) (f: (unit -> Alg a (Write :: labs))) : Alg a labs
val handle_write (#a: Type) (#labs: ops) (f: (unit -> Alg a (Write :: labs))) : Alg a labs
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 39, "end_line": 486, "start_col": 0, "start_line": 480 }
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)
{ "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) -> Alg.Alg a
Alg.Alg
[]
[]
[ "Alg.ops", "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Write", "Alg.handle_with", "FStar.List.Tot.Base.memP", "Alg.write_handler", "Alg.defh", "Alg.handler_op" ]
[]
false
true
false
false
false
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)
false
Alg.fst
Alg.write_handler
val write_handler (#a: Type) (#labs: ops) : handler_op Write a labs
val write_handler (#a: Type) (#labs: ops) : handler_op Write a labs
let write_handler (#a:Type) (#labs:ops) : handler_op Write a labs = fun s k -> handle_read k (read_handler s)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 45, "end_line": 477, "start_col": 0, "start_line": 474 }
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
{ "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_op Alg.Write a labs
Prims.Tot
[ "total" ]
[]
[ "Alg.ops", "Alg.op_inp", "Alg.Write", "Alg.op_out", "Alg.handle_read", "Alg.read_handler", "Alg.handler_op" ]
[]
false
false
false
false
false
let write_handler (#a: Type) (#labs: ops) : handler_op Write a labs =
fun s k -> handle_read k (read_handler s)
false
Alg.fst
Alg.fixup
val fixup: list baseop -> ops
val fixup: list baseop -> ops
let fixup : list baseop -> ops = List.Tot.map #baseop #op (fun x -> x)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 70, "end_line": 745, "start_col": 0, "start_line": 745 }
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 *)
{ "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.list Alg.baseop -> Alg.ops
Prims.Tot
[ "total" ]
[]
[ "FStar.List.Tot.Base.map", "Alg.baseop", "Alg.op" ]
[]
false
false
false
true
false
let fixup: list baseop -> ops =
List.Tot.map #baseop #op (fun x -> x)
false
Alg.fst
Alg.runST
val runST: #a: _ -> f: (unit -> Alg a ([Read; Write])) -> state -> a & state
val runST: #a: _ -> f: (unit -> Alg a ([Read; Write])) -> state -> a & state
let runST #a (f : unit -> Alg a (Read::Write::[])) : state -> a & state = fun s0 -> run (fun () -> catchST f s0)
{ "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": 432, "start_col": 0, "start_line": 429 }
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
{ "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) -> _: Alg.state -> a * Alg.state
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.Cons", "Alg.op", "Alg.Read", "Alg.Write", "Prims.Nil", "Alg.state", "Alg.run", "FStar.Pervasives.Native.tuple2", "Alg.catchST" ]
[]
false
false
false
false
false
let runST #a (f: (unit -> Alg a ([Read; Write]))) : state -> a & state =
fun s0 -> run (fun () -> catchST f s0)
false
Alg.fst
Alg.run_stexn
val run_stexn (#a: _) (f: (unit -> Alg a [Write; Raise; Read])) (s_0: state) : option (a & state)
val run_stexn (#a: _) (f: (unit -> Alg a [Write; Raise; Read])) (s_0: state) : option (a & state)
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))
{ "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": 447, "start_col": 0, "start_line": 446 }
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: *)
{ "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.option", "FStar.Pervasives.Native.tuple2", "Alg.catchE", "Alg.catchST" ]
[]
false
false
false
false
false
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))
false
Alg.fst
Alg.run_tree
val run_tree (#a: _) (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : option a & state
val run_tree (#a: _) (f: (unit -> Alg a [Raise; Write; Read])) (s0: state) : option a & state
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)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 54, "end_line": 570, "start_col": 0, "start_line": 565 }
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)
{ "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.handle_read'", "Alg.handle_write'", "Alg.handle_with", "Alg.handle_return", "Alg.handler_raise" ]
[]
false
false
false
false
false
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)
false
Alg.fst
Alg.lattice_get_repr
val lattice_get_repr: Prims.unit -> L.repr int [L.RD]
val lattice_get_repr: Prims.unit -> L.repr int [L.RD]
let lattice_get_repr () : L.repr int [L.RD] = reify (L.get ())
{ "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": 761, "start_col": 0, "start_line": 761 }
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
{ "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 Prims.int [Lattice.RD]
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Lattice.get", "Prims.int", "Lattice.repr", "Prims.Cons", "Lattice.eff_label", "Lattice.RD", "Prims.Nil" ]
[]
false
false
false
true
false
let lattice_get_repr () : L.repr int [L.RD] =
reify (L.get ())
false
Alg.fst
Alg.handle_one
val handle_one (#a: _) (#o: op) (#labs1: _) ($f: (unit -> Alg a (o :: labs1))) (h: handler_op o a labs1) : Alg a labs1
val handle_one (#a: _) (#o: op) (#labs1: _) ($f: (unit -> Alg a (o :: labs1))) (h: handler_op o a labs1) : Alg a labs1
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)
{ "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": 529, "start_col": 0, "start_line": 525 }
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)
{ "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) -> h: Alg.handler_op o a labs1 -> Alg.Alg a
Alg.Alg
[]
[]
[ "Alg.op", "Prims.list", "Prims.unit", "Prims.Cons", "Alg.handler_op", "Alg.handle_with", "Alg.widen_handler_1" ]
[]
false
true
false
false
false
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)
false
Alg.fst
Alg.handle_write'
val handle_write' (#a #labs: _) (f: (unit -> Alg a (Write :: labs))) : Alg a labs
val handle_write' (#a #labs: _) (f: (unit -> Alg a (Write :: labs))) : Alg a labs
let handle_write' #a #labs (f : unit -> Alg a (Write::labs)) : Alg a labs = handle_one f (fun s k -> handle_read' k s)
{ "file_name": "examples/layeredeffects/Alg.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 46, "end_line": 546, "start_col": 0, "start_line": 544 }
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)
{ "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) -> Alg.Alg a
Alg.Alg
[]
[]
[ "Prims.list", "Alg.op", "Prims.unit", "Prims.Cons", "Alg.Write", "Alg.handle_one", "Alg.op_inp", "Alg.op_out", "Alg.handle_read'" ]
[]
false
true
false
false
false
let handle_write' #a #labs (f: (unit -> Alg a (Write :: labs))) : Alg a labs =
handle_one f (fun s k -> handle_read' k s)
false