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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Target.fst | Target.has_output_type_exprs | val has_output_type_exprs (ds:list decl) : bool | val has_output_type_exprs (ds:list decl) : bool | let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 57,
"end_line": 87,
"start_col": 0,
"start_line": 86
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | ds: Prims.list Target.decl -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Prims.list",
"Target.decl",
"FStar.List.Tot.Base.existsb",
"FStar.Pervasives.Native.tuple2",
"Target.decl'",
"Target.decl_attributes",
"Target.uu___is_Output_type_expr",
"Prims.bool"
] | [] | false | false | false | true | false | let has_output_type_exprs (ds: list decl) : bool =
| List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds | false |
Target.fst | Target.print_range | val print_range (r: A.range) : string | val print_range (r: A.range) : string | let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 15,
"end_line": 184,
"start_col": 0,
"start_line": 177
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | r: Ast.range -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Ast.range",
"FStar.Printf.sprintf",
"Ast.__proj__Mkpos__item__filename",
"FStar.Pervasives.Native.fst",
"Ast.pos",
"Ast.__proj__Mkpos__item__line",
"Ast.__proj__Mkpos__item__col",
"FStar.Pervasives.Native.snd",
"Prims.string"
] | [] | false | false | false | true | false | let print_range (r: A.range) : string =
| let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.accessor_fldata | val accessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (accessor (gaccessor_fldata p sz)) | val accessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (accessor (gaccessor_fldata p sz)) | let accessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (accessor (gaccessor_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = slice_access_eq h (gaccessor_fldata p sz) input pos in
pos | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 5,
"end_line": 266,
"start_col": 0,
"start_line": 257
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos
inline_for_extraction
let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 ()
inline_for_extraction
let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata_strong s sz))
= jump_constant_size (parse_fldata_strong s sz) sz32 ()
let gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _))
= fun (input: bytes) -> (
let _ = match parse (parse_fldata p sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0
)
let gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _))
= gaccessor_prop_equiv (parse_fldata p sz) p (clens_id _) (gaccessor_fldata' p sz);
gaccessor_fldata' p sz | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
p:
LowParse.Spec.Base.parser k t
{ Mkparser_kind'?.parser_kind_subkind k ==
FStar.Pervasives.Native.Some LowParse.Spec.Base.ParserStrong } ->
sz: Prims.nat
-> LowParse.Low.Base.accessor (LowParse.Low.FLData.gaccessor_fldata p sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"Prims.eq2",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserStrong",
"Prims.nat",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt32.t",
"Prims.unit",
"LowParse.Low.Base.Spec.slice_access_eq",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata",
"LowParse.Low.Base.Spec.clens_id",
"LowParse.Low.FLData.gaccessor_fldata",
"FStar.Monotonic.HyperStack.mem",
"FStar.HyperStack.ST.get",
"LowParse.Low.Base.accessor"
] | [] | false | false | false | false | false | let accessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (accessor (gaccessor_fldata p sz)) =
| fun #rrel #rel input pos ->
let h = HST.get () in
[@@ inline_let ]let _ = slice_access_eq h (gaccessor_fldata p sz) input pos in
pos | false |
Hacl.Test.SHA3.fst | Hacl.Test.SHA3.test_sha3 | val test_sha3:
msg_len:size_t
-> msg:lbuffer uint8 msg_len
-> expected224:lbuffer uint8 28ul
-> expected256:lbuffer uint8 32ul
-> expected384:lbuffer uint8 48ul
-> expected512:lbuffer uint8 64ul
-> Stack unit
(requires fun h ->
live h msg /\ live h expected224 /\ live h expected256 /\
live h expected384 /\ live h expected512)
(ensures fun h0 r h1 -> True) | val test_sha3:
msg_len:size_t
-> msg:lbuffer uint8 msg_len
-> expected224:lbuffer uint8 28ul
-> expected256:lbuffer uint8 32ul
-> expected384:lbuffer uint8 48ul
-> expected512:lbuffer uint8 64ul
-> Stack unit
(requires fun h ->
live h msg /\ live h expected224 /\ live h expected256 /\
live h expected384 /\ live h expected512)
(ensures fun h0 r h1 -> True) | let test_sha3 msg_len msg expected224 expected256 expected384 expected512 =
push_frame();
let test224 = create 28ul (u8 0) in
let test256 = create 32ul (u8 0) in
let test384 = create 48ul (u8 0) in
let test512 = create 64ul (u8 0) in
sha3_224 test224 msg msg_len;
sha3_256 test256 msg msg_len;
sha3_384 test384 msg msg_len;
sha3_512 test512 msg msg_len;
if not (result_compare_display 28ul (to_const test224) (to_const expected224)) then C.exit 255l;
if not (result_compare_display 32ul (to_const test256) (to_const expected256)) then C.exit 255l;
if not (result_compare_display 48ul (to_const test384) (to_const expected384)) then C.exit 255l;
if not (result_compare_display 64ul (to_const test512) (to_const expected512)) then C.exit 255l;
pop_frame() | {
"file_name": "code/tests/Hacl.Test.SHA3.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 42,
"start_col": 0,
"start_line": 26
} | module Hacl.Test.SHA3
open FStar.HyperStack.All
open FStar.Mul
open Lib.IntTypes
open Lib.Buffer
open Lib.PrintBuffer
open Hacl.SHA3
#reset-options "--z3rlimit 100 --fuel 0 --ifuel 0"
val test_sha3:
msg_len:size_t
-> msg:lbuffer uint8 msg_len
-> expected224:lbuffer uint8 28ul
-> expected256:lbuffer uint8 32ul
-> expected384:lbuffer uint8 48ul
-> expected512:lbuffer uint8 64ul
-> Stack unit
(requires fun h ->
live h msg /\ live h expected224 /\ live h expected256 /\
live h expected384 /\ live h expected512)
(ensures fun h0 r h1 -> True) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Lib.RawIntTypes.fsti.checked",
"Lib.PrintBuffer.fsti.checked",
"Lib.IntTypes.fsti.checked",
"Lib.Buffer.fsti.checked",
"Hacl.SHA3.fst.checked",
"FStar.UInt32.fsti.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.List.Tot.fst.checked",
"FStar.Int32.fsti.checked",
"FStar.HyperStack.All.fst.checked",
"C.String.fsti.checked",
"C.fst.checked"
],
"interface_file": false,
"source_file": "Hacl.Test.SHA3.fst"
} | [
{
"abbrev": false,
"full_module": "Hacl.SHA3",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.PrintBuffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.HyperStack.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl.Test",
"short_module": null
},
{
"abbrev": false,
"full_module": "Hacl.Test",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 100,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
msg_len: Lib.IntTypes.size_t ->
msg: Lib.Buffer.lbuffer Lib.IntTypes.uint8 msg_len ->
expected224: Lib.Buffer.lbuffer Lib.IntTypes.uint8 28ul ->
expected256: Lib.Buffer.lbuffer Lib.IntTypes.uint8 32ul ->
expected384: Lib.Buffer.lbuffer Lib.IntTypes.uint8 48ul ->
expected512: Lib.Buffer.lbuffer Lib.IntTypes.uint8 64ul
-> FStar.HyperStack.ST.Stack Prims.unit | FStar.HyperStack.ST.Stack | [] | [] | [
"Lib.IntTypes.size_t",
"Lib.Buffer.lbuffer",
"Lib.IntTypes.uint8",
"FStar.UInt32.__uint_to_t",
"FStar.HyperStack.ST.pop_frame",
"Prims.unit",
"C.exit",
"FStar.Int32.__int_to_t",
"Prims.bool",
"Prims.op_Negation",
"Lib.PrintBuffer.result_compare_display",
"Lib.Buffer.to_const",
"Lib.Buffer.MUT",
"Hacl.SHA3.sha3_512",
"Hacl.SHA3.sha3_384",
"Hacl.SHA3.sha3_256",
"Hacl.SHA3.sha3_224",
"Lib.Buffer.lbuffer_t",
"Lib.IntTypes.int_t",
"Lib.IntTypes.U8",
"Lib.IntTypes.SEC",
"FStar.UInt32.uint_to_t",
"FStar.UInt32.t",
"Lib.Buffer.create",
"Lib.IntTypes.u8",
"FStar.HyperStack.ST.push_frame"
] | [] | false | true | false | false | false | let test_sha3 msg_len msg expected224 expected256 expected384 expected512 =
| push_frame ();
let test224 = create 28ul (u8 0) in
let test256 = create 32ul (u8 0) in
let test384 = create 48ul (u8 0) in
let test512 = create 64ul (u8 0) in
sha3_224 test224 msg msg_len;
sha3_256 test256 msg msg_len;
sha3_384 test384 msg msg_len;
sha3_512 test512 msg msg_len;
if not (result_compare_display 28ul (to_const test224) (to_const expected224)) then C.exit 255l;
if not (result_compare_display 32ul (to_const test256) (to_const expected256)) then C.exit 255l;
if not (result_compare_display 48ul (to_const test384) (to_const expected384)) then C.exit 255l;
if not (result_compare_display 64ul (to_const test512) (to_const expected512)) then C.exit 255l;
pop_frame () | false |
Target.fst | Target.error_handler_decl | val error_handler_decl : decl | val error_handler_decl : decl | let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 18,
"end_line": 131,
"start_col": 0,
"start_line": 122
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | Target.decl | Prims.Tot | [
"total"
] | [] | [
"FStar.Pervasives.Native.Mktuple2",
"Target.decl'",
"Target.decl_attributes",
"Target.default_attrs",
"Target.Assumption",
"Ast.ident",
"Target.typ",
"Target.error_handler_name",
"Target.T_app",
"Ast.KindSpec",
"Prims.Nil",
"FStar.Pervasives.either",
"Target.expr",
"Ast.with_meta_t",
"Ast.ident'",
"Ast.with_range",
"Ast.dummy_range",
"Ast.Mkident'",
"FStar.Pervasives.Native.Some",
"Prims.string"
] | [] | false | false | false | true | false | let error_handler_decl =
| let open A in
let error_handler_id' = { modul_name = Some "EverParse3d.Actions.Base"; name = "error_handler" } in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs | false |
Target.fst | Target.has_extern_types | val has_extern_types (ds:list decl) : bool | val has_extern_types (ds:list decl) : bool | let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 52,
"end_line": 90,
"start_col": 0,
"start_line": 89
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | ds: Prims.list Target.decl -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Prims.list",
"Target.decl",
"FStar.List.Tot.Base.existsb",
"FStar.Pervasives.Native.tuple2",
"Target.decl'",
"Target.decl_attributes",
"Target.uu___is_Extern_type",
"Prims.bool"
] | [] | false | false | false | true | false | let has_extern_types (ds: list decl) : bool =
| List.Tot.existsb (fun (d, _) -> Extern_type? d) ds | false |
Target.fst | Target.default_attrs | val default_attrs : Target.decl_attributes | let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
} | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 1,
"end_line": 111,
"start_col": 0,
"start_line": 105
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | Target.decl_attributes | Prims.Tot | [
"total"
] | [] | [
"Target.Mkdecl_attributes",
"Prims.Nil",
"Prims.string"
] | [] | false | false | false | true | false | let default_attrs =
| { is_hoisted = false; is_if_def = false; is_exported = false; should_inline = false; comments = [] } | false |
|
Target.fst | Target.has_external_api | val has_external_api (ds:list decl) : bool | val has_external_api (ds:list decl) : bool | let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 25,
"end_line": 102,
"start_col": 0,
"start_line": 98
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | ds: Prims.list Target.decl -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Prims.list",
"Target.decl",
"Prims.op_BarBar",
"Target.has_output_type_exprs",
"Target.has_extern_types",
"Target.has_extern_functions",
"Target.has_extern_probes",
"Prims.bool"
] | [] | false | false | false | true | false | let has_external_api (ds: list decl) : bool =
| has_output_type_exprs ds || has_extern_types ds || has_extern_functions ds || has_extern_probes ds | false |
Target.fst | Target.print_maybe_qualified_ident | val print_maybe_qualified_ident (mname:string) (i:A.ident) : ML string | val print_maybe_qualified_ident (mname:string) (i:A.ident) : ML string | let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 68,
"end_line": 153,
"start_col": 0,
"start_line": 152
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> i: Ast.ident -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Ast.ident",
"FStar.Printf.sprintf",
"Target.maybe_mname_prefix",
"Target.print_ident"
] | [] | false | true | false | false | false | let print_maybe_qualified_ident (mname: string) (i: A.ident) =
| Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i) | false |
Target.fst | Target.arith_op | val arith_op : o: Target.op -> Prims.bool | let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 199,
"start_col": 0,
"start_line": 186
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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: Target.op -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Target.op",
"Ast.integer_type",
"Prims.bool"
] | [] | false | false | false | true | false | let arith_op (o: op) =
| match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false | false |
|
Target.fst | Target.is_infix | val is_infix : _: Target.op -> Prims.bool | let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 264,
"start_col": 0,
"start_line": 258
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | _: Target.op -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Target.op",
"Prims.bool"
] | [] | false | false | false | true | false | let is_infix =
| function
| Eq | Neq | And | Or -> true
| _ -> false | false |
|
Steel.ST.C.Types.UserStruct.fsti | Steel.ST.C.Types.UserStruct.set_snoc | val set_snoc (#t: eqtype) (q: FStar.Set.set t) (a: t)
: Pure (nonempty_set t)
(requires True)
(ensures
(fun s ->
(forall (x: t). {:pattern FStar.Set.mem x s}
FStar.Set.mem x s == (x = a || FStar.Set.mem x q)))) | val set_snoc (#t: eqtype) (q: FStar.Set.set t) (a: t)
: Pure (nonempty_set t)
(requires True)
(ensures
(fun s ->
(forall (x: t). {:pattern FStar.Set.mem x s}
FStar.Set.mem x s == (x = a || FStar.Set.mem x q)))) | let set_snoc // for associativity reasons
(#t: eqtype) (q: FStar.Set.set t) (a: t) : Pure (nonempty_set t)
(requires True)
(ensures (fun s ->
(forall (x: t). {:pattern FStar.Set.mem x s} FStar.Set.mem x s == (x = a || FStar.Set.mem x q))
))
= q `FStar.Set.union` FStar.Set.singleton a | {
"file_name": "lib/steel/c/Steel.ST.C.Types.UserStruct.fsti",
"git_rev": "f984200f79bdc452374ae994a5ca837496476c41",
"git_url": "https://github.com/FStarLang/steel.git",
"project_name": "steel"
} | {
"end_col": 43,
"end_line": 29,
"start_col": 0,
"start_line": 23
} | module Steel.ST.C.Types.UserStruct
open Steel.ST.Util
open Steel.ST.C.Types.Struct.Aux
module Set = FStar.Set
(* This library allows the user to define their own struct type, with
a constructor from field values, and a destructor to field values for
each field. This may be necessary for recursive structs *)
let set_def
(#t: eqtype)
(s: FStar.Set.set t)
(x: t)
: Tot bool
= FStar.Set.mem x s
noextract
let nonempty_set (t: eqtype) =
(s: Set.set t { exists x . set_def s x == true }) | {
"checked_file": "/",
"dependencies": [
"Steel.ST.Util.fsti.checked",
"Steel.ST.C.Types.Struct.Aux.fsti.checked",
"Steel.FractionalPermission.fst.checked",
"prims.fst.checked",
"FStar.Set.fsti.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Ghost.fsti.checked",
"FStar.Classical.fsti.checked"
],
"interface_file": false,
"source_file": "Steel.ST.C.Types.UserStruct.fsti"
} | [
{
"abbrev": true,
"full_module": "FStar.Set",
"short_module": "Set"
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types.Struct.Aux",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.Util",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types",
"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 | q: FStar.Set.set t -> a: t -> Prims.Pure (Steel.ST.C.Types.UserStruct.nonempty_set t) | Prims.Pure | [] | [] | [
"Prims.eqtype",
"FStar.Set.set",
"FStar.Set.union",
"FStar.Set.singleton",
"Steel.ST.C.Types.UserStruct.nonempty_set",
"Prims.l_True",
"Prims.l_Forall",
"Prims.eq2",
"Prims.bool",
"FStar.Set.mem",
"Prims.op_BarBar",
"Prims.op_Equality"
] | [] | false | false | false | false | false | let set_snoc (#t: eqtype) (q: FStar.Set.set t) (a: t)
: Pure (nonempty_set t)
(requires True)
(ensures
(fun s ->
(forall (x: t). {:pattern FStar.Set.mem x s}
FStar.Set.mem x s == (x = a || FStar.Set.mem x q)))) =
| q `FStar.Set.union` (FStar.Set.singleton a) | false |
Target.fst | Target.print_arith_op_range | val print_arith_op_range: Prims.unit -> ML bool | val print_arith_op_range: Prims.unit -> ML bool | let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0 | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 52,
"end_line": 216,
"start_col": 0,
"start_line": 215
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | _: Prims.unit -> FStar.All.ML Prims.bool | FStar.All.ML | [
"ml"
] | [] | [
"Prims.unit",
"Prims.op_Equality",
"Prims.int",
"Prims.bool",
"FStar.List.Tot.Base.length",
"FStar.Pervasives.Native.tuple2",
"Prims.string",
"Prims.list",
"Options.get_equate_types_list"
] | [] | false | true | false | false | false | let print_arith_op_range () : ML bool =
| List.length (Options.get_equate_types_list ()) = 0 | false |
Lib.Sequence.fsti | Lib.Sequence.last | val last : len: Prims.nat -> blocksize: Lib.IntTypes.size_pos -> Type0 | let last (len:nat) (blocksize:size_pos) = i:nat{i = len / blocksize} | {
"file_name": "lib/Lib.Sequence.fsti",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 69,
"end_line": 437,
"start_col": 0,
"start_line": 437
} | module Lib.Sequence
open FStar.Mul
open Lib.IntTypes
#set-options "--z3rlimit 30 --max_fuel 0 --max_ifuel 0 --using_facts_from '-* +Prims +FStar.Math.Lemmas +FStar.Seq +Lib.IntTypes +Lib.Sequence'"
/// Variable length Sequences, derived from FStar.Seq
(* This is the type of unbounded sequences.
Use this only when dealing with, say, user input whose length is unbounded.
As far as possible use the API for bounded sequences defined later in this file.*)
(** Definition of a Sequence *)
let seq (a:Type0) = Seq.seq a
(** Length of a Sequence *)
let length (#a:Type0) (s:seq a) : nat = Seq.length s
/// Fixed length Sequences
(* This is the type of bounded sequences.
Use this as much as possible.
It adds additional length checks that you'd have to prove in the implementation otherwise *)
(** Definition of a fixed-length Sequence *)
let lseq (a:Type0) (len:size_nat) = s:seq a{Seq.length s == len}
let to_seq (#a:Type0) (#len:size_nat) (l:lseq a len) : seq a = l
let to_lseq (#a:Type0) (s:seq a{length s <= max_size_t}) : l:lseq a (length s){l == s} = s
(* If you want to prove your code with an abstract lseq use the following: *)
// val lseq: a:Type0 -> len:size_nat -> Type0
// val to_seq: #a:Type0 -> #len:size_nat -> lseq a len -> s:seq a{length s == len}
// val to_lseq: #a:Type0 -> s:seq a{length s <= max_size_t} -> lseq a (length s)
val index:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> i:size_nat{i < len} ->
Tot (r:a{r == Seq.index (to_seq s) i})
(** Creation of a fixed-length Sequence from an initial value *)
val create:
#a:Type
-> len:size_nat
-> init:a ->
Tot (s:lseq a len{to_seq s == Seq.create len init /\ (forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init)})
(** Concatenate sequences: use with care, may make implementation hard to verify *)
val concat:
#a:Type
-> #len0:size_nat
-> #len1:size_nat{len0 + len1 <= max_size_t}
-> s0:lseq a len0
-> s1:lseq a len1 ->
Tot (s2:lseq a (len0 + len1){to_seq s2 == Seq.append (to_seq s0) (to_seq s1)})
let ( @| ) #a #len0 #len1 s0 s1 = concat #a #len0 #len1 s0 s1
(** Conversion of a Sequence to a list *)
val to_list:
#a:Type
-> s:seq a ->
Tot (l:list a{List.Tot.length l = length s /\ l == Seq.seq_to_list s})
(** Creation of a fixed-length Sequence from a list of values *)
val of_list:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t} ->
Tot (s:lseq a (List.Tot.length l){to_seq s == Seq.seq_of_list l})
val of_list_index:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t}
-> i:nat{i < List.Tot.length l} ->
Lemma (index (of_list l) i == List.Tot.index l i)
[SMTPat (index (of_list l) i)]
val equal (#a:Type) (#len:size_nat) (s1:lseq a len) (s2:lseq a len) : Type0
val eq_intro: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires forall i. {:pattern index s1 i; index s2 i} index s1 i == index s2 i)
(ensures equal s1 s2)
[SMTPat (equal s1 s2)]
val eq_elim: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires equal s1 s2)
(ensures s1 == s2)
[SMTPat (equal s1 s2)]
(* Alias for creation from a list *)
unfold let createL #a l = of_list #a l
(** Updating an element of a fixed-length Sequence *)
val upd:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> n:size_nat{n < len}
-> x:a ->
Tot (o:lseq a len{to_seq o == Seq.upd (to_seq s) n x /\ index o n == x /\ (forall (i:size_nat).
{:pattern (index s i)} (i < len /\ i <> n) ==> index o i == index s i)})
(** Membership of an element to a fixed-length Sequence *)
val member: #a:eqtype -> #len: size_nat -> a -> lseq a len -> Tot bool
(** Operator for accessing an element of a fixed-length Sequence *)
unfold
let op_String_Access #a #len = index #a #len
(** Operator for updating an element of a fixed-length Sequence *)
unfold
let op_String_Assignment #a #len = upd #a #len
(** Selecting a subset of a fixed-length Sequence *)
val sub:
#a:Type
-> #len:size_nat
-> s1:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len} ->
Tot (s2:lseq a n{to_seq s2 == Seq.slice (to_seq s1) start (start + n) /\
(forall (k:nat{k < n}). {:pattern (index s2 k)} index s2 k == index s1 (start + k))})
(** Selecting a subset of a fixed-length Sequence *)
let slice
(#a:Type)
(#len:size_nat)
(s1:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
=
sub #a s1 start (fin - start)
(** Updating a sub-Sequence from another fixed-length Sequence *)
val update_sub:
#a:Type
-> #len:size_nat
-> i:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> x:lseq a n ->
Tot (o:lseq a len{sub o start n == x /\
(forall (k:nat{(0 <= k /\ k < start) \/ (start + n <= k /\ k < len)}).
{:pattern (index o k)} index o k == index i k)})
(** Lemma regarding updating a sub-Sequence with another Sequence *)
val lemma_update_sub:
#a:Type
-> #len:size_nat
-> dst:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> src:lseq a n
-> res:lseq a len ->
Lemma
(requires
sub res 0 start == sub dst 0 start /\
sub res start n == src /\
sub res (start + n) (len - start - n) ==
sub dst (start + n) (len - start - n))
(ensures
res == update_sub dst start n src)
val lemma_concat2:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> s:lseq a (len0 + len1) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1)
(ensures s == concat s0 s1)
val lemma_concat3:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> len2:size_nat{len0 + len1 + len2 <= max_size_t}
-> s2:lseq a len2
-> s:lseq a (len0 + len1 + len2) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1 /\
sub s (len0 + len1) len2 == s2)
(ensures s == concat (concat s0 s1) s2)
(** Updating a sub-Sequence from another fixed-length Sequence *)
let update_slice
(#a:Type)
(#len:size_nat)
(i:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
(upd:lseq a (fin - start))
=
update_sub #a i start (fin - start) upd
(** Creation of a fixed-length Sequence from an initialization function *)
val createi: #a:Type
-> len:size_nat
-> init:(i:nat{i < len} -> a) ->
Tot (s:lseq a len{(forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init i)})
(** Mapi function for fixed-length Sequences *)
val mapi:#a:Type -> #b:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f i s1.[i])})
(** Map function for fixed-length Sequences *)
val map:#a:Type -> #b:Type -> #len:size_nat
-> f:(a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f s1.[i])})
(** Map2i function for fixed-length Sequences *)
val map2i:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f i s1.[i] s2.[i])})
(** Map2 function for fixed-length Sequences *)
val map2:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f s1.[i] s2.[i])})
(** Forall function for fixed-length Sequences *)
val for_all:#a:Type -> #len:size_nat -> (a -> Tot bool) -> lseq a len -> bool
(** Forall2 function for fixed-length Sequences *)
val for_all2:#a:Type -> #b:Type -> #len:size_nat
-> (a -> b -> Tot bool)
-> s1:lseq a len
-> s2:lseq b len ->
Tot bool
val repeati_blocks:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(i:nat{i < length inp / blocksize} -> lseq a blocksize -> b -> b)
-> l:(i:nat{i == length inp / blocksize} -> len:size_nat{len == length inp % blocksize} -> s:lseq a len -> b -> b)
-> init:b ->
Tot b
let repeat_blocks_f
(#a:Type0)
(#b:Type0)
(bs:size_nat{bs > 0})
(inp:seq a)
(f:(lseq a bs -> b -> b))
(nb:nat{nb == length inp / bs})
(i:nat{i < nb})
(acc:b) : b
=
assert ((i+1) * bs <= nb * bs);
let block = Seq.slice inp (i * bs) (i * bs + bs) in
f block acc
val repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(lseq a blocksize -> b -> b)
-> l:(len:nat{len < blocksize} -> s:lseq a len -> b -> c)
-> init:b ->
Tot c
val lemma_repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> bs:size_pos
-> inp:seq a
-> f:(lseq a bs -> b -> b)
-> l:(len:nat{len < bs} -> s:lseq a len -> b -> c)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
let rem = len % bs in
let acc = Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init in
let last = Seq.slice inp (nb * bs) len in
let acc = l rem last acc in
repeat_blocks #a #b bs inp f l init == acc)
val repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a{length inp % blocksize = 0}
-> f:(lseq a blocksize -> b -> b)
-> init:b ->
Tot b
val lemma_repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> bs:size_pos
-> inp:seq a{length inp % bs = 0}
-> f:(lseq a bs -> b -> b)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
repeat_blocks_multi #a #b bs inp f init ==
Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init)
(** Generates `n` blocks of length `len` by iteratively applying a function with an accumulator *)
val generate_blocks:
#t:Type0
-> len:size_nat
-> max:nat
-> n:nat{n <= max}
-> a:(i:nat{i <= max} -> Type)
-> f:(i:nat{i < max} -> a i -> a (i + 1) & s:seq t{length s == len})
-> init:a 0 ->
Tot (a n & s:seq t{length s == n * len})
(** Generates `n` blocks of length `len` by iteratively applying a function without an accumulator *)
val generate_blocks_simple:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> f:(i:nat{i < max} -> lseq a blocksize) ->
Tot (s:seq a{length s == n * blocksize})
(** The following functions allow us to bridge between unbounded and bounded sequences *)
val div_interval: b:pos -> n:int -> i:int -> Lemma
(requires n * b <= i /\ i < (n + 1) * b)
(ensures i / b = n)
val mod_interval_lt: b:pos -> n:int -> i:int -> j:int -> Lemma
(requires n * b <= i /\ i < j /\ j < (n + 1) * b)
(ensures i % b < j % b)
val div_mul_lt: b:pos -> a:int -> n:int -> Lemma
(requires a < n * b)
(ensures a / b < n)
val mod_div_lt: b:pos -> i:int -> j:int -> Lemma
(requires (j / b) * b <= i /\ i < j)
(ensures i % b < j % b)
val div_mul_l: a:int -> b:int -> c:pos -> d:pos -> Lemma
(requires a / d = b / d)
(ensures a / (c * d) = b / (c * d))
let map_blocks_a (a:Type) (bs:size_nat) (max:nat) (i:nat{i <= max}) = s:seq a{length s == i * bs}
let map_blocks_f
(#a:Type)
(bs:size_nat{bs > 0})
(max:nat)
(inp:seq a{length inp == max * bs})
(f:(i:nat{i < max} -> lseq a bs -> lseq a bs))
(i:nat{i < max})
(acc:map_blocks_a a bs max i) : map_blocks_a a bs max (i + 1)
=
Math.Lemmas.lemma_mult_le_right bs (i+1) max;
let block = Seq.slice inp (i*bs) ((i+1)*bs) in
Seq.append acc (f i block)
val map_blocks_multi:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> inp:seq a{length inp == max * blocksize}
-> f:(i:nat{i < max} -> lseq a blocksize -> lseq a blocksize) ->
Tot (out:seq a {length out == n * blocksize})
val lemma_map_blocks_multi:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> inp:seq a{length inp == max * blocksize}
-> f:(i:nat{i < max} -> lseq a blocksize -> lseq a blocksize)
-> Lemma
(map_blocks_multi #a blocksize max n inp f ==
LoopCombinators.repeat_gen n (map_blocks_a a blocksize max) (map_blocks_f #a blocksize max inp f) Seq.empty)
#restart-solver
val index_map_blocks_multi:
#a:Type0
-> bs:size_pos
-> max:pos
-> n:pos{n <= max}
-> inp:seq a{length inp == max * bs}
-> f:(i:nat{i < max} -> lseq a bs -> lseq a bs)
-> i:nat{i < n * bs}
-> Lemma (
div_mul_lt bs i n;
let j = i / bs in
let block: lseq a bs = Seq.slice inp (j * bs) ((j + 1) * bs) in
Seq.index (map_blocks_multi bs max n inp f) i == Seq.index (f j block) (i % bs))
(* A full block index *)
unfold
let block (len:nat) (blocksize:size_pos) = i:nat{i < len / blocksize}
(* Index of last (incomplete) block *) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.List.Tot.fst.checked"
],
"interface_file": false,
"source_file": "Lib.Sequence.fsti"
} | [
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"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": 30,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | len: Prims.nat -> blocksize: Lib.IntTypes.size_pos -> Type0 | Prims.Tot | [
"total"
] | [] | [
"Prims.nat",
"Lib.IntTypes.size_pos",
"Prims.b2t",
"Prims.op_Equality",
"Prims.int",
"Prims.op_Division"
] | [] | false | false | false | true | true | let last (len: nat) (blocksize: size_pos) =
| i: nat{i = len / blocksize} | false |
|
LowParse.Low.FLData.fst | LowParse.Low.FLData.jump_fldata | val jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (jumper (parse_fldata p sz)) | val jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (jumper (parse_fldata p sz)) | let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 () | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 48,
"end_line": 217,
"start_col": 0,
"start_line": 210
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | p: LowParse.Spec.Base.parser k t -> sz: Prims.nat -> sz32: FStar.UInt32.t{FStar.UInt32.v sz32 == sz}
-> LowParse.Low.Base.jumper (LowParse.Spec.FLData.parse_fldata p sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"Prims.nat",
"FStar.UInt32.t",
"Prims.eq2",
"Prims.int",
"Prims.l_or",
"FStar.UInt.size",
"FStar.UInt32.n",
"Prims.b2t",
"Prims.op_GreaterThanOrEqual",
"FStar.UInt32.v",
"LowParse.Low.Base.jump_constant_size",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata",
"LowParse.Low.Base.jumper"
] | [] | false | false | false | false | false | let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (jumper (parse_fldata p sz)) =
| jump_constant_size (parse_fldata p sz) sz32 () | false |
Lib.Sequence.fsti | Lib.Sequence.repeat_blocks_f | val repeat_blocks_f
(#a #b: Type0)
(bs: size_nat{bs > 0})
(inp: seq a)
(f: (lseq a bs -> b -> b))
(nb: nat{nb == length inp / bs})
(i: nat{i < nb})
(acc: b)
: b | val repeat_blocks_f
(#a #b: Type0)
(bs: size_nat{bs > 0})
(inp: seq a)
(f: (lseq a bs -> b -> b))
(nb: nat{nb == length inp / bs})
(i: nat{i < nb})
(acc: b)
: b | let repeat_blocks_f
(#a:Type0)
(#b:Type0)
(bs:size_nat{bs > 0})
(inp:seq a)
(f:(lseq a bs -> b -> b))
(nb:nat{nb == length inp / bs})
(i:nat{i < nb})
(acc:b) : b
=
assert ((i+1) * bs <= nb * bs);
let block = Seq.slice inp (i * bs) (i * bs + bs) in
f block acc | {
"file_name": "lib/Lib.Sequence.fsti",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 13,
"end_line": 280,
"start_col": 0,
"start_line": 268
} | module Lib.Sequence
open FStar.Mul
open Lib.IntTypes
#set-options "--z3rlimit 30 --max_fuel 0 --max_ifuel 0 --using_facts_from '-* +Prims +FStar.Math.Lemmas +FStar.Seq +Lib.IntTypes +Lib.Sequence'"
/// Variable length Sequences, derived from FStar.Seq
(* This is the type of unbounded sequences.
Use this only when dealing with, say, user input whose length is unbounded.
As far as possible use the API for bounded sequences defined later in this file.*)
(** Definition of a Sequence *)
let seq (a:Type0) = Seq.seq a
(** Length of a Sequence *)
let length (#a:Type0) (s:seq a) : nat = Seq.length s
/// Fixed length Sequences
(* This is the type of bounded sequences.
Use this as much as possible.
It adds additional length checks that you'd have to prove in the implementation otherwise *)
(** Definition of a fixed-length Sequence *)
let lseq (a:Type0) (len:size_nat) = s:seq a{Seq.length s == len}
let to_seq (#a:Type0) (#len:size_nat) (l:lseq a len) : seq a = l
let to_lseq (#a:Type0) (s:seq a{length s <= max_size_t}) : l:lseq a (length s){l == s} = s
(* If you want to prove your code with an abstract lseq use the following: *)
// val lseq: a:Type0 -> len:size_nat -> Type0
// val to_seq: #a:Type0 -> #len:size_nat -> lseq a len -> s:seq a{length s == len}
// val to_lseq: #a:Type0 -> s:seq a{length s <= max_size_t} -> lseq a (length s)
val index:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> i:size_nat{i < len} ->
Tot (r:a{r == Seq.index (to_seq s) i})
(** Creation of a fixed-length Sequence from an initial value *)
val create:
#a:Type
-> len:size_nat
-> init:a ->
Tot (s:lseq a len{to_seq s == Seq.create len init /\ (forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init)})
(** Concatenate sequences: use with care, may make implementation hard to verify *)
val concat:
#a:Type
-> #len0:size_nat
-> #len1:size_nat{len0 + len1 <= max_size_t}
-> s0:lseq a len0
-> s1:lseq a len1 ->
Tot (s2:lseq a (len0 + len1){to_seq s2 == Seq.append (to_seq s0) (to_seq s1)})
let ( @| ) #a #len0 #len1 s0 s1 = concat #a #len0 #len1 s0 s1
(** Conversion of a Sequence to a list *)
val to_list:
#a:Type
-> s:seq a ->
Tot (l:list a{List.Tot.length l = length s /\ l == Seq.seq_to_list s})
(** Creation of a fixed-length Sequence from a list of values *)
val of_list:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t} ->
Tot (s:lseq a (List.Tot.length l){to_seq s == Seq.seq_of_list l})
val of_list_index:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t}
-> i:nat{i < List.Tot.length l} ->
Lemma (index (of_list l) i == List.Tot.index l i)
[SMTPat (index (of_list l) i)]
val equal (#a:Type) (#len:size_nat) (s1:lseq a len) (s2:lseq a len) : Type0
val eq_intro: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires forall i. {:pattern index s1 i; index s2 i} index s1 i == index s2 i)
(ensures equal s1 s2)
[SMTPat (equal s1 s2)]
val eq_elim: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires equal s1 s2)
(ensures s1 == s2)
[SMTPat (equal s1 s2)]
(* Alias for creation from a list *)
unfold let createL #a l = of_list #a l
(** Updating an element of a fixed-length Sequence *)
val upd:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> n:size_nat{n < len}
-> x:a ->
Tot (o:lseq a len{to_seq o == Seq.upd (to_seq s) n x /\ index o n == x /\ (forall (i:size_nat).
{:pattern (index s i)} (i < len /\ i <> n) ==> index o i == index s i)})
(** Membership of an element to a fixed-length Sequence *)
val member: #a:eqtype -> #len: size_nat -> a -> lseq a len -> Tot bool
(** Operator for accessing an element of a fixed-length Sequence *)
unfold
let op_String_Access #a #len = index #a #len
(** Operator for updating an element of a fixed-length Sequence *)
unfold
let op_String_Assignment #a #len = upd #a #len
(** Selecting a subset of a fixed-length Sequence *)
val sub:
#a:Type
-> #len:size_nat
-> s1:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len} ->
Tot (s2:lseq a n{to_seq s2 == Seq.slice (to_seq s1) start (start + n) /\
(forall (k:nat{k < n}). {:pattern (index s2 k)} index s2 k == index s1 (start + k))})
(** Selecting a subset of a fixed-length Sequence *)
let slice
(#a:Type)
(#len:size_nat)
(s1:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
=
sub #a s1 start (fin - start)
(** Updating a sub-Sequence from another fixed-length Sequence *)
val update_sub:
#a:Type
-> #len:size_nat
-> i:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> x:lseq a n ->
Tot (o:lseq a len{sub o start n == x /\
(forall (k:nat{(0 <= k /\ k < start) \/ (start + n <= k /\ k < len)}).
{:pattern (index o k)} index o k == index i k)})
(** Lemma regarding updating a sub-Sequence with another Sequence *)
val lemma_update_sub:
#a:Type
-> #len:size_nat
-> dst:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> src:lseq a n
-> res:lseq a len ->
Lemma
(requires
sub res 0 start == sub dst 0 start /\
sub res start n == src /\
sub res (start + n) (len - start - n) ==
sub dst (start + n) (len - start - n))
(ensures
res == update_sub dst start n src)
val lemma_concat2:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> s:lseq a (len0 + len1) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1)
(ensures s == concat s0 s1)
val lemma_concat3:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> len2:size_nat{len0 + len1 + len2 <= max_size_t}
-> s2:lseq a len2
-> s:lseq a (len0 + len1 + len2) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1 /\
sub s (len0 + len1) len2 == s2)
(ensures s == concat (concat s0 s1) s2)
(** Updating a sub-Sequence from another fixed-length Sequence *)
let update_slice
(#a:Type)
(#len:size_nat)
(i:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
(upd:lseq a (fin - start))
=
update_sub #a i start (fin - start) upd
(** Creation of a fixed-length Sequence from an initialization function *)
val createi: #a:Type
-> len:size_nat
-> init:(i:nat{i < len} -> a) ->
Tot (s:lseq a len{(forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init i)})
(** Mapi function for fixed-length Sequences *)
val mapi:#a:Type -> #b:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f i s1.[i])})
(** Map function for fixed-length Sequences *)
val map:#a:Type -> #b:Type -> #len:size_nat
-> f:(a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f s1.[i])})
(** Map2i function for fixed-length Sequences *)
val map2i:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f i s1.[i] s2.[i])})
(** Map2 function for fixed-length Sequences *)
val map2:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f s1.[i] s2.[i])})
(** Forall function for fixed-length Sequences *)
val for_all:#a:Type -> #len:size_nat -> (a -> Tot bool) -> lseq a len -> bool
(** Forall2 function for fixed-length Sequences *)
val for_all2:#a:Type -> #b:Type -> #len:size_nat
-> (a -> b -> Tot bool)
-> s1:lseq a len
-> s2:lseq b len ->
Tot bool
val repeati_blocks:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(i:nat{i < length inp / blocksize} -> lseq a blocksize -> b -> b)
-> l:(i:nat{i == length inp / blocksize} -> len:size_nat{len == length inp % blocksize} -> s:lseq a len -> b -> b)
-> init:b ->
Tot b | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.List.Tot.fst.checked"
],
"interface_file": false,
"source_file": "Lib.Sequence.fsti"
} | [
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"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": 30,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
bs: Lib.IntTypes.size_nat{bs > 0} ->
inp: Lib.Sequence.seq a ->
f: (_: Lib.Sequence.lseq a bs -> _: b -> b) ->
nb: Prims.nat{nb == Lib.Sequence.length inp / bs} ->
i: Prims.nat{i < nb} ->
acc: b
-> b | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_GreaterThan",
"Lib.Sequence.seq",
"Lib.Sequence.lseq",
"Prims.nat",
"Prims.eq2",
"Prims.int",
"Prims.op_Division",
"Lib.Sequence.length",
"Prims.op_LessThan",
"FStar.Seq.Base.seq",
"FStar.Seq.Base.slice",
"FStar.Mul.op_Star",
"Prims.op_Addition",
"Prims.unit",
"Prims._assert",
"Prims.op_LessThanOrEqual"
] | [] | false | false | false | false | false | let repeat_blocks_f
(#a #b: Type0)
(bs: size_nat{bs > 0})
(inp: seq a)
(f: (lseq a bs -> b -> b))
(nb: nat{nb == length inp / bs})
(i: nat{i < nb})
(acc: b)
: b =
| assert ((i + 1) * bs <= nb * bs);
let block = Seq.slice inp (i * bs) (i * bs + bs) in
f block acc | false |
Target.fst | Target.print_op | val print_op : o: Target.op -> FStar.All.ALL Prims.string | let print_op = print_op_with_range None | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 39,
"end_line": 305,
"start_col": 0,
"start_line": 305
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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: Target.op -> FStar.All.ALL Prims.string | FStar.All.ALL | [] | [] | [
"Target.print_op_with_range",
"FStar.Pervasives.Native.None",
"Ast.range"
] | [] | false | true | false | false | false | let print_op =
| print_op_with_range None | false |
|
Steel.ST.C.Types.UserStruct.fsti | Steel.ST.C.Types.UserStruct.nonempty_set_nonempty_type | val nonempty_set_nonempty_type (x: string) (s: Set.set string)
: Lemma (requires (x `Set.mem` s)) (ensures (exists (x: field_t s). True)) | val nonempty_set_nonempty_type (x: string) (s: Set.set string)
: Lemma (requires (x `Set.mem` s)) (ensures (exists (x: field_t s). True)) | let nonempty_set_nonempty_type (x: string) (s: Set.set string) : Lemma
(requires (x `Set.mem` s))
(ensures (exists (x: field_t s) . True))
= Classical.exists_intro (fun (_: field_t s) -> True) x | {
"file_name": "lib/steel/c/Steel.ST.C.Types.UserStruct.fsti",
"git_rev": "f984200f79bdc452374ae994a5ca837496476c41",
"git_url": "https://github.com/FStarLang/steel.git",
"project_name": "steel"
} | {
"end_col": 55,
"end_line": 51,
"start_col": 0,
"start_line": 48
} | module Steel.ST.C.Types.UserStruct
open Steel.ST.Util
open Steel.ST.C.Types.Struct.Aux
module Set = FStar.Set
(* This library allows the user to define their own struct type, with
a constructor from field values, and a destructor to field values for
each field. This may be necessary for recursive structs *)
let set_def
(#t: eqtype)
(s: FStar.Set.set t)
(x: t)
: Tot bool
= FStar.Set.mem x s
noextract
let nonempty_set (t: eqtype) =
(s: Set.set t { exists x . set_def s x == true })
noextract
let set_snoc // for associativity reasons
(#t: eqtype) (q: FStar.Set.set t) (a: t) : Pure (nonempty_set t)
(requires True)
(ensures (fun s ->
(forall (x: t). {:pattern FStar.Set.mem x s} FStar.Set.mem x s == (x = a || FStar.Set.mem x q))
))
= q `FStar.Set.union` FStar.Set.singleton a
[@@noextract_to "krml"]
let field_t (s: Set.set string) : Tot eqtype =
(f: string { Set.mem f s })
[@@noextract_to "krml"; norm_field_attr]
inline_for_extraction // for field_desc.fd_type
noeq
type struct_def (t: Type) = {
fields: Set.set string;
field_desc: field_description_gen_t (field_t fields);
mk: ((f: field_t fields) -> Tot (field_desc.fd_type f)) -> Tot t;
get: (t -> (f: field_t fields) -> Tot (field_desc.fd_type f));
get_mk: (phi: ((f: field_t fields) -> Tot (field_desc.fd_type f))) -> (f: field_t fields) -> Lemma
(get (mk phi) f == phi f);
extensionality: (x1: t) -> (x2: t) -> ((f: field_t fields) -> Lemma (get x1 f == get x2 f)) -> Lemma (x1 == x2);
} | {
"checked_file": "/",
"dependencies": [
"Steel.ST.Util.fsti.checked",
"Steel.ST.C.Types.Struct.Aux.fsti.checked",
"Steel.FractionalPermission.fst.checked",
"prims.fst.checked",
"FStar.Set.fsti.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Ghost.fsti.checked",
"FStar.Classical.fsti.checked"
],
"interface_file": false,
"source_file": "Steel.ST.C.Types.UserStruct.fsti"
} | [
{
"abbrev": true,
"full_module": "FStar.Set",
"short_module": "Set"
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types.Struct.Aux",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.Util",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types",
"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.string -> s: FStar.Set.set Prims.string
-> FStar.Pervasives.Lemma (requires FStar.Set.mem x s)
(ensures exists (x: Steel.ST.C.Types.UserStruct.field_t s). Prims.l_True) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"Prims.string",
"FStar.Set.set",
"FStar.Classical.exists_intro",
"Steel.ST.C.Types.UserStruct.field_t",
"Prims.l_True",
"Prims.unit",
"Prims.b2t",
"FStar.Set.mem",
"Prims.squash",
"Prims.l_Exists",
"Prims.Nil",
"FStar.Pervasives.pattern"
] | [] | false | false | true | false | false | let nonempty_set_nonempty_type (x: string) (s: Set.set string)
: Lemma (requires (x `Set.mem` s)) (ensures (exists (x: field_t s). True)) =
| Classical.exists_intro (fun (_: field_t s) -> True) x | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.validate_fldata_strong | val validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata_strong s sz)) | val validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata_strong s sz)) | let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 37,
"end_line": 207,
"start_col": 0,
"start_line": 194
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
s: LowParse.Spec.Base.serializer p ->
v: LowParse.Low.Base.validator p ->
sz: Prims.nat ->
sz32: FStar.UInt32.t{FStar.UInt32.v sz32 == sz}
-> LowParse.Low.Base.validator (LowParse.Spec.FLData.parse_fldata_strong s sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Spec.Base.serializer",
"LowParse.Low.Base.validator",
"Prims.nat",
"FStar.UInt32.t",
"Prims.eq2",
"Prims.int",
"Prims.l_or",
"FStar.UInt.size",
"FStar.UInt32.n",
"Prims.b2t",
"Prims.op_GreaterThanOrEqual",
"FStar.UInt32.v",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt64.t",
"LowParse.Low.FLData.validate_fldata",
"Prims.unit",
"LowParse.Low.Base.Spec.valid_facts",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata_strong_t",
"LowParse.Spec.FLData.parse_fldata_strong",
"LowParse.Low.ErrorCode.uint64_to_uint32",
"LowParse.Spec.FLData.parse_fldata",
"FStar.Monotonic.HyperStack.mem",
"FStar.HyperStack.ST.get"
] | [] | false | false | false | false | false | let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata_strong s sz)) =
| fun #rrel #rel input pos ->
let h = HST.get () in
[@@ inline_let ]let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@@ inline_let ]let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos | false |
Lib.Sequence.fsti | Lib.Sequence.map_blocks_f | val map_blocks_f
(#a: Type)
(bs: size_nat{bs > 0})
(max: nat)
(inp: seq a {length inp == max * bs})
(f: (i: nat{i < max} -> lseq a bs -> lseq a bs))
(i: nat{i < max})
(acc: map_blocks_a a bs max i)
: map_blocks_a a bs max (i + 1) | val map_blocks_f
(#a: Type)
(bs: size_nat{bs > 0})
(max: nat)
(inp: seq a {length inp == max * bs})
(f: (i: nat{i < max} -> lseq a bs -> lseq a bs))
(i: nat{i < max})
(acc: map_blocks_a a bs max i)
: map_blocks_a a bs max (i + 1) | let map_blocks_f
(#a:Type)
(bs:size_nat{bs > 0})
(max:nat)
(inp:seq a{length inp == max * bs})
(f:(i:nat{i < max} -> lseq a bs -> lseq a bs))
(i:nat{i < max})
(acc:map_blocks_a a bs max i) : map_blocks_a a bs max (i + 1)
=
Math.Lemmas.lemma_mult_le_right bs (i+1) max;
let block = Seq.slice inp (i*bs) ((i+1)*bs) in
Seq.append acc (f i block) | {
"file_name": "lib/Lib.Sequence.fsti",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 28,
"end_line": 391,
"start_col": 0,
"start_line": 380
} | module Lib.Sequence
open FStar.Mul
open Lib.IntTypes
#set-options "--z3rlimit 30 --max_fuel 0 --max_ifuel 0 --using_facts_from '-* +Prims +FStar.Math.Lemmas +FStar.Seq +Lib.IntTypes +Lib.Sequence'"
/// Variable length Sequences, derived from FStar.Seq
(* This is the type of unbounded sequences.
Use this only when dealing with, say, user input whose length is unbounded.
As far as possible use the API for bounded sequences defined later in this file.*)
(** Definition of a Sequence *)
let seq (a:Type0) = Seq.seq a
(** Length of a Sequence *)
let length (#a:Type0) (s:seq a) : nat = Seq.length s
/// Fixed length Sequences
(* This is the type of bounded sequences.
Use this as much as possible.
It adds additional length checks that you'd have to prove in the implementation otherwise *)
(** Definition of a fixed-length Sequence *)
let lseq (a:Type0) (len:size_nat) = s:seq a{Seq.length s == len}
let to_seq (#a:Type0) (#len:size_nat) (l:lseq a len) : seq a = l
let to_lseq (#a:Type0) (s:seq a{length s <= max_size_t}) : l:lseq a (length s){l == s} = s
(* If you want to prove your code with an abstract lseq use the following: *)
// val lseq: a:Type0 -> len:size_nat -> Type0
// val to_seq: #a:Type0 -> #len:size_nat -> lseq a len -> s:seq a{length s == len}
// val to_lseq: #a:Type0 -> s:seq a{length s <= max_size_t} -> lseq a (length s)
val index:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> i:size_nat{i < len} ->
Tot (r:a{r == Seq.index (to_seq s) i})
(** Creation of a fixed-length Sequence from an initial value *)
val create:
#a:Type
-> len:size_nat
-> init:a ->
Tot (s:lseq a len{to_seq s == Seq.create len init /\ (forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init)})
(** Concatenate sequences: use with care, may make implementation hard to verify *)
val concat:
#a:Type
-> #len0:size_nat
-> #len1:size_nat{len0 + len1 <= max_size_t}
-> s0:lseq a len0
-> s1:lseq a len1 ->
Tot (s2:lseq a (len0 + len1){to_seq s2 == Seq.append (to_seq s0) (to_seq s1)})
let ( @| ) #a #len0 #len1 s0 s1 = concat #a #len0 #len1 s0 s1
(** Conversion of a Sequence to a list *)
val to_list:
#a:Type
-> s:seq a ->
Tot (l:list a{List.Tot.length l = length s /\ l == Seq.seq_to_list s})
(** Creation of a fixed-length Sequence from a list of values *)
val of_list:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t} ->
Tot (s:lseq a (List.Tot.length l){to_seq s == Seq.seq_of_list l})
val of_list_index:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t}
-> i:nat{i < List.Tot.length l} ->
Lemma (index (of_list l) i == List.Tot.index l i)
[SMTPat (index (of_list l) i)]
val equal (#a:Type) (#len:size_nat) (s1:lseq a len) (s2:lseq a len) : Type0
val eq_intro: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires forall i. {:pattern index s1 i; index s2 i} index s1 i == index s2 i)
(ensures equal s1 s2)
[SMTPat (equal s1 s2)]
val eq_elim: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires equal s1 s2)
(ensures s1 == s2)
[SMTPat (equal s1 s2)]
(* Alias for creation from a list *)
unfold let createL #a l = of_list #a l
(** Updating an element of a fixed-length Sequence *)
val upd:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> n:size_nat{n < len}
-> x:a ->
Tot (o:lseq a len{to_seq o == Seq.upd (to_seq s) n x /\ index o n == x /\ (forall (i:size_nat).
{:pattern (index s i)} (i < len /\ i <> n) ==> index o i == index s i)})
(** Membership of an element to a fixed-length Sequence *)
val member: #a:eqtype -> #len: size_nat -> a -> lseq a len -> Tot bool
(** Operator for accessing an element of a fixed-length Sequence *)
unfold
let op_String_Access #a #len = index #a #len
(** Operator for updating an element of a fixed-length Sequence *)
unfold
let op_String_Assignment #a #len = upd #a #len
(** Selecting a subset of a fixed-length Sequence *)
val sub:
#a:Type
-> #len:size_nat
-> s1:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len} ->
Tot (s2:lseq a n{to_seq s2 == Seq.slice (to_seq s1) start (start + n) /\
(forall (k:nat{k < n}). {:pattern (index s2 k)} index s2 k == index s1 (start + k))})
(** Selecting a subset of a fixed-length Sequence *)
let slice
(#a:Type)
(#len:size_nat)
(s1:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
=
sub #a s1 start (fin - start)
(** Updating a sub-Sequence from another fixed-length Sequence *)
val update_sub:
#a:Type
-> #len:size_nat
-> i:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> x:lseq a n ->
Tot (o:lseq a len{sub o start n == x /\
(forall (k:nat{(0 <= k /\ k < start) \/ (start + n <= k /\ k < len)}).
{:pattern (index o k)} index o k == index i k)})
(** Lemma regarding updating a sub-Sequence with another Sequence *)
val lemma_update_sub:
#a:Type
-> #len:size_nat
-> dst:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> src:lseq a n
-> res:lseq a len ->
Lemma
(requires
sub res 0 start == sub dst 0 start /\
sub res start n == src /\
sub res (start + n) (len - start - n) ==
sub dst (start + n) (len - start - n))
(ensures
res == update_sub dst start n src)
val lemma_concat2:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> s:lseq a (len0 + len1) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1)
(ensures s == concat s0 s1)
val lemma_concat3:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> len2:size_nat{len0 + len1 + len2 <= max_size_t}
-> s2:lseq a len2
-> s:lseq a (len0 + len1 + len2) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1 /\
sub s (len0 + len1) len2 == s2)
(ensures s == concat (concat s0 s1) s2)
(** Updating a sub-Sequence from another fixed-length Sequence *)
let update_slice
(#a:Type)
(#len:size_nat)
(i:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
(upd:lseq a (fin - start))
=
update_sub #a i start (fin - start) upd
(** Creation of a fixed-length Sequence from an initialization function *)
val createi: #a:Type
-> len:size_nat
-> init:(i:nat{i < len} -> a) ->
Tot (s:lseq a len{(forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init i)})
(** Mapi function for fixed-length Sequences *)
val mapi:#a:Type -> #b:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f i s1.[i])})
(** Map function for fixed-length Sequences *)
val map:#a:Type -> #b:Type -> #len:size_nat
-> f:(a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f s1.[i])})
(** Map2i function for fixed-length Sequences *)
val map2i:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f i s1.[i] s2.[i])})
(** Map2 function for fixed-length Sequences *)
val map2:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f s1.[i] s2.[i])})
(** Forall function for fixed-length Sequences *)
val for_all:#a:Type -> #len:size_nat -> (a -> Tot bool) -> lseq a len -> bool
(** Forall2 function for fixed-length Sequences *)
val for_all2:#a:Type -> #b:Type -> #len:size_nat
-> (a -> b -> Tot bool)
-> s1:lseq a len
-> s2:lseq b len ->
Tot bool
val repeati_blocks:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(i:nat{i < length inp / blocksize} -> lseq a blocksize -> b -> b)
-> l:(i:nat{i == length inp / blocksize} -> len:size_nat{len == length inp % blocksize} -> s:lseq a len -> b -> b)
-> init:b ->
Tot b
let repeat_blocks_f
(#a:Type0)
(#b:Type0)
(bs:size_nat{bs > 0})
(inp:seq a)
(f:(lseq a bs -> b -> b))
(nb:nat{nb == length inp / bs})
(i:nat{i < nb})
(acc:b) : b
=
assert ((i+1) * bs <= nb * bs);
let block = Seq.slice inp (i * bs) (i * bs + bs) in
f block acc
val repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(lseq a blocksize -> b -> b)
-> l:(len:nat{len < blocksize} -> s:lseq a len -> b -> c)
-> init:b ->
Tot c
val lemma_repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> bs:size_pos
-> inp:seq a
-> f:(lseq a bs -> b -> b)
-> l:(len:nat{len < bs} -> s:lseq a len -> b -> c)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
let rem = len % bs in
let acc = Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init in
let last = Seq.slice inp (nb * bs) len in
let acc = l rem last acc in
repeat_blocks #a #b bs inp f l init == acc)
val repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a{length inp % blocksize = 0}
-> f:(lseq a blocksize -> b -> b)
-> init:b ->
Tot b
val lemma_repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> bs:size_pos
-> inp:seq a{length inp % bs = 0}
-> f:(lseq a bs -> b -> b)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
repeat_blocks_multi #a #b bs inp f init ==
Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init)
(** Generates `n` blocks of length `len` by iteratively applying a function with an accumulator *)
val generate_blocks:
#t:Type0
-> len:size_nat
-> max:nat
-> n:nat{n <= max}
-> a:(i:nat{i <= max} -> Type)
-> f:(i:nat{i < max} -> a i -> a (i + 1) & s:seq t{length s == len})
-> init:a 0 ->
Tot (a n & s:seq t{length s == n * len})
(** Generates `n` blocks of length `len` by iteratively applying a function without an accumulator *)
val generate_blocks_simple:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> f:(i:nat{i < max} -> lseq a blocksize) ->
Tot (s:seq a{length s == n * blocksize})
(** The following functions allow us to bridge between unbounded and bounded sequences *)
val div_interval: b:pos -> n:int -> i:int -> Lemma
(requires n * b <= i /\ i < (n + 1) * b)
(ensures i / b = n)
val mod_interval_lt: b:pos -> n:int -> i:int -> j:int -> Lemma
(requires n * b <= i /\ i < j /\ j < (n + 1) * b)
(ensures i % b < j % b)
val div_mul_lt: b:pos -> a:int -> n:int -> Lemma
(requires a < n * b)
(ensures a / b < n)
val mod_div_lt: b:pos -> i:int -> j:int -> Lemma
(requires (j / b) * b <= i /\ i < j)
(ensures i % b < j % b)
val div_mul_l: a:int -> b:int -> c:pos -> d:pos -> Lemma
(requires a / d = b / d)
(ensures a / (c * d) = b / (c * d))
let map_blocks_a (a:Type) (bs:size_nat) (max:nat) (i:nat{i <= max}) = s:seq a{length s == i * bs} | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.List.Tot.fst.checked"
],
"interface_file": false,
"source_file": "Lib.Sequence.fsti"
} | [
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"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": 30,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
bs: Lib.IntTypes.size_nat{bs > 0} ->
max: Prims.nat ->
inp: Lib.Sequence.seq a {Lib.Sequence.length inp == max * bs} ->
f: (i: Prims.nat{i < max} -> _: Lib.Sequence.lseq a bs -> Lib.Sequence.lseq a bs) ->
i: Prims.nat{i < max} ->
acc: Lib.Sequence.map_blocks_a a bs max i
-> Lib.Sequence.map_blocks_a a bs max (i + 1) | Prims.Tot | [
"total"
] | [] | [
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_GreaterThan",
"Prims.nat",
"Lib.Sequence.seq",
"Prims.eq2",
"Prims.int",
"Lib.Sequence.length",
"FStar.Mul.op_Star",
"Prims.op_LessThan",
"Lib.Sequence.lseq",
"Lib.Sequence.map_blocks_a",
"FStar.Seq.Base.append",
"FStar.Seq.Base.seq",
"FStar.Seq.Base.slice",
"Prims.op_Addition",
"Prims.unit",
"FStar.Math.Lemmas.lemma_mult_le_right"
] | [] | false | false | false | false | false | let map_blocks_f
(#a: Type)
(bs: size_nat{bs > 0})
(max: nat)
(inp: seq a {length inp == max * bs})
(f: (i: nat{i < max} -> lseq a bs -> lseq a bs))
(i: nat{i < max})
(acc: map_blocks_a a bs max i)
: map_blocks_a a bs max (i + 1) =
| Math.Lemmas.lemma_mult_le_right bs (i + 1) max;
let block = Seq.slice inp (i * bs) ((i + 1) * bs) in
Seq.append acc (f i block) | false |
Lib.Sequence.fsti | Lib.Sequence.get_block | val get_block
(#a: Type)
(#len: nat)
(blocksize: size_pos)
(inp: seq a {length inp == len})
(f: (block len blocksize -> lseq a blocksize -> lseq a blocksize))
(i: nat{i < (len / blocksize) * blocksize})
: Pure (lseq a blocksize) True (fun _ -> i / blocksize < len / blocksize) | val get_block
(#a: Type)
(#len: nat)
(blocksize: size_pos)
(inp: seq a {length inp == len})
(f: (block len blocksize -> lseq a blocksize -> lseq a blocksize))
(i: nat{i < (len / blocksize) * blocksize})
: Pure (lseq a blocksize) True (fun _ -> i / blocksize < len / blocksize) | let get_block
(#a:Type)
(#len:nat)
(blocksize:size_pos)
(inp:seq a{length inp == len})
(f:(block len blocksize -> lseq a blocksize -> lseq a blocksize))
(i:nat{i < (len / blocksize) * blocksize}) :
Pure (lseq a blocksize) True (fun _ -> i / blocksize < len / blocksize)
=
div_mul_lt blocksize i (len / blocksize);
let j: block len blocksize = i / blocksize in
let b: lseq a blocksize = Seq.slice inp (j * blocksize) ((j + 1) * blocksize) in
f j b | {
"file_name": "lib/Lib.Sequence.fsti",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 7,
"end_line": 478,
"start_col": 0,
"start_line": 466
} | module Lib.Sequence
open FStar.Mul
open Lib.IntTypes
#set-options "--z3rlimit 30 --max_fuel 0 --max_ifuel 0 --using_facts_from '-* +Prims +FStar.Math.Lemmas +FStar.Seq +Lib.IntTypes +Lib.Sequence'"
/// Variable length Sequences, derived from FStar.Seq
(* This is the type of unbounded sequences.
Use this only when dealing with, say, user input whose length is unbounded.
As far as possible use the API for bounded sequences defined later in this file.*)
(** Definition of a Sequence *)
let seq (a:Type0) = Seq.seq a
(** Length of a Sequence *)
let length (#a:Type0) (s:seq a) : nat = Seq.length s
/// Fixed length Sequences
(* This is the type of bounded sequences.
Use this as much as possible.
It adds additional length checks that you'd have to prove in the implementation otherwise *)
(** Definition of a fixed-length Sequence *)
let lseq (a:Type0) (len:size_nat) = s:seq a{Seq.length s == len}
let to_seq (#a:Type0) (#len:size_nat) (l:lseq a len) : seq a = l
let to_lseq (#a:Type0) (s:seq a{length s <= max_size_t}) : l:lseq a (length s){l == s} = s
(* If you want to prove your code with an abstract lseq use the following: *)
// val lseq: a:Type0 -> len:size_nat -> Type0
// val to_seq: #a:Type0 -> #len:size_nat -> lseq a len -> s:seq a{length s == len}
// val to_lseq: #a:Type0 -> s:seq a{length s <= max_size_t} -> lseq a (length s)
val index:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> i:size_nat{i < len} ->
Tot (r:a{r == Seq.index (to_seq s) i})
(** Creation of a fixed-length Sequence from an initial value *)
val create:
#a:Type
-> len:size_nat
-> init:a ->
Tot (s:lseq a len{to_seq s == Seq.create len init /\ (forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init)})
(** Concatenate sequences: use with care, may make implementation hard to verify *)
val concat:
#a:Type
-> #len0:size_nat
-> #len1:size_nat{len0 + len1 <= max_size_t}
-> s0:lseq a len0
-> s1:lseq a len1 ->
Tot (s2:lseq a (len0 + len1){to_seq s2 == Seq.append (to_seq s0) (to_seq s1)})
let ( @| ) #a #len0 #len1 s0 s1 = concat #a #len0 #len1 s0 s1
(** Conversion of a Sequence to a list *)
val to_list:
#a:Type
-> s:seq a ->
Tot (l:list a{List.Tot.length l = length s /\ l == Seq.seq_to_list s})
(** Creation of a fixed-length Sequence from a list of values *)
val of_list:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t} ->
Tot (s:lseq a (List.Tot.length l){to_seq s == Seq.seq_of_list l})
val of_list_index:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t}
-> i:nat{i < List.Tot.length l} ->
Lemma (index (of_list l) i == List.Tot.index l i)
[SMTPat (index (of_list l) i)]
val equal (#a:Type) (#len:size_nat) (s1:lseq a len) (s2:lseq a len) : Type0
val eq_intro: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires forall i. {:pattern index s1 i; index s2 i} index s1 i == index s2 i)
(ensures equal s1 s2)
[SMTPat (equal s1 s2)]
val eq_elim: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires equal s1 s2)
(ensures s1 == s2)
[SMTPat (equal s1 s2)]
(* Alias for creation from a list *)
unfold let createL #a l = of_list #a l
(** Updating an element of a fixed-length Sequence *)
val upd:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> n:size_nat{n < len}
-> x:a ->
Tot (o:lseq a len{to_seq o == Seq.upd (to_seq s) n x /\ index o n == x /\ (forall (i:size_nat).
{:pattern (index s i)} (i < len /\ i <> n) ==> index o i == index s i)})
(** Membership of an element to a fixed-length Sequence *)
val member: #a:eqtype -> #len: size_nat -> a -> lseq a len -> Tot bool
(** Operator for accessing an element of a fixed-length Sequence *)
unfold
let op_String_Access #a #len = index #a #len
(** Operator for updating an element of a fixed-length Sequence *)
unfold
let op_String_Assignment #a #len = upd #a #len
(** Selecting a subset of a fixed-length Sequence *)
val sub:
#a:Type
-> #len:size_nat
-> s1:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len} ->
Tot (s2:lseq a n{to_seq s2 == Seq.slice (to_seq s1) start (start + n) /\
(forall (k:nat{k < n}). {:pattern (index s2 k)} index s2 k == index s1 (start + k))})
(** Selecting a subset of a fixed-length Sequence *)
let slice
(#a:Type)
(#len:size_nat)
(s1:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
=
sub #a s1 start (fin - start)
(** Updating a sub-Sequence from another fixed-length Sequence *)
val update_sub:
#a:Type
-> #len:size_nat
-> i:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> x:lseq a n ->
Tot (o:lseq a len{sub o start n == x /\
(forall (k:nat{(0 <= k /\ k < start) \/ (start + n <= k /\ k < len)}).
{:pattern (index o k)} index o k == index i k)})
(** Lemma regarding updating a sub-Sequence with another Sequence *)
val lemma_update_sub:
#a:Type
-> #len:size_nat
-> dst:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> src:lseq a n
-> res:lseq a len ->
Lemma
(requires
sub res 0 start == sub dst 0 start /\
sub res start n == src /\
sub res (start + n) (len - start - n) ==
sub dst (start + n) (len - start - n))
(ensures
res == update_sub dst start n src)
val lemma_concat2:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> s:lseq a (len0 + len1) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1)
(ensures s == concat s0 s1)
val lemma_concat3:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> len2:size_nat{len0 + len1 + len2 <= max_size_t}
-> s2:lseq a len2
-> s:lseq a (len0 + len1 + len2) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1 /\
sub s (len0 + len1) len2 == s2)
(ensures s == concat (concat s0 s1) s2)
(** Updating a sub-Sequence from another fixed-length Sequence *)
let update_slice
(#a:Type)
(#len:size_nat)
(i:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
(upd:lseq a (fin - start))
=
update_sub #a i start (fin - start) upd
(** Creation of a fixed-length Sequence from an initialization function *)
val createi: #a:Type
-> len:size_nat
-> init:(i:nat{i < len} -> a) ->
Tot (s:lseq a len{(forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init i)})
(** Mapi function for fixed-length Sequences *)
val mapi:#a:Type -> #b:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f i s1.[i])})
(** Map function for fixed-length Sequences *)
val map:#a:Type -> #b:Type -> #len:size_nat
-> f:(a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f s1.[i])})
(** Map2i function for fixed-length Sequences *)
val map2i:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f i s1.[i] s2.[i])})
(** Map2 function for fixed-length Sequences *)
val map2:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f s1.[i] s2.[i])})
(** Forall function for fixed-length Sequences *)
val for_all:#a:Type -> #len:size_nat -> (a -> Tot bool) -> lseq a len -> bool
(** Forall2 function for fixed-length Sequences *)
val for_all2:#a:Type -> #b:Type -> #len:size_nat
-> (a -> b -> Tot bool)
-> s1:lseq a len
-> s2:lseq b len ->
Tot bool
val repeati_blocks:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(i:nat{i < length inp / blocksize} -> lseq a blocksize -> b -> b)
-> l:(i:nat{i == length inp / blocksize} -> len:size_nat{len == length inp % blocksize} -> s:lseq a len -> b -> b)
-> init:b ->
Tot b
let repeat_blocks_f
(#a:Type0)
(#b:Type0)
(bs:size_nat{bs > 0})
(inp:seq a)
(f:(lseq a bs -> b -> b))
(nb:nat{nb == length inp / bs})
(i:nat{i < nb})
(acc:b) : b
=
assert ((i+1) * bs <= nb * bs);
let block = Seq.slice inp (i * bs) (i * bs + bs) in
f block acc
val repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(lseq a blocksize -> b -> b)
-> l:(len:nat{len < blocksize} -> s:lseq a len -> b -> c)
-> init:b ->
Tot c
val lemma_repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> bs:size_pos
-> inp:seq a
-> f:(lseq a bs -> b -> b)
-> l:(len:nat{len < bs} -> s:lseq a len -> b -> c)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
let rem = len % bs in
let acc = Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init in
let last = Seq.slice inp (nb * bs) len in
let acc = l rem last acc in
repeat_blocks #a #b bs inp f l init == acc)
val repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a{length inp % blocksize = 0}
-> f:(lseq a blocksize -> b -> b)
-> init:b ->
Tot b
val lemma_repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> bs:size_pos
-> inp:seq a{length inp % bs = 0}
-> f:(lseq a bs -> b -> b)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
repeat_blocks_multi #a #b bs inp f init ==
Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init)
(** Generates `n` blocks of length `len` by iteratively applying a function with an accumulator *)
val generate_blocks:
#t:Type0
-> len:size_nat
-> max:nat
-> n:nat{n <= max}
-> a:(i:nat{i <= max} -> Type)
-> f:(i:nat{i < max} -> a i -> a (i + 1) & s:seq t{length s == len})
-> init:a 0 ->
Tot (a n & s:seq t{length s == n * len})
(** Generates `n` blocks of length `len` by iteratively applying a function without an accumulator *)
val generate_blocks_simple:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> f:(i:nat{i < max} -> lseq a blocksize) ->
Tot (s:seq a{length s == n * blocksize})
(** The following functions allow us to bridge between unbounded and bounded sequences *)
val div_interval: b:pos -> n:int -> i:int -> Lemma
(requires n * b <= i /\ i < (n + 1) * b)
(ensures i / b = n)
val mod_interval_lt: b:pos -> n:int -> i:int -> j:int -> Lemma
(requires n * b <= i /\ i < j /\ j < (n + 1) * b)
(ensures i % b < j % b)
val div_mul_lt: b:pos -> a:int -> n:int -> Lemma
(requires a < n * b)
(ensures a / b < n)
val mod_div_lt: b:pos -> i:int -> j:int -> Lemma
(requires (j / b) * b <= i /\ i < j)
(ensures i % b < j % b)
val div_mul_l: a:int -> b:int -> c:pos -> d:pos -> Lemma
(requires a / d = b / d)
(ensures a / (c * d) = b / (c * d))
let map_blocks_a (a:Type) (bs:size_nat) (max:nat) (i:nat{i <= max}) = s:seq a{length s == i * bs}
let map_blocks_f
(#a:Type)
(bs:size_nat{bs > 0})
(max:nat)
(inp:seq a{length inp == max * bs})
(f:(i:nat{i < max} -> lseq a bs -> lseq a bs))
(i:nat{i < max})
(acc:map_blocks_a a bs max i) : map_blocks_a a bs max (i + 1)
=
Math.Lemmas.lemma_mult_le_right bs (i+1) max;
let block = Seq.slice inp (i*bs) ((i+1)*bs) in
Seq.append acc (f i block)
val map_blocks_multi:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> inp:seq a{length inp == max * blocksize}
-> f:(i:nat{i < max} -> lseq a blocksize -> lseq a blocksize) ->
Tot (out:seq a {length out == n * blocksize})
val lemma_map_blocks_multi:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> inp:seq a{length inp == max * blocksize}
-> f:(i:nat{i < max} -> lseq a blocksize -> lseq a blocksize)
-> Lemma
(map_blocks_multi #a blocksize max n inp f ==
LoopCombinators.repeat_gen n (map_blocks_a a blocksize max) (map_blocks_f #a blocksize max inp f) Seq.empty)
#restart-solver
val index_map_blocks_multi:
#a:Type0
-> bs:size_pos
-> max:pos
-> n:pos{n <= max}
-> inp:seq a{length inp == max * bs}
-> f:(i:nat{i < max} -> lseq a bs -> lseq a bs)
-> i:nat{i < n * bs}
-> Lemma (
div_mul_lt bs i n;
let j = i / bs in
let block: lseq a bs = Seq.slice inp (j * bs) ((j + 1) * bs) in
Seq.index (map_blocks_multi bs max n inp f) i == Seq.index (f j block) (i % bs))
(* A full block index *)
unfold
let block (len:nat) (blocksize:size_pos) = i:nat{i < len / blocksize}
(* Index of last (incomplete) block *)
unfold
let last (len:nat) (blocksize:size_pos) = i:nat{i = len / blocksize}
val map_blocks:
#a:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(block (length inp) blocksize -> lseq a blocksize -> lseq a blocksize)
-> g:(last (length inp) blocksize -> rem:size_nat{rem < blocksize} -> s:lseq a rem -> lseq a rem) ->
Tot (out:seq a{length out == length inp})
val lemma_map_blocks:
#a:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(block (length inp) blocksize -> lseq a blocksize -> lseq a blocksize)
-> g:(last (length inp) blocksize -> rem:size_nat{rem < blocksize} -> s:lseq a rem -> lseq a rem) ->
Lemma (
let len = length inp in
let nb = len / blocksize in
let rem = len % blocksize in
let blocks = Seq.slice inp 0 (nb * blocksize) in
let last = Seq.slice inp (nb * blocksize) len in
Math.Lemmas.cancel_mul_div nb blocksize;
let bs = map_blocks_multi #a blocksize nb nb blocks f in
let res = if (rem > 0) then Seq.append bs (g nb rem last) else bs in
res == map_blocks #a blocksize inp f g) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.List.Tot.fst.checked"
],
"interface_file": false,
"source_file": "Lib.Sequence.fsti"
} | [
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"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": 30,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
blocksize: Lib.IntTypes.size_pos ->
inp: Lib.Sequence.seq a {Lib.Sequence.length inp == len} ->
f:
(_: Lib.Sequence.block len blocksize -> _: Lib.Sequence.lseq a blocksize
-> Lib.Sequence.lseq a blocksize) ->
i: Prims.nat{i < (len / blocksize) * blocksize}
-> Prims.Pure (Lib.Sequence.lseq a blocksize) | Prims.Pure | [] | [] | [
"Prims.nat",
"Lib.IntTypes.size_pos",
"Lib.Sequence.seq",
"Prims.eq2",
"Lib.Sequence.length",
"Lib.Sequence.block",
"Lib.Sequence.lseq",
"Prims.b2t",
"Prims.op_LessThan",
"FStar.Mul.op_Star",
"Prims.op_Division",
"FStar.Seq.Base.slice",
"Prims.op_Addition",
"Prims.unit",
"Lib.Sequence.div_mul_lt",
"Prims.l_True"
] | [] | false | false | false | false | false | let get_block
(#a: Type)
(#len: nat)
(blocksize: size_pos)
(inp: seq a {length inp == len})
(f: (block len blocksize -> lseq a blocksize -> lseq a blocksize))
(i: nat{i < (len / blocksize) * blocksize})
: Pure (lseq a blocksize) True (fun _ -> i / blocksize < len / blocksize) =
| div_mul_lt blocksize i (len / blocksize);
let j:block len blocksize = i / blocksize in
let b:lseq a blocksize = Seq.slice inp (j * blocksize) ((j + 1) * blocksize) in
f j b | false |
Target.fst | Target.print_expr_lam | val print_expr_lam (mname: string) (x: lam expr) : ML string | val print_expr_lam (mname: string) (x: lam expr) : ML string | let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 32,
"end_line": 364,
"start_col": 0,
"start_line": 363
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> x: Target.lam Target.expr -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.lam",
"Target.expr",
"Target.print_lam",
"Target.print_expr"
] | [] | false | true | false | false | false | let print_expr_lam (mname: string) (x: lam expr) : ML string =
| print_lam (print_expr mname) x | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.gaccessor_fldata | val gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _)) | val gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _)) | let gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _))
= gaccessor_prop_equiv (parse_fldata p sz) p (clens_id _) (gaccessor_fldata' p sz);
gaccessor_fldata' p sz | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 24,
"end_line": 254,
"start_col": 0,
"start_line": 247
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos
inline_for_extraction
let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 ()
inline_for_extraction
let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata_strong s sz))
= jump_constant_size (parse_fldata_strong s sz) sz32 ()
let gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _))
= fun (input: bytes) -> (
let _ = match parse (parse_fldata p sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0
) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
p:
LowParse.Spec.Base.parser k t
{ Mkparser_kind'?.parser_kind_subkind k ==
FStar.Pervasives.Native.Some LowParse.Spec.Base.ParserStrong } ->
sz: Prims.nat
-> LowParse.Low.Base.Spec.gaccessor (LowParse.Spec.FLData.parse_fldata p sz)
p
(LowParse.Low.Base.Spec.clens_id t) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"Prims.eq2",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserStrong",
"Prims.nat",
"LowParse.Low.FLData.gaccessor_fldata'",
"Prims.unit",
"LowParse.Low.Base.Spec.gaccessor_prop_equiv",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata",
"LowParse.Low.Base.Spec.clens_id",
"LowParse.Low.Base.Spec.gaccessor"
] | [] | false | false | false | false | false | let gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _)) =
| gaccessor_prop_equiv (parse_fldata p sz) p (clens_id _) (gaccessor_fldata' p sz);
gaccessor_fldata' p sz | false |
Lib.Sequence.fsti | Lib.Sequence.get_last | val get_last
(#a: Type)
(#len: nat)
(blocksize: size_pos)
(inp: seq a {length inp == len})
(g: (last len blocksize -> rem: size_nat{rem < blocksize} -> lseq a rem -> lseq a rem))
(i: nat{(len / blocksize) * blocksize <= i /\ i < len})
: Pure (lseq a (len % blocksize)) True (fun _ -> i % blocksize < len % blocksize) | val get_last
(#a: Type)
(#len: nat)
(blocksize: size_pos)
(inp: seq a {length inp == len})
(g: (last len blocksize -> rem: size_nat{rem < blocksize} -> lseq a rem -> lseq a rem))
(i: nat{(len / blocksize) * blocksize <= i /\ i < len})
: Pure (lseq a (len % blocksize)) True (fun _ -> i % blocksize < len % blocksize) | let get_last
(#a:Type)
(#len:nat)
(blocksize:size_pos)
(inp:seq a{length inp == len})
(g:(last len blocksize -> rem:size_nat{rem < blocksize} -> lseq a rem -> lseq a rem))
(i:nat{(len / blocksize) * blocksize <= i /\ i < len}) :
Pure (lseq a (len % blocksize)) True (fun _ -> i % blocksize < len % blocksize)
=
mod_div_lt blocksize i len;
let rem = len % blocksize in
let b: lseq a rem = Seq.slice inp (len - rem) len in
g (len / blocksize) rem b | {
"file_name": "lib/Lib.Sequence.fsti",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 27,
"end_line": 494,
"start_col": 0,
"start_line": 482
} | module Lib.Sequence
open FStar.Mul
open Lib.IntTypes
#set-options "--z3rlimit 30 --max_fuel 0 --max_ifuel 0 --using_facts_from '-* +Prims +FStar.Math.Lemmas +FStar.Seq +Lib.IntTypes +Lib.Sequence'"
/// Variable length Sequences, derived from FStar.Seq
(* This is the type of unbounded sequences.
Use this only when dealing with, say, user input whose length is unbounded.
As far as possible use the API for bounded sequences defined later in this file.*)
(** Definition of a Sequence *)
let seq (a:Type0) = Seq.seq a
(** Length of a Sequence *)
let length (#a:Type0) (s:seq a) : nat = Seq.length s
/// Fixed length Sequences
(* This is the type of bounded sequences.
Use this as much as possible.
It adds additional length checks that you'd have to prove in the implementation otherwise *)
(** Definition of a fixed-length Sequence *)
let lseq (a:Type0) (len:size_nat) = s:seq a{Seq.length s == len}
let to_seq (#a:Type0) (#len:size_nat) (l:lseq a len) : seq a = l
let to_lseq (#a:Type0) (s:seq a{length s <= max_size_t}) : l:lseq a (length s){l == s} = s
(* If you want to prove your code with an abstract lseq use the following: *)
// val lseq: a:Type0 -> len:size_nat -> Type0
// val to_seq: #a:Type0 -> #len:size_nat -> lseq a len -> s:seq a{length s == len}
// val to_lseq: #a:Type0 -> s:seq a{length s <= max_size_t} -> lseq a (length s)
val index:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> i:size_nat{i < len} ->
Tot (r:a{r == Seq.index (to_seq s) i})
(** Creation of a fixed-length Sequence from an initial value *)
val create:
#a:Type
-> len:size_nat
-> init:a ->
Tot (s:lseq a len{to_seq s == Seq.create len init /\ (forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init)})
(** Concatenate sequences: use with care, may make implementation hard to verify *)
val concat:
#a:Type
-> #len0:size_nat
-> #len1:size_nat{len0 + len1 <= max_size_t}
-> s0:lseq a len0
-> s1:lseq a len1 ->
Tot (s2:lseq a (len0 + len1){to_seq s2 == Seq.append (to_seq s0) (to_seq s1)})
let ( @| ) #a #len0 #len1 s0 s1 = concat #a #len0 #len1 s0 s1
(** Conversion of a Sequence to a list *)
val to_list:
#a:Type
-> s:seq a ->
Tot (l:list a{List.Tot.length l = length s /\ l == Seq.seq_to_list s})
(** Creation of a fixed-length Sequence from a list of values *)
val of_list:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t} ->
Tot (s:lseq a (List.Tot.length l){to_seq s == Seq.seq_of_list l})
val of_list_index:
#a:Type
-> l:list a{List.Tot.length l <= max_size_t}
-> i:nat{i < List.Tot.length l} ->
Lemma (index (of_list l) i == List.Tot.index l i)
[SMTPat (index (of_list l) i)]
val equal (#a:Type) (#len:size_nat) (s1:lseq a len) (s2:lseq a len) : Type0
val eq_intro: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires forall i. {:pattern index s1 i; index s2 i} index s1 i == index s2 i)
(ensures equal s1 s2)
[SMTPat (equal s1 s2)]
val eq_elim: #a:Type -> #len:size_nat -> s1:lseq a len -> s2:lseq a len ->
Lemma
(requires equal s1 s2)
(ensures s1 == s2)
[SMTPat (equal s1 s2)]
(* Alias for creation from a list *)
unfold let createL #a l = of_list #a l
(** Updating an element of a fixed-length Sequence *)
val upd:
#a:Type
-> #len:size_nat
-> s:lseq a len
-> n:size_nat{n < len}
-> x:a ->
Tot (o:lseq a len{to_seq o == Seq.upd (to_seq s) n x /\ index o n == x /\ (forall (i:size_nat).
{:pattern (index s i)} (i < len /\ i <> n) ==> index o i == index s i)})
(** Membership of an element to a fixed-length Sequence *)
val member: #a:eqtype -> #len: size_nat -> a -> lseq a len -> Tot bool
(** Operator for accessing an element of a fixed-length Sequence *)
unfold
let op_String_Access #a #len = index #a #len
(** Operator for updating an element of a fixed-length Sequence *)
unfold
let op_String_Assignment #a #len = upd #a #len
(** Selecting a subset of a fixed-length Sequence *)
val sub:
#a:Type
-> #len:size_nat
-> s1:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len} ->
Tot (s2:lseq a n{to_seq s2 == Seq.slice (to_seq s1) start (start + n) /\
(forall (k:nat{k < n}). {:pattern (index s2 k)} index s2 k == index s1 (start + k))})
(** Selecting a subset of a fixed-length Sequence *)
let slice
(#a:Type)
(#len:size_nat)
(s1:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
=
sub #a s1 start (fin - start)
(** Updating a sub-Sequence from another fixed-length Sequence *)
val update_sub:
#a:Type
-> #len:size_nat
-> i:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> x:lseq a n ->
Tot (o:lseq a len{sub o start n == x /\
(forall (k:nat{(0 <= k /\ k < start) \/ (start + n <= k /\ k < len)}).
{:pattern (index o k)} index o k == index i k)})
(** Lemma regarding updating a sub-Sequence with another Sequence *)
val lemma_update_sub:
#a:Type
-> #len:size_nat
-> dst:lseq a len
-> start:size_nat
-> n:size_nat{start + n <= len}
-> src:lseq a n
-> res:lseq a len ->
Lemma
(requires
sub res 0 start == sub dst 0 start /\
sub res start n == src /\
sub res (start + n) (len - start - n) ==
sub dst (start + n) (len - start - n))
(ensures
res == update_sub dst start n src)
val lemma_concat2:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> s:lseq a (len0 + len1) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1)
(ensures s == concat s0 s1)
val lemma_concat3:
#a:Type0
-> len0:size_nat
-> s0:lseq a len0
-> len1:size_nat{len0 + len1 <= max_size_t}
-> s1:lseq a len1
-> len2:size_nat{len0 + len1 + len2 <= max_size_t}
-> s2:lseq a len2
-> s:lseq a (len0 + len1 + len2) ->
Lemma
(requires
sub s 0 len0 == s0 /\
sub s len0 len1 == s1 /\
sub s (len0 + len1) len2 == s2)
(ensures s == concat (concat s0 s1) s2)
(** Updating a sub-Sequence from another fixed-length Sequence *)
let update_slice
(#a:Type)
(#len:size_nat)
(i:lseq a len)
(start:size_nat)
(fin:size_nat{start <= fin /\ fin <= len})
(upd:lseq a (fin - start))
=
update_sub #a i start (fin - start) upd
(** Creation of a fixed-length Sequence from an initialization function *)
val createi: #a:Type
-> len:size_nat
-> init:(i:nat{i < len} -> a) ->
Tot (s:lseq a len{(forall (i:nat).
{:pattern (index s i)} i < len ==> index s i == init i)})
(** Mapi function for fixed-length Sequences *)
val mapi:#a:Type -> #b:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f i s1.[i])})
(** Map function for fixed-length Sequences *)
val map:#a:Type -> #b:Type -> #len:size_nat
-> f:(a -> Tot b)
-> s1:lseq a len ->
Tot (s2:lseq b len{(forall (i:nat).
{:pattern (index s2 i)} i < len ==> index s2 i == f s1.[i])})
(** Map2i function for fixed-length Sequences *)
val map2i:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(i:nat{i < len} -> a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f i s1.[i] s2.[i])})
(** Map2 function for fixed-length Sequences *)
val map2:#a:Type -> #b:Type -> #c:Type -> #len:size_nat
-> f:(a -> b -> Tot c)
-> s1:lseq a len
-> s2:lseq b len ->
Tot (s3:lseq c len{(forall (i:nat).
{:pattern (index s3 i)} i < len ==> index s3 i == f s1.[i] s2.[i])})
(** Forall function for fixed-length Sequences *)
val for_all:#a:Type -> #len:size_nat -> (a -> Tot bool) -> lseq a len -> bool
(** Forall2 function for fixed-length Sequences *)
val for_all2:#a:Type -> #b:Type -> #len:size_nat
-> (a -> b -> Tot bool)
-> s1:lseq a len
-> s2:lseq b len ->
Tot bool
val repeati_blocks:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(i:nat{i < length inp / blocksize} -> lseq a blocksize -> b -> b)
-> l:(i:nat{i == length inp / blocksize} -> len:size_nat{len == length inp % blocksize} -> s:lseq a len -> b -> b)
-> init:b ->
Tot b
let repeat_blocks_f
(#a:Type0)
(#b:Type0)
(bs:size_nat{bs > 0})
(inp:seq a)
(f:(lseq a bs -> b -> b))
(nb:nat{nb == length inp / bs})
(i:nat{i < nb})
(acc:b) : b
=
assert ((i+1) * bs <= nb * bs);
let block = Seq.slice inp (i * bs) (i * bs + bs) in
f block acc
val repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(lseq a blocksize -> b -> b)
-> l:(len:nat{len < blocksize} -> s:lseq a len -> b -> c)
-> init:b ->
Tot c
val lemma_repeat_blocks:
#a:Type0
-> #b:Type0
-> #c:Type0
-> bs:size_pos
-> inp:seq a
-> f:(lseq a bs -> b -> b)
-> l:(len:nat{len < bs} -> s:lseq a len -> b -> c)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
let rem = len % bs in
let acc = Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init in
let last = Seq.slice inp (nb * bs) len in
let acc = l rem last acc in
repeat_blocks #a #b bs inp f l init == acc)
val repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> blocksize:size_pos
-> inp:seq a{length inp % blocksize = 0}
-> f:(lseq a blocksize -> b -> b)
-> init:b ->
Tot b
val lemma_repeat_blocks_multi:
#a:Type0
-> #b:Type0
-> bs:size_pos
-> inp:seq a{length inp % bs = 0}
-> f:(lseq a bs -> b -> b)
-> init:b ->
Lemma (
let len = length inp in
let nb = len / bs in
repeat_blocks_multi #a #b bs inp f init ==
Lib.LoopCombinators.repeati nb (repeat_blocks_f bs inp f nb) init)
(** Generates `n` blocks of length `len` by iteratively applying a function with an accumulator *)
val generate_blocks:
#t:Type0
-> len:size_nat
-> max:nat
-> n:nat{n <= max}
-> a:(i:nat{i <= max} -> Type)
-> f:(i:nat{i < max} -> a i -> a (i + 1) & s:seq t{length s == len})
-> init:a 0 ->
Tot (a n & s:seq t{length s == n * len})
(** Generates `n` blocks of length `len` by iteratively applying a function without an accumulator *)
val generate_blocks_simple:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> f:(i:nat{i < max} -> lseq a blocksize) ->
Tot (s:seq a{length s == n * blocksize})
(** The following functions allow us to bridge between unbounded and bounded sequences *)
val div_interval: b:pos -> n:int -> i:int -> Lemma
(requires n * b <= i /\ i < (n + 1) * b)
(ensures i / b = n)
val mod_interval_lt: b:pos -> n:int -> i:int -> j:int -> Lemma
(requires n * b <= i /\ i < j /\ j < (n + 1) * b)
(ensures i % b < j % b)
val div_mul_lt: b:pos -> a:int -> n:int -> Lemma
(requires a < n * b)
(ensures a / b < n)
val mod_div_lt: b:pos -> i:int -> j:int -> Lemma
(requires (j / b) * b <= i /\ i < j)
(ensures i % b < j % b)
val div_mul_l: a:int -> b:int -> c:pos -> d:pos -> Lemma
(requires a / d = b / d)
(ensures a / (c * d) = b / (c * d))
let map_blocks_a (a:Type) (bs:size_nat) (max:nat) (i:nat{i <= max}) = s:seq a{length s == i * bs}
let map_blocks_f
(#a:Type)
(bs:size_nat{bs > 0})
(max:nat)
(inp:seq a{length inp == max * bs})
(f:(i:nat{i < max} -> lseq a bs -> lseq a bs))
(i:nat{i < max})
(acc:map_blocks_a a bs max i) : map_blocks_a a bs max (i + 1)
=
Math.Lemmas.lemma_mult_le_right bs (i+1) max;
let block = Seq.slice inp (i*bs) ((i+1)*bs) in
Seq.append acc (f i block)
val map_blocks_multi:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> inp:seq a{length inp == max * blocksize}
-> f:(i:nat{i < max} -> lseq a blocksize -> lseq a blocksize) ->
Tot (out:seq a {length out == n * blocksize})
val lemma_map_blocks_multi:
#a:Type0
-> blocksize:size_pos
-> max:nat
-> n:nat{n <= max}
-> inp:seq a{length inp == max * blocksize}
-> f:(i:nat{i < max} -> lseq a blocksize -> lseq a blocksize)
-> Lemma
(map_blocks_multi #a blocksize max n inp f ==
LoopCombinators.repeat_gen n (map_blocks_a a blocksize max) (map_blocks_f #a blocksize max inp f) Seq.empty)
#restart-solver
val index_map_blocks_multi:
#a:Type0
-> bs:size_pos
-> max:pos
-> n:pos{n <= max}
-> inp:seq a{length inp == max * bs}
-> f:(i:nat{i < max} -> lseq a bs -> lseq a bs)
-> i:nat{i < n * bs}
-> Lemma (
div_mul_lt bs i n;
let j = i / bs in
let block: lseq a bs = Seq.slice inp (j * bs) ((j + 1) * bs) in
Seq.index (map_blocks_multi bs max n inp f) i == Seq.index (f j block) (i % bs))
(* A full block index *)
unfold
let block (len:nat) (blocksize:size_pos) = i:nat{i < len / blocksize}
(* Index of last (incomplete) block *)
unfold
let last (len:nat) (blocksize:size_pos) = i:nat{i = len / blocksize}
val map_blocks:
#a:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(block (length inp) blocksize -> lseq a blocksize -> lseq a blocksize)
-> g:(last (length inp) blocksize -> rem:size_nat{rem < blocksize} -> s:lseq a rem -> lseq a rem) ->
Tot (out:seq a{length out == length inp})
val lemma_map_blocks:
#a:Type0
-> blocksize:size_pos
-> inp:seq a
-> f:(block (length inp) blocksize -> lseq a blocksize -> lseq a blocksize)
-> g:(last (length inp) blocksize -> rem:size_nat{rem < blocksize} -> s:lseq a rem -> lseq a rem) ->
Lemma (
let len = length inp in
let nb = len / blocksize in
let rem = len % blocksize in
let blocks = Seq.slice inp 0 (nb * blocksize) in
let last = Seq.slice inp (nb * blocksize) len in
Math.Lemmas.cancel_mul_div nb blocksize;
let bs = map_blocks_multi #a blocksize nb nb blocks f in
let res = if (rem > 0) then Seq.append bs (g nb rem last) else bs in
res == map_blocks #a blocksize inp f g)
(* Computes the block of the i-th element of (map_blocks blocksize input f g) *)
let get_block
(#a:Type)
(#len:nat)
(blocksize:size_pos)
(inp:seq a{length inp == len})
(f:(block len blocksize -> lseq a blocksize -> lseq a blocksize))
(i:nat{i < (len / blocksize) * blocksize}) :
Pure (lseq a blocksize) True (fun _ -> i / blocksize < len / blocksize)
=
div_mul_lt blocksize i (len / blocksize);
let j: block len blocksize = i / blocksize in
let b: lseq a blocksize = Seq.slice inp (j * blocksize) ((j + 1) * blocksize) in
f j b | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Lib.LoopCombinators.fsti.checked",
"Lib.IntTypes.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.List.Tot.fst.checked"
],
"interface_file": false,
"source_file": "Lib.Sequence.fsti"
} | [
{
"abbrev": false,
"full_module": "Lib.IntTypes",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"short_module": null
},
{
"abbrev": false,
"full_module": "Lib",
"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": 30,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
blocksize: Lib.IntTypes.size_pos ->
inp: Lib.Sequence.seq a {Lib.Sequence.length inp == len} ->
g:
(
_: Lib.Sequence.last len blocksize ->
rem: Lib.IntTypes.size_nat{rem < blocksize} ->
_: Lib.Sequence.lseq a rem
-> Lib.Sequence.lseq a rem) ->
i: Prims.nat{(len / blocksize) * blocksize <= i /\ i < len}
-> Prims.Pure (Lib.Sequence.lseq a (len % blocksize)) | Prims.Pure | [] | [] | [
"Prims.nat",
"Lib.IntTypes.size_pos",
"Lib.Sequence.seq",
"Prims.eq2",
"Lib.Sequence.length",
"Lib.Sequence.last",
"Lib.IntTypes.size_nat",
"Prims.b2t",
"Prims.op_LessThan",
"Lib.Sequence.lseq",
"Prims.l_and",
"Prims.op_LessThanOrEqual",
"FStar.Mul.op_Star",
"Prims.op_Division",
"FStar.Seq.Base.slice",
"Prims.op_Subtraction",
"Prims.int",
"Prims.op_Modulus",
"Prims.unit",
"Lib.Sequence.mod_div_lt",
"Prims.l_True"
] | [] | false | false | false | false | false | let get_last
(#a: Type)
(#len: nat)
(blocksize: size_pos)
(inp: seq a {length inp == len})
(g: (last len blocksize -> rem: size_nat{rem < blocksize} -> lseq a rem -> lseq a rem))
(i: nat{(len / blocksize) * blocksize <= i /\ i < len})
: Pure (lseq a (len % blocksize)) True (fun _ -> i % blocksize < len % blocksize) =
| mod_div_lt blocksize i len;
let rem = len % blocksize in
let b:lseq a rem = Seq.slice inp (len - rem) len in
g (len / blocksize) rem b | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.gaccessor_fldata_strong | val gaccessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor (parse_fldata_strong s sz) p (clens_fldata_strong s sz)) | val gaccessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor (parse_fldata_strong s sz) p (clens_fldata_strong s sz)) | let gaccessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p { k.parser_kind_subkind == Some ParserStrong })
(sz: nat)
: Tot (gaccessor (parse_fldata_strong s sz) p (clens_fldata_strong s sz))
= gaccessor_prop_equiv (parse_fldata_strong s sz) p (clens_fldata_strong s sz) (gaccessor_fldata_strong' s sz);
gaccessor_fldata_strong' s sz | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 31,
"end_line": 307,
"start_col": 0,
"start_line": 299
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos
inline_for_extraction
let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 ()
inline_for_extraction
let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata_strong s sz))
= jump_constant_size (parse_fldata_strong s sz) sz32 ()
let gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _))
= fun (input: bytes) -> (
let _ = match parse (parse_fldata p sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0
)
let gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _))
= gaccessor_prop_equiv (parse_fldata p sz) p (clens_id _) (gaccessor_fldata' p sz);
gaccessor_fldata' p sz
inline_for_extraction
let accessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (accessor (gaccessor_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = slice_access_eq h (gaccessor_fldata p sz) input pos in
pos
let clens_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
: Tot (clens (parse_fldata_strong_t s sz) t)
= {
clens_cond = (fun _ -> True);
clens_get = (fun (x: parse_fldata_strong_t s sz) -> (x <: t));
}
inline_for_extraction
let gaccessor_fldata_strong'
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p { k.parser_kind_subkind == Some ParserStrong })
(sz: nat)
: Tot (gaccessor' (parse_fldata_strong s sz) p (clens_fldata_strong s sz))
= fun (input: bytes) ->
let _ = match parse (parse_fldata_strong s sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0 | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
s:
LowParse.Spec.Base.serializer p
{ Mkparser_kind'?.parser_kind_subkind k ==
FStar.Pervasives.Native.Some LowParse.Spec.Base.ParserStrong } ->
sz: Prims.nat
-> LowParse.Low.Base.Spec.gaccessor (LowParse.Spec.FLData.parse_fldata_strong s sz)
p
(LowParse.Low.FLData.clens_fldata_strong s sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Spec.Base.serializer",
"Prims.eq2",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserStrong",
"Prims.nat",
"LowParse.Low.FLData.gaccessor_fldata_strong'",
"Prims.unit",
"LowParse.Low.Base.Spec.gaccessor_prop_equiv",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata_strong_t",
"LowParse.Spec.FLData.parse_fldata_strong",
"LowParse.Low.FLData.clens_fldata_strong",
"LowParse.Low.Base.Spec.gaccessor"
] | [] | false | false | false | false | false | let gaccessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor (parse_fldata_strong s sz) p (clens_fldata_strong s sz)) =
| gaccessor_prop_equiv (parse_fldata_strong s sz)
p
(clens_fldata_strong s sz)
(gaccessor_fldata_strong' s sz);
gaccessor_fldata_strong' s sz | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.validate_fldata | val validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata p sz)) | val validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata p sz)) | let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32 | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 36,
"end_line": 132,
"start_col": 0,
"start_line": 122
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos' | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | v: LowParse.Low.Base.validator p -> sz: Prims.nat -> sz32: FStar.UInt32.t{FStar.UInt32.v sz32 == sz}
-> LowParse.Low.Base.validator (LowParse.Spec.FLData.parse_fldata p sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Low.Base.validator",
"Prims.nat",
"FStar.UInt32.t",
"Prims.eq2",
"Prims.int",
"Prims.l_or",
"FStar.UInt.size",
"FStar.UInt32.n",
"Prims.b2t",
"Prims.op_GreaterThanOrEqual",
"FStar.UInt32.v",
"Prims.op_Equality",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserConsumesAll",
"LowParse.Low.FLData.validate_fldata_consumes_all",
"Prims.bool",
"LowParse.Low.FLData.validate_fldata_gen",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata"
] | [] | false | false | false | false | false | let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata p sz)) =
| if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32 | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.valid_fldata_gen | val valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz))
))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_content_pos (parse_fldata p sz)
h
input
pos
(contents_exact p h input pos pos')
pos'))) | val valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz))
))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_content_pos (parse_fldata p sz)
h
input
pos
(contents_exact p h input pos pos')
pos'))) | let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 38,
"end_line": 36,
"start_col": 0,
"start_line": 12
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64 | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
p: LowParse.Spec.Base.parser k t ->
sz: Prims.nat ->
input: LowParse.Slice.slice rrel rel ->
pos: FStar.UInt32.t ->
h: FStar.Monotonic.HyperStack.mem
-> FStar.Pervasives.Lemma
(requires
FStar.UInt32.v pos + sz < 4294967296 /\
LowParse.Low.Base.Spec.valid_exact p
h
input
pos
(FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz)))
(ensures
FStar.UInt32.v pos + sz < 4294967296 /\
(let pos' = FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz) in
LowParse.Low.Base.Spec.valid_content_pos (LowParse.Spec.FLData.parse_fldata p sz)
h
input
pos
(LowParse.Low.Base.Spec.contents_exact p h input pos pos')
pos')) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"Prims.nat",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt32.t",
"FStar.Monotonic.HyperStack.mem",
"LowParse.Low.Base.Spec.contents_exact_eq",
"Prims.unit",
"LowParse.Low.Base.Spec.valid_exact_equiv",
"LowParse.Low.Base.Spec.valid_facts",
"LowParse.Slice.Mkslice",
"LowParse.Slice.__proj__Mkslice__item__base",
"FStar.UInt32.add",
"FStar.UInt32.uint_to_t",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata",
"Prims.l_and",
"Prims.b2t",
"Prims.op_LessThan",
"Prims.op_Addition",
"FStar.UInt32.v",
"LowParse.Low.Base.Spec.valid_exact",
"Prims.squash",
"LowParse.Low.Base.Spec.valid_content_pos",
"LowParse.Low.Base.Spec.contents_exact",
"Prims.Nil",
"FStar.Pervasives.pattern"
] | [] | true | false | true | false | false | let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel
#rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz))
))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_content_pos (parse_fldata p sz)
h
input
pos
(contents_exact p h input pos pos')
pos'))) =
| valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` (U32.uint_to_t sz) in
let input' = { base = input.base; len = pos' } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.jump_fldata_strong | val jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (jumper (parse_fldata_strong s sz)) | val jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (jumper (parse_fldata_strong s sz)) | let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata_strong s sz))
= jump_constant_size (parse_fldata_strong s sz) sz32 () | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 55,
"end_line": 228,
"start_col": 0,
"start_line": 220
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos
inline_for_extraction
let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 () | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
s: LowParse.Spec.Base.serializer p ->
sz: Prims.nat ->
sz32: FStar.UInt32.t{FStar.UInt32.v sz32 == sz}
-> LowParse.Low.Base.jumper (LowParse.Spec.FLData.parse_fldata_strong s sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Spec.Base.serializer",
"Prims.nat",
"FStar.UInt32.t",
"Prims.eq2",
"Prims.int",
"Prims.l_or",
"FStar.UInt.size",
"FStar.UInt32.n",
"Prims.b2t",
"Prims.op_GreaterThanOrEqual",
"FStar.UInt32.v",
"LowParse.Low.Base.jump_constant_size",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata_strong_t",
"LowParse.Spec.FLData.parse_fldata_strong",
"LowParse.Low.Base.jumper"
] | [] | false | false | false | false | false | let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (jumper (parse_fldata_strong s sz)) =
| jump_constant_size (parse_fldata_strong s sz) sz32 () | false |
Target.fst | Target.lookup | val lookup (s: subst) (i: A.ident) : option expr | val lookup (s: subst) (i: A.ident) : option expr | let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 22,
"end_line": 23,
"start_col": 0,
"start_line": 22
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | s: Target.subst -> i: Ast.ident -> FStar.Pervasives.Native.option Target.expr | Prims.Tot | [
"total"
] | [] | [
"Target.subst",
"Ast.ident",
"FStar.List.Tot.Base.assoc",
"Ast.ident'",
"Target.expr",
"Ast.__proj__Mkwith_meta_t__item__v",
"FStar.Pervasives.Native.option"
] | [] | false | false | false | true | false | let lookup (s: subst) (i: A.ident) : option expr =
| List.Tot.assoc i.v s | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.gaccessor_fldata' | val gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _)) | val gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _)) | let gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _))
= fun (input: bytes) -> (
let _ = match parse (parse_fldata p sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0
) | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 3,
"end_line": 245,
"start_col": 0,
"start_line": 230
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos
inline_for_extraction
let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 ()
inline_for_extraction
let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata_strong s sz))
= jump_constant_size (parse_fldata_strong s sz) sz32 () | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
p:
LowParse.Spec.Base.parser k t
{ Mkparser_kind'?.parser_kind_subkind k ==
FStar.Pervasives.Native.Some LowParse.Spec.Base.ParserStrong } ->
sz: Prims.nat
-> LowParse.Low.Base.Spec.gaccessor' (LowParse.Spec.FLData.parse_fldata p sz)
p
(LowParse.Low.Base.Spec.clens_id t) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"Prims.eq2",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserStrong",
"Prims.nat",
"LowParse.Bytes.bytes",
"Prims.unit",
"LowParse.Spec.Base.parse",
"LowParse.Spec.FLData.parse_fldata",
"LowParse.Spec.Base.consumed_length",
"Prims.op_Equality",
"LowParse.Spec.Base.parse_strong_prefix",
"FStar.Seq.Base.slice",
"LowParse.Bytes.byte",
"Prims.bool",
"LowParse.Low.Base.Spec.gaccessor'",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Low.Base.Spec.clens_id"
] | [] | false | false | false | false | false | let gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _)) =
| fun (input: bytes) ->
(let _ =
match parse (parse_fldata p sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz then parse_strong_prefix p (Seq.slice input 0 sz) input
in
0) | false |
Steel.ST.C.Types.UserStruct.fsti | Steel.ST.C.Types.UserStruct.get_set | val get_set
(#t: Type)
(sd: struct_def t)
(x: t)
(f: field_t sd.fields)
(v: sd.field_desc.fd_type f)
(f': field_t sd.fields)
: Lemma (sd.get (set sd x f v) f' == (if f = f' then v else sd.get x f'))
[SMTPat (sd.get (set sd x f v) f')] | val get_set
(#t: Type)
(sd: struct_def t)
(x: t)
(f: field_t sd.fields)
(v: sd.field_desc.fd_type f)
(f': field_t sd.fields)
: Lemma (sd.get (set sd x f v) f' == (if f = f' then v else sd.get x f'))
[SMTPat (sd.get (set sd x f v) f')] | let get_set (#t: Type) (sd: struct_def t) (x: t) (f: field_t sd.fields) (v: sd.field_desc.fd_type f) (f' : field_t sd.fields) : Lemma
(sd.get (set sd x f v) f' == (if f = f' then v else sd.get x f'))
[SMTPat (sd.get (set sd x f v) f')]
= sd.get_mk (set_aux sd x f v) f' | {
"file_name": "lib/steel/c/Steel.ST.C.Types.UserStruct.fsti",
"git_rev": "f984200f79bdc452374ae994a5ca837496476c41",
"git_url": "https://github.com/FStarLang/steel.git",
"project_name": "steel"
} | {
"end_col": 33,
"end_line": 66,
"start_col": 0,
"start_line": 63
} | module Steel.ST.C.Types.UserStruct
open Steel.ST.Util
open Steel.ST.C.Types.Struct.Aux
module Set = FStar.Set
(* This library allows the user to define their own struct type, with
a constructor from field values, and a destructor to field values for
each field. This may be necessary for recursive structs *)
let set_def
(#t: eqtype)
(s: FStar.Set.set t)
(x: t)
: Tot bool
= FStar.Set.mem x s
noextract
let nonempty_set (t: eqtype) =
(s: Set.set t { exists x . set_def s x == true })
noextract
let set_snoc // for associativity reasons
(#t: eqtype) (q: FStar.Set.set t) (a: t) : Pure (nonempty_set t)
(requires True)
(ensures (fun s ->
(forall (x: t). {:pattern FStar.Set.mem x s} FStar.Set.mem x s == (x = a || FStar.Set.mem x q))
))
= q `FStar.Set.union` FStar.Set.singleton a
[@@noextract_to "krml"]
let field_t (s: Set.set string) : Tot eqtype =
(f: string { Set.mem f s })
[@@noextract_to "krml"; norm_field_attr]
inline_for_extraction // for field_desc.fd_type
noeq
type struct_def (t: Type) = {
fields: Set.set string;
field_desc: field_description_gen_t (field_t fields);
mk: ((f: field_t fields) -> Tot (field_desc.fd_type f)) -> Tot t;
get: (t -> (f: field_t fields) -> Tot (field_desc.fd_type f));
get_mk: (phi: ((f: field_t fields) -> Tot (field_desc.fd_type f))) -> (f: field_t fields) -> Lemma
(get (mk phi) f == phi f);
extensionality: (x1: t) -> (x2: t) -> ((f: field_t fields) -> Lemma (get x1 f == get x2 f)) -> Lemma (x1 == x2);
}
let nonempty_set_nonempty_type (x: string) (s: Set.set string) : Lemma
(requires (x `Set.mem` s))
(ensures (exists (x: field_t s) . True))
= Classical.exists_intro (fun (_: field_t s) -> True) x
[@@noextract_to "krml"]
let set_aux
(#t: Type) (sd: struct_def t) (x: t) (f: field_t sd.fields) (v: sd.field_desc.fd_type f) (f': field_t sd.fields)
: Tot (sd.field_desc.fd_type f')
= if f = f' then v else sd.get x f'
[@@noextract_to "krml"]
let set (#t: Type) (sd: struct_def t) (x: t) (f: field_t sd.fields) (v: sd.field_desc.fd_type f) : Tot t =
sd.mk (set_aux sd x f v) | {
"checked_file": "/",
"dependencies": [
"Steel.ST.Util.fsti.checked",
"Steel.ST.C.Types.Struct.Aux.fsti.checked",
"Steel.FractionalPermission.fst.checked",
"prims.fst.checked",
"FStar.Set.fsti.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Ghost.fsti.checked",
"FStar.Classical.fsti.checked"
],
"interface_file": false,
"source_file": "Steel.ST.C.Types.UserStruct.fsti"
} | [
{
"abbrev": true,
"full_module": "FStar.Set",
"short_module": "Set"
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types.Struct.Aux",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.Util",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.ST.C.Types",
"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 |
sd: Steel.ST.C.Types.UserStruct.struct_def t ->
x: t ->
f: Steel.ST.C.Types.UserStruct.field_t (Mkstruct_def?.fields sd) ->
v: Mkfield_description_gen_t?.fd_type (Mkstruct_def?.field_desc sd) f ->
f': Steel.ST.C.Types.UserStruct.field_t (Mkstruct_def?.fields sd)
-> FStar.Pervasives.Lemma
(ensures
Mkstruct_def?.get sd (Steel.ST.C.Types.UserStruct.set sd x f v) f' ==
(match f = f' with
| true -> v
| _ -> Mkstruct_def?.get sd x f'))
[SMTPat (Mkstruct_def?.get sd (Steel.ST.C.Types.UserStruct.set sd x f v) f')] | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"Steel.ST.C.Types.UserStruct.struct_def",
"Steel.ST.C.Types.UserStruct.field_t",
"Steel.ST.C.Types.UserStruct.__proj__Mkstruct_def__item__fields",
"Steel.ST.C.Types.Struct.Aux.__proj__Mkfield_description_gen_t__item__fd_type",
"Steel.ST.C.Types.UserStruct.__proj__Mkstruct_def__item__field_desc",
"Steel.ST.C.Types.UserStruct.__proj__Mkstruct_def__item__get_mk",
"Steel.ST.C.Types.UserStruct.set_aux",
"Prims.unit",
"Prims.l_True",
"Prims.squash",
"Prims.eq2",
"Steel.ST.C.Types.UserStruct.__proj__Mkstruct_def__item__get",
"Steel.ST.C.Types.UserStruct.set",
"Prims.op_Equality",
"Prims.bool",
"Prims.Cons",
"FStar.Pervasives.pattern",
"FStar.Pervasives.smt_pat",
"Prims.Nil"
] | [] | true | false | true | false | false | let get_set
(#t: Type)
(sd: struct_def t)
(x: t)
(f: field_t sd.fields)
(v: sd.field_desc.fd_type f)
(f': field_t sd.fields)
: Lemma (sd.get (set sd x f v) f' == (if f = f' then v else sd.get x f'))
[SMTPat (sd.get (set sd x f v) f')] =
| sd.get_mk (set_aux sd x f v) f' | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.accessor_fldata_strong | val accessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (accessor (gaccessor_fldata_strong s sz)) | val accessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (accessor (gaccessor_fldata_strong s sz)) | let accessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p { k.parser_kind_subkind == Some ParserStrong })
(sz: nat)
: Tot (accessor (gaccessor_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = slice_access_eq h (gaccessor_fldata_strong s sz) input pos in
pos | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 5,
"end_line": 320,
"start_col": 0,
"start_line": 310
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos
inline_for_extraction
let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 ()
inline_for_extraction
let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata_strong s sz))
= jump_constant_size (parse_fldata_strong s sz) sz32 ()
let gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _))
= fun (input: bytes) -> (
let _ = match parse (parse_fldata p sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0
)
let gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _))
= gaccessor_prop_equiv (parse_fldata p sz) p (clens_id _) (gaccessor_fldata' p sz);
gaccessor_fldata' p sz
inline_for_extraction
let accessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (accessor (gaccessor_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = slice_access_eq h (gaccessor_fldata p sz) input pos in
pos
let clens_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
: Tot (clens (parse_fldata_strong_t s sz) t)
= {
clens_cond = (fun _ -> True);
clens_get = (fun (x: parse_fldata_strong_t s sz) -> (x <: t));
}
inline_for_extraction
let gaccessor_fldata_strong'
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p { k.parser_kind_subkind == Some ParserStrong })
(sz: nat)
: Tot (gaccessor' (parse_fldata_strong s sz) p (clens_fldata_strong s sz))
= fun (input: bytes) ->
let _ = match parse (parse_fldata_strong s sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0
inline_for_extraction
let gaccessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p { k.parser_kind_subkind == Some ParserStrong })
(sz: nat)
: Tot (gaccessor (parse_fldata_strong s sz) p (clens_fldata_strong s sz))
= gaccessor_prop_equiv (parse_fldata_strong s sz) p (clens_fldata_strong s sz) (gaccessor_fldata_strong' s sz);
gaccessor_fldata_strong' s sz | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
s:
LowParse.Spec.Base.serializer p
{ Mkparser_kind'?.parser_kind_subkind k ==
FStar.Pervasives.Native.Some LowParse.Spec.Base.ParserStrong } ->
sz: Prims.nat
-> LowParse.Low.Base.accessor (LowParse.Low.FLData.gaccessor_fldata_strong s sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Spec.Base.serializer",
"Prims.eq2",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserStrong",
"Prims.nat",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt32.t",
"Prims.unit",
"LowParse.Low.Base.Spec.slice_access_eq",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata_strong_t",
"LowParse.Spec.FLData.parse_fldata_strong",
"LowParse.Low.FLData.clens_fldata_strong",
"LowParse.Low.FLData.gaccessor_fldata_strong",
"FStar.Monotonic.HyperStack.mem",
"FStar.HyperStack.ST.get",
"LowParse.Low.Base.accessor"
] | [] | false | false | false | false | false | let accessor_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (accessor (gaccessor_fldata_strong s sz)) =
| fun #rrel #rel input pos ->
let h = HST.get () in
[@@ inline_let ]let _ = slice_access_eq h (gaccessor_fldata_strong s sz) input pos in
pos | false |
Target.fst | Target.parser_kind_eq | val parser_kind_eq (k k':parser_kind) : bool | val parser_kind_eq (k k':parser_kind) : bool | let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 81,
"start_col": 0,
"start_line": 68
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2 | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | k: Target.parser_kind -> k': Target.parser_kind -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Target.parser_kind",
"FStar.Pervasives.Native.Mktuple2",
"Target.parser_kind'",
"Target.__proj__Mkparser_kind__item__pk_kind",
"Ast.ident",
"Prims.op_Equality",
"Ast.ident'",
"Ast.__proj__Mkwith_meta_t__item__v",
"Target.parser_kind_eq",
"Prims.op_AmpAmp",
"FStar.Pervasives.Native.tuple2",
"Prims.bool"
] | [
"recursion"
] | false | false | false | true | false | let rec parser_kind_eq k k' =
| match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> let open A in hd1.v = hd2.v
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' -> parser_kind_eq k1 k1' && parser_kind_eq k2 k2'
| _ -> false | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.gaccessor_fldata_strong' | val gaccessor_fldata_strong'
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor' (parse_fldata_strong s sz) p (clens_fldata_strong s sz)) | val gaccessor_fldata_strong'
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor' (parse_fldata_strong s sz) p (clens_fldata_strong s sz)) | let gaccessor_fldata_strong'
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p { k.parser_kind_subkind == Some ParserStrong })
(sz: nat)
: Tot (gaccessor' (parse_fldata_strong s sz) p (clens_fldata_strong s sz))
= fun (input: bytes) ->
let _ = match parse (parse_fldata_strong s sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0 | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 5,
"end_line": 296,
"start_col": 0,
"start_line": 281
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata_strong s sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
[@inline_let] let _ = valid_facts (parse_fldata_strong s sz) h input (uint64_to_uint32 pos) in
validate_fldata v sz sz32 input pos
inline_for_extraction
let jump_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata p sz))
= jump_constant_size (parse_fldata p sz) sz32 ()
inline_for_extraction
let jump_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (jumper (parse_fldata_strong s sz))
= jump_constant_size (parse_fldata_strong s sz) sz32 ()
let gaccessor_fldata'
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor' (parse_fldata p sz) p (clens_id _))
= fun (input: bytes) -> (
let _ = match parse (parse_fldata p sz) input with
| None -> ()
| Some (_, consumed) ->
if consumed = sz
then parse_strong_prefix p (Seq.slice input 0 sz) input
else ()
in
0
)
let gaccessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (gaccessor (parse_fldata p sz) p (clens_id _))
= gaccessor_prop_equiv (parse_fldata p sz) p (clens_id _) (gaccessor_fldata' p sz);
gaccessor_fldata' p sz
inline_for_extraction
let accessor_fldata
(#k: parser_kind)
(#t: Type)
(p: parser k t { k.parser_kind_subkind == Some ParserStrong } )
(sz: nat)
: Tot (accessor (gaccessor_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = slice_access_eq h (gaccessor_fldata p sz) input pos in
pos
let clens_fldata_strong
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p)
(sz: nat)
: Tot (clens (parse_fldata_strong_t s sz) t)
= {
clens_cond = (fun _ -> True);
clens_get = (fun (x: parse_fldata_strong_t s sz) -> (x <: t));
} | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
s:
LowParse.Spec.Base.serializer p
{ Mkparser_kind'?.parser_kind_subkind k ==
FStar.Pervasives.Native.Some LowParse.Spec.Base.ParserStrong } ->
sz: Prims.nat
-> LowParse.Low.Base.Spec.gaccessor' (LowParse.Spec.FLData.parse_fldata_strong s sz)
p
(LowParse.Low.FLData.clens_fldata_strong s sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Spec.Base.serializer",
"Prims.eq2",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserStrong",
"Prims.nat",
"LowParse.Bytes.bytes",
"Prims.unit",
"LowParse.Spec.Base.parse",
"LowParse.Spec.FLData.parse_fldata_strong_t",
"LowParse.Spec.FLData.parse_fldata_strong",
"LowParse.Spec.Base.consumed_length",
"Prims.op_Equality",
"LowParse.Spec.Base.parse_strong_prefix",
"FStar.Seq.Base.slice",
"LowParse.Bytes.byte",
"Prims.bool",
"LowParse.Low.Base.Spec.gaccessor'",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Low.FLData.clens_fldata_strong"
] | [] | false | false | false | false | false | let gaccessor_fldata_strong'
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(s: serializer p {k.parser_kind_subkind == Some ParserStrong})
(sz: nat)
: Tot (gaccessor' (parse_fldata_strong s sz) p (clens_fldata_strong s sz)) =
| fun (input: bytes) ->
let _ =
match parse (parse_fldata_strong s sz) input with
| None -> ()
| Some (_, consumed) -> if consumed = sz then parse_strong_prefix p (Seq.slice input 0 sz) input
in
0 | false |
Target.fst | Target.maybe_mname_prefix | val maybe_mname_prefix (mname:string) (i:A.ident) : string | val maybe_mname_prefix (mname:string) (i:A.ident) : string | let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 62,
"end_line": 141,
"start_col": 0,
"start_line": 137
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
//////////////////////////////////////////////////////////////////////////////// | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> i: Ast.ident -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Prims.string",
"Ast.ident",
"Ast.__proj__Mkident'__item__modul_name",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.ident'",
"Prims.op_Equality",
"Prims.bool",
"FStar.Printf.sprintf"
] | [] | false | false | false | true | false | let maybe_mname_prefix (mname: string) (i: A.ident) =
| let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s | false |
Target.fst | Target.subst_exprs | val subst_exprs : s: Target.subst -> es: Prims.list (Target.expr' * Ast.range)
-> Prims.list (Target.expr' * Ast.range) | let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 56,
"end_line": 47,
"start_col": 0,
"start_line": 25
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | s: Target.subst -> es: Prims.list (Target.expr' * Ast.range)
-> Prims.list (Target.expr' * Ast.range) | Prims.Tot | [
"total"
] | [
"subst_expr",
"subst_exprs",
"subst_fields"
] | [
"Target.subst",
"Prims.list",
"FStar.Pervasives.Native.tuple2",
"Target.expr'",
"Ast.range",
"Prims.Nil",
"Prims.Cons",
"Target.subst_expr",
"Target.subst_exprs"
] | [
"mutual recursion"
] | false | false | false | true | false | let rec subst_exprs s es =
| match es with
| [] -> []
| e :: es -> subst_expr s e :: subst_exprs s es | false |
|
Target.fst | Target.subst_fields | val subst_fields : s: Target.subst -> fs: Prims.list (Ast.ident * (Target.expr' * Ast.range))
-> Prims.list (Ast.ident * (Target.expr' * Ast.range)) | let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 56,
"end_line": 47,
"start_col": 0,
"start_line": 25
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | s: Target.subst -> fs: Prims.list (Ast.ident * (Target.expr' * Ast.range))
-> Prims.list (Ast.ident * (Target.expr' * Ast.range)) | Prims.Tot | [
"total"
] | [
"subst_expr",
"subst_exprs",
"subst_fields"
] | [
"Target.subst",
"Prims.list",
"FStar.Pervasives.Native.tuple2",
"Ast.ident",
"Target.expr'",
"Ast.range",
"Prims.Nil",
"Prims.Cons",
"FStar.Pervasives.Native.Mktuple2",
"Target.subst_expr",
"Target.subst_fields"
] | [
"mutual recursion"
] | false | false | false | true | false | let rec subst_fields s fs =
| match fs with
| [] -> []
| (i, e) :: fs -> (i, subst_expr s e) :: subst_fields s fs | false |
|
Target.fst | Target.print_typedef_typ | val print_typedef_typ (tdn: typedef_name) : ML string | val print_typedef_typ (tdn: typedef_name) : ML string | let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params)) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 65,
"end_line": 529,
"start_col": 0,
"start_line": 525
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params)) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | tdn: Target.typedef_name -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.typedef_name",
"FStar.Printf.sprintf",
"Target.print_ident",
"Target.__proj__Mktypedef_name__item__td_name",
"Prims.string",
"FStar.String.concat",
"Prims.list",
"FStar.List.map",
"FStar.Pervasives.Native.tuple2",
"Ast.ident",
"Target.typ",
"Target.__proj__Mktypedef_name__item__td_params"
] | [] | false | true | false | false | false | let print_typedef_typ (tdn: typedef_name) : ML string =
| Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " " (List.map (fun (id, t) -> (print_ident id)) tdn.td_params)) | false |
Target.fst | Target.exprs_eq | val exprs_eq (es1 es1:list expr) : bool | val exprs_eq (es1 es1:list expr) : bool | let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 67,
"start_col": 0,
"start_line": 49
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | es1: Prims.list Target.expr -> es1: Prims.list Target.expr -> Prims.bool | Prims.Tot | [
"total"
] | [
"expr_eq",
"exprs_eq",
"fields_eq"
] | [
"Prims.list",
"Target.expr",
"FStar.Pervasives.Native.Mktuple2",
"Prims.op_AmpAmp",
"Target.expr_eq",
"Target.exprs_eq",
"FStar.Pervasives.Native.tuple2",
"Prims.bool"
] | [
"mutual recursion"
] | false | false | false | true | false | let rec exprs_eq es1 es2 =
| match es1, es2 with
| [], [] -> true
| e1 :: es1, e2 :: es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false | false |
Target.fst | Target.namespace_of_integer_type | val namespace_of_integer_type : _: Ast.integer_type -> Prims.string | let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 23,
"end_line": 175,
"start_col": 0,
"start_line": 169
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | _: Ast.integer_type -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Ast.integer_type",
"Prims.string"
] | [] | false | false | false | true | false | let namespace_of_integer_type =
| let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64" | false |
|
LowParse.Low.FLData.fst | LowParse.Low.FLData.valid_fldata_gen_elim | val valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma (requires (valid (parse_fldata p sz) h input pos))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
valid_content_pos (parse_fldata p sz)
h
input
pos
(contents_exact p h input pos pos')
pos'))) | val valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma (requires (valid (parse_fldata p sz) h input pos))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
valid_content_pos (parse_fldata p sz)
h
input
pos
(contents_exact p h input pos pos')
pos'))) | let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 38,
"end_line": 62,
"start_col": 0,
"start_line": 38
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
p: LowParse.Spec.Base.parser k t ->
sz: Prims.nat ->
input: LowParse.Slice.slice rrel rel ->
pos: FStar.UInt32.t ->
h: FStar.Monotonic.HyperStack.mem
-> FStar.Pervasives.Lemma
(requires LowParse.Low.Base.Spec.valid (LowParse.Spec.FLData.parse_fldata p sz) h input pos)
(ensures
FStar.UInt32.v pos + sz < 4294967296 /\
(let pos' = FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz) in
LowParse.Low.Base.Spec.valid_exact p
h
input
pos
(FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz)) /\
LowParse.Low.Base.Spec.valid_content_pos (LowParse.Spec.FLData.parse_fldata p sz)
h
input
pos
(LowParse.Low.Base.Spec.contents_exact p h input pos pos')
pos')) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"Prims.nat",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt32.t",
"FStar.Monotonic.HyperStack.mem",
"LowParse.Low.Base.Spec.contents_exact_eq",
"Prims.unit",
"LowParse.Low.Base.Spec.valid_exact_equiv",
"LowParse.Low.Base.Spec.valid_facts",
"LowParse.Slice.Mkslice",
"LowParse.Slice.__proj__Mkslice__item__base",
"FStar.UInt32.add",
"FStar.UInt32.uint_to_t",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata",
"LowParse.Low.Base.Spec.valid",
"Prims.squash",
"Prims.l_and",
"Prims.b2t",
"Prims.op_LessThan",
"Prims.op_Addition",
"FStar.UInt32.v",
"LowParse.Low.Base.Spec.valid_exact",
"LowParse.Low.Base.Spec.valid_content_pos",
"LowParse.Low.Base.Spec.contents_exact",
"Prims.Nil",
"FStar.Pervasives.pattern"
] | [] | true | false | true | false | false | let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel
#rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma (requires (valid (parse_fldata p sz) h input pos))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
valid_content_pos (parse_fldata p sz)
h
input
pos
(contents_exact p h input pos pos')
pos'))) =
| valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` (U32.uint_to_t sz) in
let input' = { base = input.base; len = pos' } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.validate_fldata_consumes_all | val validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz)) | val validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz)) | let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos' | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 13,
"end_line": 119,
"start_col": 0,
"start_line": 93
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos' | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
v: LowParse.Low.Base.validator p ->
sz: Prims.nat ->
sz32: FStar.UInt32.t{FStar.UInt32.v sz32 == sz} ->
sq:
Prims.squash (Mkparser_kind'?.parser_kind_subkind k ==
FStar.Pervasives.Native.Some LowParse.Spec.Base.ParserConsumesAll)
-> LowParse.Low.Base.validator (LowParse.Spec.FLData.parse_fldata p sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Low.Base.validator",
"Prims.nat",
"FStar.UInt32.t",
"Prims.eq2",
"Prims.int",
"Prims.l_or",
"FStar.UInt.size",
"FStar.UInt32.n",
"Prims.b2t",
"Prims.op_GreaterThanOrEqual",
"FStar.UInt32.v",
"Prims.squash",
"FStar.Pervasives.Native.option",
"LowParse.Spec.Base.parser_subkind",
"LowParse.Spec.Base.__proj__Mkparser_kind'__item__parser_kind_subkind",
"FStar.Pervasives.Native.Some",
"LowParse.Spec.Base.ParserConsumesAll",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt64.t",
"FStar.UInt64.lt",
"FStar.UInt64.sub",
"FStar.Int.Cast.uint32_to_uint64",
"LowParse.Slice.__proj__Mkslice__item__len",
"LowParse.Low.ErrorCode.validator_error_not_enough_data",
"Prims.bool",
"LowParse.Low.ErrorCode.is_error",
"Prims.op_Equality",
"LowParse.Low.ErrorCode.validator_error_generic",
"Prims.unit",
"LowParse.Low.Base.Spec.valid_facts",
"LowParse.Low.ErrorCode.uint64_to_uint32",
"LowParse.Slice.Mkslice",
"LowParse.Slice.__proj__Mkslice__item__base",
"FStar.UInt32.add",
"LowParse.Spec.FLData.parse_fldata_consumes_all_correct",
"LowParse.Slice.bytes_of_slice_from",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata",
"FStar.Monotonic.HyperStack.mem",
"FStar.HyperStack.ST.get"
] | [] | false | false | false | false | false | let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz)) =
| fun #rrel #rel input pos ->
let h = HST.get () in
[@@ inline_let ]let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if ((Cast.uint32_to_uint64 input.len) `U64.sub` pos) `U64.lt` (Cast.uint32_to_uint64 sz32)
then validator_error_not_enough_data
else
[@@ inline_let ]let input' =
{ base = input.base; len = (uint64_to_uint32 pos) `U32.add` sz32 }
in
[@@ inline_let ]let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then if pos' = validator_error_not_enough_data then validator_error_generic else pos'
else pos' | false |
Target.fst | Target.print_ident | val print_ident (i:A.ident) : string | val print_ident (i:A.ident) : string | let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 37,
"end_line": 150,
"start_col": 0,
"start_line": 143
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | i: Ast.ident -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Ast.ident",
"FStar.String.list_of_string",
"Ast.__proj__Mkident'__item__name",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.ident'",
"FStar.String.char",
"Prims.list",
"Prims.op_Equality",
"FStar.Char.char",
"FStar.Char.lowercase",
"Prims.bool",
"Prims.op_Hat",
"Ast.reserved_prefix",
"Prims.string"
] | [] | false | false | false | true | false | let print_ident (i: A.ident) =
| let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0 :: _ -> if FStar.Char.lowercase c0 = c0 then i.v.name else Ast.reserved_prefix ^ i.v.name | false |
Target.fst | Target.print_typedef_actions_inv_and_fp | val print_typedef_actions_inv_and_fp : td: Target.type_decl -> Prims.string * Prims.string | let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 11,
"end_line": 570,
"start_col": 0,
"start_line": 544
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | td: Target.type_decl -> Prims.string * Prims.string | Prims.Tot | [
"total"
] | [] | [
"Target.type_decl",
"FStar.Pervasives.Native.Mktuple2",
"Prims.string",
"FStar.List.Tot.Base.fold_right",
"FStar.Pervasives.Native.tuple2",
"Ast.ident",
"Target.typ",
"FStar.Printf.sprintf",
"Target.print_ident",
"Prims.bool",
"Prims.list",
"Prims.l_Forall",
"Prims.l_imp",
"FStar.List.Tot.Base.memP",
"Prims.b2t",
"Prims.op_AmpAmp",
"Target.uu___is_T_pointer",
"Prims.op_Negation",
"Prims.op_BarBar",
"Target.is_output_type",
"Target.is_extern_type",
"FStar.List.Tot.Base.filter",
"Target.__proj__Mktypedef_name__item__td_params",
"Target.__proj__Mktype_decl__item__decl_name",
"FStar.List.Tot.Base.existsb"
] | [] | false | false | false | true | false | let print_typedef_actions_inv_and_fp (td: type_decl) =
| let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params
in
let pointers =
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t))
td.decl_name.td_params
in
let inv =
List.Tot.fold_right (fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)" (print_ident x) out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right (fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)" (print_ident x) out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp | false |
|
Target.fst | Target.print_comments | val print_comments (cs: list string) : string | val print_comments (cs: list string) : string | let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 40,
"end_line": 577,
"start_col": 0,
"start_line": 572
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | cs: Prims.list Prims.string -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Prims.list",
"Prims.string",
"FStar.Printf.sprintf",
"FStar.String.concat"
] | [] | false | false | false | true | false | let print_comments (cs: list string) : string =
| match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c | false |
Target.fst | Target.fields_eq | val fields_eq (fs1 fs2:list (A.ident & expr)) : bool | val fields_eq (fs1 fs2:list (A.ident & expr)) : bool | let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 67,
"start_col": 0,
"start_line": 49
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | fs1: Prims.list (Ast.ident * Target.expr) -> fs2: Prims.list (Ast.ident * Target.expr) -> Prims.bool | Prims.Tot | [
"total"
] | [
"expr_eq",
"exprs_eq",
"fields_eq"
] | [
"Prims.list",
"FStar.Pervasives.Native.tuple2",
"Ast.ident",
"Target.expr",
"FStar.Pervasives.Native.Mktuple2",
"Prims.op_AmpAmp",
"Prims.op_Equality",
"Ast.ident'",
"Ast.__proj__Mkwith_meta_t__item__v",
"Target.fields_eq",
"Prims.bool"
] | [
"mutual recursion"
] | false | false | false | true | false | let rec fields_eq fs1 fs2 =
| match fs1, fs2 with
| [], [] -> true
| (i1, e1) :: fs1, (i2, e2) :: fs2 -> A.(i1.v = i2.v) && fields_eq fs1 fs2
| _ -> false | false |
Target.fst | Target.print_attributes | val print_attributes (entrypoint: bool) (attrs: decl_attributes) : string | val print_attributes (entrypoint: bool) (attrs: decl_attributes) : string | let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "") | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 69,
"end_line": 594,
"start_col": 0,
"start_line": 579
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | entrypoint: Prims.bool -> attrs: Target.decl_attributes -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Prims.bool",
"Target.decl_attributes",
"Target.__proj__Mkdecl_attributes__item__comments",
"Prims.op_BarBar",
"Target.__proj__Mkdecl_attributes__item__is_exported",
"Target.__proj__Mkdecl_attributes__item__should_inline",
"Prims.string",
"Prims.list",
"FStar.Printf.sprintf",
"Target.print_comments",
"Prims.op_AmpAmp",
"Prims.op_Negation"
] | [] | false | false | false | true | false | let print_attributes (entrypoint: bool) (attrs: decl_attributes) : string =
| match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline then "inline_for_extraction noextract\n" else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint && not attrs.is_exported && not attrs.should_inline then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "") | false |
Target.fst | Target.subst_expr | val subst_expr (s:subst) (e:expr) : expr | val subst_expr (s:subst) (e:expr) : expr | let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 56,
"end_line": 47,
"start_col": 0,
"start_line": 25
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | s: Target.subst -> e: Target.expr -> Target.expr | Prims.Tot | [
"total"
] | [
"subst_expr",
"subst_exprs",
"subst_fields"
] | [
"Target.subst",
"Target.expr",
"FStar.Pervasives.Native.fst",
"Target.expr'",
"Ast.range",
"Ast.constant",
"Ast.ident",
"Target.lookup",
"Target.op",
"Prims.list",
"FStar.Pervasives.Native.tuple2",
"FStar.Pervasives.Native.Mktuple2",
"Target.App",
"Target.subst_exprs",
"FStar.Pervasives.Native.snd",
"Target.Record",
"Target.subst_fields"
] | [
"mutual recursion"
] | false | false | false | true | false | let rec subst_expr (s: subst) (e: expr) : expr =
| match fst e with
| Constant _ -> e
| Identifier i ->
(match lookup s i with
| Some e' -> e'
| None -> e)
| App hd args -> (App hd (subst_exprs s args), snd e)
| Record tn fields -> (Record tn (subst_fields s fields), snd e) | false |
Target.fst | Target.print_field_id_name | val print_field_id_name : i: Ast.ident -> FStar.All.ALL Prims.string | let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 66,
"end_line": 159,
"start_col": 0,
"start_line": 155
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | i: Ast.ident -> FStar.All.ALL Prims.string | FStar.All.ALL | [] | [] | [
"Ast.ident",
"Ast.__proj__Mkident'__item__modul_name",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.ident'",
"FStar.All.failwith",
"Prims.string",
"FStar.Printf.sprintf",
"FStar.String.lowercase",
"Ast.__proj__Mkident'__item__name"
] | [] | false | true | false | false | false | let print_field_id_name (i: A.ident) =
| let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name | false |
|
Target.fst | Target.print_typedef_name | val print_typedef_name (mname: string) (tdn: typedef_name) : ML string | val print_typedef_name (mname: string) (tdn: typedef_name) : ML string | let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params)) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 36,
"end_line": 523,
"start_col": 0,
"start_line": 514
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> tdn: Target.typedef_name -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.typedef_name",
"FStar.Printf.sprintf",
"Target.print_ident",
"Target.__proj__Mktypedef_name__item__td_name",
"FStar.String.concat",
"Prims.list",
"FStar.List.map",
"FStar.Pervasives.Native.tuple2",
"Ast.ident",
"Target.typ",
"Target.print_typ",
"Target.__proj__Mktypedef_name__item__td_params"
] | [] | false | true | false | false | false | let print_typedef_name (mname: string) (tdn: typedef_name) : ML string =
| Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> Printf.sprintf "(%s:%s)" (print_ident id) (print_typ mname t))
tdn.td_params)) | false |
Target.fst | Target.expr_eq | val expr_eq (e1 e1:expr) : bool | val expr_eq (e1 e1:expr) : bool | let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 67,
"start_col": 0,
"start_line": 49
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | e1: Target.expr -> e1: Target.expr -> Prims.bool | Prims.Tot | [
"total"
] | [
"expr_eq",
"exprs_eq",
"fields_eq"
] | [
"Target.expr",
"FStar.Pervasives.Native.Mktuple2",
"Target.expr'",
"FStar.Pervasives.Native.fst",
"Ast.range",
"Ast.constant",
"Prims.op_Equality",
"Ast.ident",
"Ast.ident'",
"Ast.__proj__Mkwith_meta_t__item__v",
"Target.op",
"Prims.list",
"FStar.Pervasives.Native.tuple2",
"Prims.op_AmpAmp",
"Target.exprs_eq",
"Target.fields_eq",
"Prims.bool"
] | [
"mutual recursion"
] | false | false | false | true | false | let rec expr_eq e1 e2 =
| match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1 = c2
| Identifier i1, Identifier i2 -> let open A in i1.v = i2.v
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false | false |
Target.fst | Target.uppercase | val uppercase (name: string) : string | val uppercase (name: string) : string | let uppercase (name:string) : string = String.uppercase name | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 60,
"end_line": 724,
"start_col": 0,
"start_line": 724
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | name: Prims.string -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Prims.string",
"FStar.String.uppercase"
] | [] | false | false | false | true | false | let uppercase (name: string) : string =
| String.uppercase name | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.valid_fldata_strong_gen_elim | val valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma (requires (valid (parse_fldata_strong s sz) h input pos))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
(let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos')))) | val valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma (requires (valid (parse_fldata_strong s sz) h input pos))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
(let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos')))) | let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata_strong s sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
))))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 38,
"end_line": 191,
"start_col": 0,
"start_line": 164
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32
let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
s: LowParse.Spec.Base.serializer p ->
sz: Prims.nat ->
input: LowParse.Slice.slice rrel rel ->
pos: FStar.UInt32.t ->
h: FStar.Monotonic.HyperStack.mem
-> FStar.Pervasives.Lemma
(requires
LowParse.Low.Base.Spec.valid (LowParse.Spec.FLData.parse_fldata_strong s sz) h input pos)
(ensures
FStar.UInt32.v pos + sz < 4294967296 /\
(let pos' = FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz) in
LowParse.Low.Base.Spec.valid_exact p
h
input
pos
(FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz)) /\
(let x = LowParse.Low.Base.Spec.contents_exact p h input pos pos' in
FStar.Seq.Base.length (LowParse.Spec.Base.serialize s x) == sz /\
LowParse.Low.Base.Spec.valid_content_pos (LowParse.Spec.FLData.parse_fldata_strong s sz)
h
input
pos
x
pos'))) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Spec.Base.serializer",
"Prims.nat",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt32.t",
"FStar.Monotonic.HyperStack.mem",
"LowParse.Low.Base.Spec.contents_exact_eq",
"Prims.unit",
"LowParse.Low.Base.Spec.valid_exact_equiv",
"LowParse.Low.Base.Spec.valid_facts",
"LowParse.Slice.Mkslice",
"LowParse.Slice.__proj__Mkslice__item__base",
"FStar.UInt32.add",
"FStar.UInt32.uint_to_t",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata_strong_t",
"LowParse.Spec.FLData.parse_fldata_strong",
"LowParse.Low.Base.Spec.valid",
"Prims.squash",
"Prims.l_and",
"Prims.b2t",
"Prims.op_LessThan",
"Prims.op_Addition",
"FStar.UInt32.v",
"LowParse.Low.Base.Spec.valid_exact",
"Prims.eq2",
"FStar.Seq.Base.length",
"LowParse.Spec.Base.serialize",
"LowParse.Low.Base.Spec.valid_content_pos",
"LowParse.Low.Base.Spec.contents_exact",
"Prims.Nil",
"FStar.Pervasives.pattern"
] | [] | true | false | true | false | false | let valid_fldata_strong_gen_elim
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel
#rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma (requires (valid (parse_fldata_strong s sz) h input pos))
(ensures
(U32.v pos + sz < 4294967296 /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
(let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos')))) =
| valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` (U32.uint_to_t sz) in
let input' = { base = input.base; len = pos' } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.validate_fldata_gen | val validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata p sz)) | val validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata p sz)) | let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos' | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 13,
"end_line": 90,
"start_col": 0,
"start_line": 65
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | v: LowParse.Low.Base.validator p -> sz: Prims.nat -> sz32: FStar.UInt32.t{FStar.UInt32.v sz32 == sz}
-> LowParse.Low.Base.validator (LowParse.Spec.FLData.parse_fldata p sz) | Prims.Tot | [
"total"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Low.Base.validator",
"Prims.nat",
"FStar.UInt32.t",
"Prims.eq2",
"Prims.int",
"Prims.l_or",
"FStar.UInt.size",
"FStar.UInt32.n",
"Prims.b2t",
"Prims.op_GreaterThanOrEqual",
"FStar.UInt32.v",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt64.t",
"FStar.UInt64.lt",
"FStar.UInt64.sub",
"FStar.Int.Cast.uint32_to_uint64",
"LowParse.Slice.__proj__Mkslice__item__len",
"LowParse.Low.ErrorCode.validator_error_not_enough_data",
"Prims.bool",
"LowParse.Low.ErrorCode.is_error",
"Prims.op_Equality",
"LowParse.Low.ErrorCode.validator_error_generic",
"Prims.op_disEquality",
"Prims.unit",
"LowParse.Low.Base.Spec.valid_facts",
"LowParse.Low.ErrorCode.uint64_to_uint32",
"LowParse.Slice.Mkslice",
"LowParse.Slice.__proj__Mkslice__item__base",
"FStar.UInt32.add",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata",
"FStar.Monotonic.HyperStack.mem",
"FStar.HyperStack.ST.get"
] | [] | false | false | false | false | false | let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t{U32.v sz32 == sz})
: Tot (validator (parse_fldata p sz)) =
| fun #rrel #rel input pos ->
let h = HST.get () in
[@@ inline_let ]let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if ((Cast.uint32_to_uint64 input.len) `U64.sub` pos) `U64.lt` (Cast.uint32_to_uint64 sz32)
then validator_error_not_enough_data
else
[@@ inline_let ]let input' =
{ base = input.base; len = (uint64_to_uint32 pos) `U32.add` sz32 }
in
[@@ inline_let ]let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then if pos' = validator_error_not_enough_data then validator_error_generic else pos'
else if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32 then validator_error_generic else pos' | false |
Target.fst | Target.external_api_include | val external_api_include (modul: string) (ds: list decl) : string | val external_api_include (modul: string) (ds: list decl) : string | let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else "" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 9,
"end_line": 689,
"start_col": 0,
"start_line": 686
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | modul: Prims.string -> ds: Prims.list Target.decl -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Prims.string",
"Prims.list",
"Target.decl",
"Target.has_external_api",
"FStar.Printf.sprintf",
"Prims.bool"
] | [] | false | false | false | true | false | let external_api_include (modul: string) (ds: list decl) : string =
| if has_external_api ds then Printf.sprintf "open %s.ExternalAPI\n\n" modul else "" | false |
Target.fst | Target.wrapper_name | val wrapper_name (modul: string) (fn: string) : ML string | val wrapper_name (modul: string) (fn: string) : ML string | let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 16,
"end_line": 776,
"start_col": 0,
"start_line": 769
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | modul: Prims.string -> fn: Prims.string -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.pascal_case",
"FStar.Printf.sprintf"
] | [] | false | true | false | false | false | let wrapper_name (modul fn: string) : ML string =
| Printf.sprintf "%s_check_%s" modul fn |> pascal_case | false |
Target.fst | Target.get_output_typ_dep | val get_output_typ_dep (modul: string) (t: typ) : ML (option string) | val get_output_typ_dep (modul: string) (t: typ) : ML (option string) | let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 56,
"end_line": 767,
"start_col": 0,
"start_line": 760
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | modul: Prims.string -> t: Target.typ -> FStar.All.ML (FStar.Pervasives.Native.option Prims.string) | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.typ",
"Ast.range",
"Ast.comments",
"Ast.t_kind",
"Prims.list",
"FStar.Pervasives.either",
"Target.expr",
"FStar.Pervasives.Native.None",
"FStar.Pervasives.Native.option",
"Prims.op_Equality",
"Prims.bool",
"FStar.Pervasives.Native.Some",
"Target.get_output_typ_dep",
"FStar.All.failwith"
] | [
"recursion"
] | false | true | false | false | false | let rec get_output_typ_dep (modul: string) (t: typ) : ML (option string) =
| match t with
| T_app { v = { modul_name = None } } _ _ -> None
| T_app { v = { modul_name = Some m } } _ _ -> if m = modul then None else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type" | false |
Spec.K256.Lemmas.fst | Spec.K256.Lemmas.to_aff_point_negate_lemma | val to_aff_point_negate_lemma (p:proj_point) :
Lemma (to_aff_point (point_negate p) == aff_point_negate (to_aff_point p)) | val to_aff_point_negate_lemma (p:proj_point) :
Lemma (to_aff_point (point_negate p) == aff_point_negate (to_aff_point p)) | let to_aff_point_negate_lemma p =
let px, py, pz = p in
let qx, qy = to_aff_point (point_negate p) in
assert (qx == px /% pz /\ qy == (- py) % prime /% pz);
let ax, ay = aff_point_negate (to_aff_point p) in
assert (ax == px /% pz /\ ay == (- py /% pz) % prime);
let pz_inv = M.pow_mod #prime pz (prime - 2) in
calc (==) { // (-py) % prime /% pz;
((- py) % prime * pz_inv) % prime;
(==) { Math.Lemmas.lemma_mod_mul_distr_l (- py) pz_inv prime }
(- py * pz_inv) % prime;
(==) { Math.Lemmas.neg_mul_left py pz_inv }
(- (py * pz_inv)) % prime;
(==) { Math.Lemmas.lemma_mod_sub_distr 0 (py * pz_inv) prime }
(- (py * pz_inv) % prime) % prime; // (- py /% pz) % prime;
} | {
"file_name": "specs/lemmas/Spec.K256.Lemmas.fst",
"git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872",
"git_url": "https://github.com/project-everest/hacl-star.git",
"project_name": "hacl-star"
} | {
"end_col": 3,
"end_line": 74,
"start_col": 0,
"start_line": 58
} | module Spec.K256.Lemmas
open FStar.Mul
open Spec.K256.PointOps
module Euclid = FStar.Math.Euclid
module M = Lib.NatMod
#set-options "--z3rlimit 50 --ifuel 0 --fuel 0"
assume val prime_lemma: unit -> Lemma (Euclid.is_prime prime)
let lemma_aff_is_point_at_inf p =
prime_lemma ();
let (px, py, pz) = p in
M.lemma_div_mod_prime_is_zero #prime px pz;
M.lemma_div_mod_prime_is_zero #prime py pz
let lemma_proj_aff_id p =
let (px, py) = p in
let (pX, pY, pZ) = to_proj_point p in
assert (pX = px /\ pY = pY /\ pZ = one);
let (rx, ry) = to_aff_point (pX, pY, pZ) in
assert (rx = (pX /% pZ) /\ ry = (pY /% pZ));
M.lemma_div_mod_prime_one #prime pX;
M.lemma_div_mod_prime_one #prime pY;
assert (rx = pX /\ ry = pY)
let aff_point_at_inf_lemma p = ()
let aff_point_add_assoc_lemma p q s = admit()
let aff_point_add_comm_lemma p q = admit()
let aff_point_negate_lemma p =
let p_neg = aff_point_negate p in
let px, py = p in
let qx, qy = p_neg in
assert (qx = px /\ qy = (-py) % prime);
assert (aff_point_add p_neg p == aff_point_at_inf)
let to_aff_point_at_infinity_lemma () =
let px, py = to_aff_point point_at_inf in
assert (px == zero /% zero /\ py == one /% zero);
assert (px == zero *% M.pow_mod #prime zero (prime - 2));
M.lemma_pow_mod #prime zero (prime - 2);
assert (px == zero *% (M.pow zero (prime - 2) % prime));
M.lemma_pow_zero (prime - 2);
assert (px == zero /\ py == zero)
let to_aff_point_add_lemma p q = admit()
let to_aff_point_double_lemma p = admit() | {
"checked_file": "/",
"dependencies": [
"Spec.K256.PointOps.fst.checked",
"prims.fst.checked",
"Lib.NatMod.fsti.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.Math.Lemmas.fst.checked",
"FStar.Math.Euclid.fsti.checked",
"FStar.Calc.fsti.checked"
],
"interface_file": true,
"source_file": "Spec.K256.Lemmas.fst"
} | [
{
"abbrev": true,
"full_module": "Lib.NatMod",
"short_module": "M"
},
{
"abbrev": true,
"full_module": "FStar.Math.Euclid",
"short_module": "Euclid"
},
{
"abbrev": true,
"full_module": "Lib.NatMod",
"short_module": "LM"
},
{
"abbrev": false,
"full_module": "Spec.K256.PointOps",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Mul",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec.K256",
"short_module": null
},
{
"abbrev": false,
"full_module": "Spec.K256",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 0,
"initial_ifuel": 0,
"max_fuel": 0,
"max_ifuel": 0,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": false,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 50,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | p: Spec.K256.PointOps.proj_point
-> FStar.Pervasives.Lemma
(ensures
Spec.K256.PointOps.to_aff_point (Spec.K256.PointOps.point_negate p) ==
Spec.K256.PointOps.aff_point_negate (Spec.K256.PointOps.to_aff_point p)) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"Spec.K256.PointOps.proj_point",
"Spec.K256.PointOps.felem",
"FStar.Calc.calc_finish",
"Prims.int",
"Prims.eq2",
"Prims.op_Modulus",
"FStar.Mul.op_Star",
"Prims.op_Minus",
"Spec.K256.PointOps.prime",
"Prims.Cons",
"FStar.Preorder.relation",
"Prims.Nil",
"Prims.unit",
"FStar.Calc.calc_step",
"FStar.Calc.calc_init",
"FStar.Calc.calc_pack",
"FStar.Math.Lemmas.lemma_mod_mul_distr_l",
"Prims.squash",
"FStar.Math.Lemmas.neg_mul_left",
"FStar.Math.Lemmas.lemma_mod_sub_distr",
"Lib.NatMod.nat_mod",
"Lib.NatMod.pow_mod",
"Prims.op_Subtraction",
"Prims._assert",
"Prims.l_and",
"Spec.K256.PointOps.op_Slash_Percent",
"Spec.K256.PointOps.aff_point",
"Spec.K256.PointOps.aff_point_negate",
"Spec.K256.PointOps.to_aff_point",
"Spec.K256.PointOps.point_negate"
] | [] | false | false | true | false | false | let to_aff_point_negate_lemma p =
| let px, py, pz = p in
let qx, qy = to_aff_point (point_negate p) in
assert (qx == px /% pz /\ qy == (- py) % prime /% pz);
let ax, ay = aff_point_negate (to_aff_point p) in
assert (ax == px /% pz /\ ay == (- py /% pz) % prime);
let pz_inv = M.pow_mod #prime pz (prime - 2) in
calc ( == ) {
(((- py) % prime) * pz_inv) % prime;
( == ) { Math.Lemmas.lemma_mod_mul_distr_l (- py) pz_inv prime }
(- py * pz_inv) % prime;
( == ) { Math.Lemmas.neg_mul_left py pz_inv }
(- (py * pz_inv)) % prime;
( == ) { Math.Lemmas.lemma_mod_sub_distr 0 (py * pz_inv) prime }
(- (py * pz_inv) % prime) % prime;
} | false |
Target.fst | Target.validator_name | val validator_name (modul: string) (fn: string) : ML string | val validator_name (modul: string) (fn: string) : ML string | let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 16,
"end_line": 785,
"start_col": 0,
"start_line": 778
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | modul: Prims.string -> fn: Prims.string -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.pascal_case",
"FStar.Printf.sprintf"
] | [] | false | true | false | false | false | let validator_name (modul fn: string) : ML string =
| Printf.sprintf "%s_validate_%s" modul fn |> pascal_case | false |
Target.fst | Target.integer_type_of_arith_op | val integer_type_of_arith_op : o: Target.op{Target.arith_op o} -> Ast.integer_type | let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 21,
"end_line": 213,
"start_col": 0,
"start_line": 201
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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: Target.op{Target.arith_op o} -> Ast.integer_type | Prims.Tot | [
"total"
] | [] | [
"Target.op",
"Prims.b2t",
"Target.arith_op",
"Ast.integer_type"
] | [] | false | false | false | false | false | let integer_type_of_arith_op (o: op{arith_op o}) =
| match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t | false |
|
Target.fst | Target.print_integer_type | val print_integer_type : _: Ast.integer_type -> Prims.string | let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 23,
"end_line": 167,
"start_col": 0,
"start_line": 161
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | _: Ast.integer_type -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Ast.integer_type",
"Prims.string"
] | [] | false | false | false | true | false | let print_integer_type =
| let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64" | false |
|
Target.fst | Target.out_bt_name | val out_bt_name (t: typ) : ML string | val out_bt_name (t: typ) : ML string | let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 71,
"end_line": 1037,
"start_col": 0,
"start_line": 1033
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | t: Target.typ -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.typ",
"Ast.ident",
"Ast.t_kind",
"Prims.list",
"FStar.Pervasives.either",
"Target.expr",
"Ast.ident_name",
"Prims.string",
"Target.out_bt_name",
"FStar.All.failwith"
] | [
"recursion"
] | false | true | false | false | false | let rec out_bt_name (t: typ) : ML string =
| match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!" | false |
Target.fst | Target.print_as_c_type | val print_as_c_type (t: typ) : ML string | val print_as_c_type (t: typ) : ML string | let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 22,
"end_line": 748,
"start_col": 0,
"start_line": 726
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | t: Target.typ -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.typ",
"FStar.Printf.sprintf",
"Prims.string",
"Target.print_as_c_type",
"FStar.Pervasives.Native.option",
"Ast.range",
"Ast.comments",
"Ast.t_kind",
"Target.uppercase"
] | [
"recursion"
] | false | true | false | false | false | let rec print_as_c_type (t: typ) : ML string =
| let open Ast in
match t with
| T_pointer t -> Printf.sprintf "%s*" (print_as_c_type t)
| T_app { v = { name = "Bool" } } _ [] -> "BOOLEAN"
| T_app { v = { name = "UINT8" } } _ [] -> "uint8_t"
| T_app { v = { name = "UINT16" } } _ [] -> "uint16_t"
| T_app { v = { name = "UINT32" } } _ [] -> "uint32_t"
| T_app { v = { name = "UINT64" } } _ [] -> "uint64_t"
| T_app { v = { name = "PUINT8" } } _ [] -> "uint8_t*"
| T_app { v = { name = x } } KindSpec [] -> x
| T_app { v = { name = x } } _ [] -> uppercase x
| _ -> "__UNKNOWN__" | false |
Target.fst | Target.is_extern_type | val is_extern_type (t: typ) : bool | val is_extern_type (t: typ) : bool | let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 376,
"start_col": 0,
"start_line": 372
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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: Target.typ -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Target.typ",
"Ast.ident",
"Target.is_extern_type",
"Prims.bool"
] | [
"recursion"
] | false | false | false | true | false | let rec is_extern_type (t: typ) : bool =
| match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false | false |
Target.fst | Target.print_bitfield_bit_order | val print_bitfield_bit_order : _: Ast.bitfield_bit_order -> Prims.string | let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 30,
"end_line": 271,
"start_col": 0,
"start_line": 269
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | _: Ast.bitfield_bit_order -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Ast.bitfield_bit_order",
"Prims.string"
] | [] | false | false | false | true | false | let print_bitfield_bit_order =
| function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first" | false |
|
Target.fst | Target.print_lam | val print_lam (#a: Type) (f: (a -> ML string)) (x: lam a) : ML string | val print_lam (#a: Type) (f: (a -> ML string)) (x: lam a) : ML string | let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 18,
"end_line": 361,
"start_col": 0,
"start_line": 355
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 -> FStar.All.ML Prims.string) -> x: Target.lam a -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.lam",
"Ast.ident",
"FStar.Printf.sprintf",
"Target.print_ident"
] | [] | false | true | false | false | false | let print_lam (#a: Type) (f: (a -> ML string)) (x: lam a) : ML string =
| match x with
| Some x, y -> Printf.sprintf ("(fun %s -> %s)") (print_ident x) (f y)
| None, y -> f y | false |
Target.fst | Target.out_expr_bt_name | val out_expr_bt_name (oe: output_expr) : ML string | val out_expr_bt_name (oe: output_expr) : ML string | let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 72,
"end_line": 1039,
"start_col": 0,
"start_line": 1039
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | oe: Target.output_expr -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.output_expr",
"Target.out_bt_name",
"Target.__proj__Mkoutput_expr__item__oe_bt",
"Prims.string"
] | [] | false | true | false | false | false | let out_expr_bt_name (oe: output_expr) : ML string =
| out_bt_name oe.oe_bt | false |
Target.fst | Target.print_arith_op | val print_arith_op (o: op{arith_op o}) (r: option A.range) : ML string | val print_arith_op (o: op{arith_op o}) (r: option A.range) : ML string | let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 33,
"end_line": 256,
"start_col": 0,
"start_line": 218
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0 | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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: Target.op{Target.arith_op o} -> r: FStar.Pervasives.Native.option Ast.range
-> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.op",
"Prims.b2t",
"Target.arith_op",
"FStar.Pervasives.Native.option",
"Ast.range",
"FStar.Printf.sprintf",
"Target.print_range",
"Ast.dummy_range",
"Prims.string",
"Target.integer_type_of_arith_op",
"Prims.bool",
"Target.print_arith_op_range",
"Ast.integer_type"
] | [] | false | true | false | false | false | let print_arith_op (o: op{arith_op o}) (r: option A.range) : ML string =
| let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r =
match r with
| Some r -> r
| None -> A.dummy_range
in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s" t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn | false |
LowStar.BufferView.fsti | LowStar.BufferView.as_buffer_t | val as_buffer_t : b: LowStar.BufferView.buffer dest -> Type0 | let as_buffer_t (#dest:Type) (b:buffer dest) = B.mbuffer (Mkdtuple4?._1 b) (Mkdtuple4?._2 b) (Mkdtuple4?._3 b) | {
"file_name": "ulib/LowStar.BufferView.fsti",
"git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3",
"git_url": "https://github.com/FStarLang/FStar.git",
"project_name": "FStar"
} | {
"end_col": 110,
"end_line": 82,
"start_col": 0,
"start_line": 82
} | (*
Copyright 2008-2018 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module LowStar.BufferView
(**
* A "view" on a buffer allows treating a
* `Buffer.buffer a` as a
* `BufferView.buffer b`
*
* A "view" on a buffer is intended for specification purposes only
* It does not correspond to a pointer cast in C.
*
* Building a view requires providing a pair of mutually inverse functions
* from sequences of `a` (sub-sequences of the source buffer)
* to elements of `b`.
*
**)
open LowStar.Monotonic.Buffer
module HS=FStar.HyperStack
module B=LowStar.Monotonic.Buffer
(** Definition of a view **)
/// `f` and `g` are mutual inverses
let inverses #a #b
(f: (a -> GTot b))
(g: (b -> GTot a)) =
(forall x. g (f x) == x) /\
(forall y. f (g y) == y)
/// `view a b` maps `n`-lengthed sequences of `a` to a single `b`
noeq
type view (a:Type) (b:Type) =
| View : n:pos ->
get:(Seq.lseq a n -> GTot b) ->
put:(b -> GTot (Seq.lseq a n)) {
inverses get put
} ->
view a b
/// `buffer_views src dest`:
///
/// The main abstract type provided by this module. This type is
/// indexed by both the `src` and `dest` types. The former (`src`) is
/// the type of the underlying B.buffer's contents: as such, it is
/// forced to be in universe 0.
///
/// The destination type `dest` is for specification only and is not
/// subject to the same universe constraints by the memory model.
val buffer_view (src:Type0) (rrel rel:B.srel src) (dest:Type u#b) : Type u#b
/// `buffer b`: In contrast to `buffer_view`, `buffer b` hides the
/// source type of the view. As such, it is likely more convenient to
/// use in specifications and the rest of this interface is designed
/// around this type.
///
/// However, the type has a higher universe, and
/// this means, for instance, that values of `buffer b` cannot be
/// stored in the heap.
///
/// We leave its definition transparent in case clients wish to
/// manipulate both the `src` and `dest` types explicitly (e.g., to
/// stay in a lower universe)
let buffer (dest:Type u#a) : Type u#(max a 1) = (src:Type0 & rrel:B.srel src & rel:B.srel src & buffer_view src rrel rel dest) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Monotonic.Buffer.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowStar.BufferView.fsti"
} | [
{
"abbrev": true,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": "B"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": false,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"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 | b: LowStar.BufferView.buffer dest -> Type0 | Prims.Tot | [
"total"
] | [] | [
"LowStar.BufferView.buffer",
"LowStar.Monotonic.Buffer.mbuffer",
"FStar.Pervasives.__proj__Mkdtuple4__item___1",
"LowStar.Monotonic.Buffer.srel",
"LowStar.BufferView.buffer_view",
"FStar.Pervasives.__proj__Mkdtuple4__item___2",
"FStar.Pervasives.__proj__Mkdtuple4__item___3"
] | [] | false | false | false | true | true | let as_buffer_t (#dest: Type) (b: buffer dest) =
| B.mbuffer (Mkdtuple4?._1 b) (Mkdtuple4?._2 b) (Mkdtuple4?._3 b) | false |
|
LowStar.BufferView.fsti | LowStar.BufferView.inverses | val inverses : f: (_: a -> Prims.GTot b) -> g: (_: b -> Prims.GTot a) -> Prims.logical | let inverses #a #b
(f: (a -> GTot b))
(g: (b -> GTot a)) =
(forall x. g (f x) == x) /\
(forall y. f (g y) == y) | {
"file_name": "ulib/LowStar.BufferView.fsti",
"git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3",
"git_url": "https://github.com/FStarLang/FStar.git",
"project_name": "FStar"
} | {
"end_col": 26,
"end_line": 43,
"start_col": 0,
"start_line": 39
} | (*
Copyright 2008-2018 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module LowStar.BufferView
(**
* A "view" on a buffer allows treating a
* `Buffer.buffer a` as a
* `BufferView.buffer b`
*
* A "view" on a buffer is intended for specification purposes only
* It does not correspond to a pointer cast in C.
*
* Building a view requires providing a pair of mutually inverse functions
* from sequences of `a` (sub-sequences of the source buffer)
* to elements of `b`.
*
**)
open LowStar.Monotonic.Buffer
module HS=FStar.HyperStack
module B=LowStar.Monotonic.Buffer
(** Definition of a view **) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Monotonic.Buffer.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowStar.BufferView.fsti"
} | [
{
"abbrev": true,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": "B"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": false,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"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 -> Prims.GTot b) -> g: (_: b -> Prims.GTot a) -> Prims.logical | Prims.Tot | [
"total"
] | [] | [
"Prims.l_and",
"Prims.l_Forall",
"Prims.eq2",
"Prims.logical"
] | [] | false | false | false | false | true | let inverses #a #b (f: (a -> GTot b)) (g: (b -> GTot a)) =
| (forall x. g (f x) == x) /\ (forall y. f (g y) == y) | false |
|
Target.fst | Target.print_op_with_range | val print_op_with_range : ropt: FStar.Pervasives.Native.option Ast.range -> o: Target.op -> FStar.All.ALL Prims.string | let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 303,
"start_col": 0,
"start_line": 273
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | ropt: FStar.Pervasives.Native.option Ast.range -> o: Target.op -> FStar.All.ALL Prims.string | FStar.All.ALL | [] | [] | [
"FStar.Pervasives.Native.option",
"Ast.range",
"Target.op",
"Prims.string",
"Ast.integer_type",
"Target.print_arith_op",
"FStar.Printf.sprintf",
"Target.namespace_of_integer_type",
"Prims.int",
"Ast.bitfield_bit_order",
"Target.print_bitfield_bit_order",
"Prims.op_Equality",
"Prims.bool",
"Target.print_integer_type"
] | [] | false | true | false | false | false | let print_op_with_range ropt o =
| match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s | false |
|
Target.fst | Target.base_output_type | val base_output_type (t: typ) : ML A.ident | val base_output_type (t: typ) : ML A.ident | let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 73,
"end_line": 1066,
"start_col": 0,
"start_line": 1062
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | t: Target.typ -> FStar.All.ML Ast.ident | FStar.All.ML | [
"ml"
] | [] | [
"Target.typ",
"Ast.ident",
"Target.base_output_type",
"FStar.All.failwith"
] | [
"recursion"
] | false | true | false | false | false | let rec base_output_type (t: typ) : ML A.ident =
| match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type" | false |
LowStar.BufferView.fsti | LowStar.BufferView.live | val live : h: FStar.Monotonic.HyperStack.mem -> vb: LowStar.BufferView.buffer b -> Type0 | let live #b h (vb:buffer b) = live h (as_buffer vb) | {
"file_name": "ulib/LowStar.BufferView.fsti",
"git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3",
"git_url": "https://github.com/FStarLang/FStar.git",
"project_name": "FStar"
} | {
"end_col": 51,
"end_line": 126,
"start_col": 0,
"start_line": 126
} | (*
Copyright 2008-2018 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module LowStar.BufferView
(**
* A "view" on a buffer allows treating a
* `Buffer.buffer a` as a
* `BufferView.buffer b`
*
* A "view" on a buffer is intended for specification purposes only
* It does not correspond to a pointer cast in C.
*
* Building a view requires providing a pair of mutually inverse functions
* from sequences of `a` (sub-sequences of the source buffer)
* to elements of `b`.
*
**)
open LowStar.Monotonic.Buffer
module HS=FStar.HyperStack
module B=LowStar.Monotonic.Buffer
(** Definition of a view **)
/// `f` and `g` are mutual inverses
let inverses #a #b
(f: (a -> GTot b))
(g: (b -> GTot a)) =
(forall x. g (f x) == x) /\
(forall y. f (g y) == y)
/// `view a b` maps `n`-lengthed sequences of `a` to a single `b`
noeq
type view (a:Type) (b:Type) =
| View : n:pos ->
get:(Seq.lseq a n -> GTot b) ->
put:(b -> GTot (Seq.lseq a n)) {
inverses get put
} ->
view a b
/// `buffer_views src dest`:
///
/// The main abstract type provided by this module. This type is
/// indexed by both the `src` and `dest` types. The former (`src`) is
/// the type of the underlying B.buffer's contents: as such, it is
/// forced to be in universe 0.
///
/// The destination type `dest` is for specification only and is not
/// subject to the same universe constraints by the memory model.
val buffer_view (src:Type0) (rrel rel:B.srel src) (dest:Type u#b) : Type u#b
/// `buffer b`: In contrast to `buffer_view`, `buffer b` hides the
/// source type of the view. As such, it is likely more convenient to
/// use in specifications and the rest of this interface is designed
/// around this type.
///
/// However, the type has a higher universe, and
/// this means, for instance, that values of `buffer b` cannot be
/// stored in the heap.
///
/// We leave its definition transparent in case clients wish to
/// manipulate both the `src` and `dest` types explicitly (e.g., to
/// stay in a lower universe)
let buffer (dest:Type u#a) : Type u#(max a 1) = (src:Type0 & rrel:B.srel src & rel:B.srel src & buffer_view src rrel rel dest)
let as_buffer_t (#dest:Type) (b:buffer dest) = B.mbuffer (Mkdtuple4?._1 b) (Mkdtuple4?._2 b) (Mkdtuple4?._3 b)
/// `mk_buffer_view`: The main constructor
val mk_buffer_view (#src:Type0) (#rrel #rel:B.srel src) (#dest:Type)
(b:B.mbuffer src rrel rel)
(v:view src dest{
length b % View?.n v == 0
})
: GTot (buffer dest)
/// `as_buffer`: Projecting the underlying B.buffer from its view
val as_buffer (#b:Type) (v:buffer b) : as_buffer_t v
/// A lemma-relating projector to constructor
val as_buffer_mk_buffer_view (#src:Type0) (#rrel #rel:B.srel src) (#dest:Type)
(b:B.mbuffer src rrel rel)
(v:view src dest{
length b % View?.n v == 0
})
: Lemma (let bv = mk_buffer_view b v in
Mkdtuple4?._1 bv == src /\
Mkdtuple4?._2 bv == rrel /\
Mkdtuple4?._3 bv == rel /\
as_buffer bv == b)
[SMTPat (as_buffer (mk_buffer_view b v))]
/// `get_view`: Projecting the view functions itself
val get_view (#b : Type) (v:buffer b) : view (Mkdtuple4?._1 v) b
/// A lemma-relating projector to constructor
val get_view_mk_buffer_view (#src:Type0) (#rrel #rel:B.srel src) (#dest:Type)
(b:B.mbuffer src rrel rel)
(v:view src dest{
length b % View?.n v == 0
})
: Lemma (let bv = mk_buffer_view b v in
Mkdtuple4?._1 bv == src /\
get_view bv == v)
[SMTPat (get_view (mk_buffer_view b v))]
/// `live h vb`: liveness of a buffer view corresponds to liveness of
/// the underlying buffer | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Monotonic.Buffer.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowStar.BufferView.fsti"
} | [
{
"abbrev": true,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": "B"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": false,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"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: FStar.Monotonic.HyperStack.mem -> vb: LowStar.BufferView.buffer b -> Type0 | Prims.Tot | [
"total"
] | [] | [
"FStar.Monotonic.HyperStack.mem",
"LowStar.BufferView.buffer",
"LowStar.Monotonic.Buffer.live",
"FStar.Pervasives.__proj__Mkdtuple4__item___1",
"LowStar.Monotonic.Buffer.srel",
"LowStar.BufferView.buffer_view",
"FStar.Pervasives.__proj__Mkdtuple4__item___2",
"FStar.Pervasives.__proj__Mkdtuple4__item___3",
"LowStar.BufferView.as_buffer"
] | [] | false | false | false | true | true | let live #b h (vb: buffer b) =
| live h (as_buffer vb) | false |
|
LowStar.BufferView.fsti | LowStar.BufferView.buffer | val buffer (dest: Type u#a) : Type u#(max a 1) | val buffer (dest: Type u#a) : Type u#(max a 1) | let buffer (dest:Type u#a) : Type u#(max a 1) = (src:Type0 & rrel:B.srel src & rel:B.srel src & buffer_view src rrel rel dest) | {
"file_name": "ulib/LowStar.BufferView.fsti",
"git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3",
"git_url": "https://github.com/FStarLang/FStar.git",
"project_name": "FStar"
} | {
"end_col": 126,
"end_line": 80,
"start_col": 0,
"start_line": 80
} | (*
Copyright 2008-2018 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module LowStar.BufferView
(**
* A "view" on a buffer allows treating a
* `Buffer.buffer a` as a
* `BufferView.buffer b`
*
* A "view" on a buffer is intended for specification purposes only
* It does not correspond to a pointer cast in C.
*
* Building a view requires providing a pair of mutually inverse functions
* from sequences of `a` (sub-sequences of the source buffer)
* to elements of `b`.
*
**)
open LowStar.Monotonic.Buffer
module HS=FStar.HyperStack
module B=LowStar.Monotonic.Buffer
(** Definition of a view **)
/// `f` and `g` are mutual inverses
let inverses #a #b
(f: (a -> GTot b))
(g: (b -> GTot a)) =
(forall x. g (f x) == x) /\
(forall y. f (g y) == y)
/// `view a b` maps `n`-lengthed sequences of `a` to a single `b`
noeq
type view (a:Type) (b:Type) =
| View : n:pos ->
get:(Seq.lseq a n -> GTot b) ->
put:(b -> GTot (Seq.lseq a n)) {
inverses get put
} ->
view a b
/// `buffer_views src dest`:
///
/// The main abstract type provided by this module. This type is
/// indexed by both the `src` and `dest` types. The former (`src`) is
/// the type of the underlying B.buffer's contents: as such, it is
/// forced to be in universe 0.
///
/// The destination type `dest` is for specification only and is not
/// subject to the same universe constraints by the memory model.
val buffer_view (src:Type0) (rrel rel:B.srel src) (dest:Type u#b) : Type u#b
/// `buffer b`: In contrast to `buffer_view`, `buffer b` hides the
/// source type of the view. As such, it is likely more convenient to
/// use in specifications and the rest of this interface is designed
/// around this type.
///
/// However, the type has a higher universe, and
/// this means, for instance, that values of `buffer b` cannot be
/// stored in the heap.
///
/// We leave its definition transparent in case clients wish to
/// manipulate both the `src` and `dest` types explicitly (e.g., to
/// stay in a lower universe) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Monotonic.Buffer.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowStar.BufferView.fsti"
} | [
{
"abbrev": true,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": "B"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": false,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"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 | dest: Type -> Type | Prims.Tot | [
"total"
] | [] | [
"FStar.Pervasives.dtuple4",
"LowStar.Monotonic.Buffer.srel",
"LowStar.BufferView.buffer_view"
] | [] | false | false | false | true | true | let buffer (dest: Type u#a) : Type u#(max a 1) =
| (src: Type0 & rrel: B.srel src & rel: B.srel src & buffer_view src rrel rel dest) | false |
LowStar.BufferView.fsti | LowStar.BufferView.modifies | val modifies : vb: LowStar.BufferView.buffer b ->
h: FStar.Monotonic.HyperStack.mem ->
h': FStar.Monotonic.HyperStack.mem
-> Type0 | let modifies (#b: _)
(vb:buffer b)
(h h':HS.mem)
= B.modifies (B.loc_buffer (as_buffer vb)) h h' | {
"file_name": "ulib/LowStar.BufferView.fsti",
"git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3",
"git_url": "https://github.com/FStarLang/FStar.git",
"project_name": "FStar"
} | {
"end_col": 51,
"end_line": 193,
"start_col": 0,
"start_line": 190
} | (*
Copyright 2008-2018 Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module LowStar.BufferView
(**
* A "view" on a buffer allows treating a
* `Buffer.buffer a` as a
* `BufferView.buffer b`
*
* A "view" on a buffer is intended for specification purposes only
* It does not correspond to a pointer cast in C.
*
* Building a view requires providing a pair of mutually inverse functions
* from sequences of `a` (sub-sequences of the source buffer)
* to elements of `b`.
*
**)
open LowStar.Monotonic.Buffer
module HS=FStar.HyperStack
module B=LowStar.Monotonic.Buffer
(** Definition of a view **)
/// `f` and `g` are mutual inverses
let inverses #a #b
(f: (a -> GTot b))
(g: (b -> GTot a)) =
(forall x. g (f x) == x) /\
(forall y. f (g y) == y)
/// `view a b` maps `n`-lengthed sequences of `a` to a single `b`
noeq
type view (a:Type) (b:Type) =
| View : n:pos ->
get:(Seq.lseq a n -> GTot b) ->
put:(b -> GTot (Seq.lseq a n)) {
inverses get put
} ->
view a b
/// `buffer_views src dest`:
///
/// The main abstract type provided by this module. This type is
/// indexed by both the `src` and `dest` types. The former (`src`) is
/// the type of the underlying B.buffer's contents: as such, it is
/// forced to be in universe 0.
///
/// The destination type `dest` is for specification only and is not
/// subject to the same universe constraints by the memory model.
val buffer_view (src:Type0) (rrel rel:B.srel src) (dest:Type u#b) : Type u#b
/// `buffer b`: In contrast to `buffer_view`, `buffer b` hides the
/// source type of the view. As such, it is likely more convenient to
/// use in specifications and the rest of this interface is designed
/// around this type.
///
/// However, the type has a higher universe, and
/// this means, for instance, that values of `buffer b` cannot be
/// stored in the heap.
///
/// We leave its definition transparent in case clients wish to
/// manipulate both the `src` and `dest` types explicitly (e.g., to
/// stay in a lower universe)
let buffer (dest:Type u#a) : Type u#(max a 1) = (src:Type0 & rrel:B.srel src & rel:B.srel src & buffer_view src rrel rel dest)
let as_buffer_t (#dest:Type) (b:buffer dest) = B.mbuffer (Mkdtuple4?._1 b) (Mkdtuple4?._2 b) (Mkdtuple4?._3 b)
/// `mk_buffer_view`: The main constructor
val mk_buffer_view (#src:Type0) (#rrel #rel:B.srel src) (#dest:Type)
(b:B.mbuffer src rrel rel)
(v:view src dest{
length b % View?.n v == 0
})
: GTot (buffer dest)
/// `as_buffer`: Projecting the underlying B.buffer from its view
val as_buffer (#b:Type) (v:buffer b) : as_buffer_t v
/// A lemma-relating projector to constructor
val as_buffer_mk_buffer_view (#src:Type0) (#rrel #rel:B.srel src) (#dest:Type)
(b:B.mbuffer src rrel rel)
(v:view src dest{
length b % View?.n v == 0
})
: Lemma (let bv = mk_buffer_view b v in
Mkdtuple4?._1 bv == src /\
Mkdtuple4?._2 bv == rrel /\
Mkdtuple4?._3 bv == rel /\
as_buffer bv == b)
[SMTPat (as_buffer (mk_buffer_view b v))]
/// `get_view`: Projecting the view functions itself
val get_view (#b : Type) (v:buffer b) : view (Mkdtuple4?._1 v) b
/// A lemma-relating projector to constructor
val get_view_mk_buffer_view (#src:Type0) (#rrel #rel:B.srel src) (#dest:Type)
(b:B.mbuffer src rrel rel)
(v:view src dest{
length b % View?.n v == 0
})
: Lemma (let bv = mk_buffer_view b v in
Mkdtuple4?._1 bv == src /\
get_view bv == v)
[SMTPat (get_view (mk_buffer_view b v))]
/// `live h vb`: liveness of a buffer view corresponds to liveness of
/// the underlying buffer
unfold
let live #b h (vb:buffer b) = live h (as_buffer vb)
/// `length vb`: is defined in terms of the underlying buffer
///
/// Internally, it is defined as
///
/// ```
/// length (as_buffer vb) / View?.n (get_view vb)
/// ```
///
/// However, rather than expose this definition (which uses non-linear
/// arithmetic) to callers, we treat length abstractly.
///
/// To reveal its definition explicitly, use the `length_eq` lemma below.
val length (#b: _) (vb:buffer b)
: GTot nat
/// `length_eq`: Reveals the definition of the `length` function
val length_eq (#b: _) (vb:buffer b)
: Lemma (length vb = B.length (as_buffer vb) / View?.n (get_view vb))
/// `view_indexing`: A lemma that requires a bit of non-linear
/// arithmetic, necessary for some of the specs below and convenient
/// when relating the underlying buffer to its view.
val view_indexing (#b: _) (vb:buffer b) (i:nat{i < length vb})
: Lemma (let open FStar.Mul in
let n = View?.n (get_view vb) in
n <= length vb * n - i * n)
/// `sel h vb i` : selects element at index `i` from the buffer `vb` in heap `h`
val sel (#b: _)
(h:HS.mem)
(vb:buffer b)
(i:nat{i < length vb})
: GTot b
/// `upd h vb i x`: stores `x` at index `i` in the buffer `vb` in heap `h`
val upd (#b: _)
(h:HS.mem)
(vb:buffer b{live h vb})
(i:nat{i < length vb})
(x:b)
: GTot HS.mem
/// `sel_upd`: A classic select/update lemma for reasoning about maps
val sel_upd (#b:_)
(vb:buffer b)
(i:nat{i < length vb})
(j:nat{j < length vb})
(x:b)
(h:HS.mem{live h vb})
: Lemma (if i = j
then sel (upd h vb i x) vb j == x
else sel (upd h vb i x) vb j == sel h vb j)
[SMTPat (sel (upd h vb i x) vb j)]
val lemma_upd_with_sel (#b:_)
(vb:buffer b)
(i:nat{i < length vb})
(h:HS.mem{live h vb})
:Lemma (upd h vb i (sel h vb i) == h)
/// `modifies` on views is just defined in terms of the underlying buffer | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Monotonic.Buffer.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Mul.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowStar.BufferView.fsti"
} | [
{
"abbrev": true,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": "B"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": false,
"full_module": "LowStar.Monotonic.Buffer",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowStar",
"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 |
vb: LowStar.BufferView.buffer b ->
h: FStar.Monotonic.HyperStack.mem ->
h': FStar.Monotonic.HyperStack.mem
-> Type0 | Prims.Tot | [
"total"
] | [] | [
"LowStar.BufferView.buffer",
"FStar.Monotonic.HyperStack.mem",
"LowStar.Monotonic.Buffer.modifies",
"LowStar.Monotonic.Buffer.loc_buffer",
"FStar.Pervasives.__proj__Mkdtuple4__item___1",
"LowStar.Monotonic.Buffer.srel",
"LowStar.BufferView.buffer_view",
"FStar.Pervasives.__proj__Mkdtuple4__item___2",
"FStar.Pervasives.__proj__Mkdtuple4__item___3",
"LowStar.BufferView.as_buffer"
] | [] | false | false | false | true | true | let modifies (#b: _) (vb: buffer b) (h h': HS.mem) =
| B.modifies (B.loc_buffer (as_buffer vb)) h h' | false |
|
Target.fst | Target.print_out_expr_set | val print_out_expr_set (tbl: set) (oe: output_expr) : ML string | val print_out_expr_set (tbl: set) (oe: output_expr) : ML string | let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 34,
"end_line": 1158,
"start_col": 0,
"start_line": 1136
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | tbl: Target.set -> oe: Target.output_expr -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.set",
"Target.output_expr",
"Prims.unit",
"Prims.string",
"FStar.Pervasives.Native.option",
"FStar.Printf.sprintf",
"Ast.ident_name",
"Target.print_out_expr'",
"Target.__proj__Mkoutput_expr__item__oe_expr",
"Target.print_as_c_type",
"Target.__proj__Mkoutput_expr__item__oe_t",
"Ast.ident",
"Target.base_id_of_output_expr",
"Target.__proj__Mkoutput_expr__item__oe_bt",
"Hashtable.insert",
"Hashtable.try_find",
"Target.pascal_case",
"Target.out_fn_name"
] | [] | false | true | false | false | false | let print_out_expr_set (tbl: set) (oe: output_expr) : ML string =
| let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf "%s = %s;" (print_out_expr' oe.oe_expr) fn_arg2_name in
let fn =
Printf.sprintf "void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body
in
Printf.sprintf "\n\n%s\n\n" fn | false |
Target.fst | Target.output_setter_name | val output_setter_name (lhs:output_expr) : ML string | val output_setter_name (lhs:output_expr) : ML string | let output_setter_name lhs = Printf.sprintf "set_%s" (out_fn_name lhs) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 70,
"end_line": 1196,
"start_col": 0,
"start_line": 1196
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*)
let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | lhs: Target.output_expr -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.output_expr",
"FStar.Printf.sprintf",
"Prims.string",
"Target.out_fn_name"
] | [] | false | true | false | false | false | let output_setter_name lhs =
| Printf.sprintf "set_%s" (out_fn_name lhs) | false |
Target.fst | Target.print_out_expr_get | val print_out_expr_get (tbl: set) (oe: output_expr) : ML string | val print_out_expr_get (tbl: set) (oe: output_expr) : ML string | let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 34,
"end_line": 1194,
"start_col": 0,
"start_line": 1178
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | tbl: Target.set -> oe: Target.output_expr -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.set",
"Target.output_expr",
"Prims.unit",
"Prims.string",
"FStar.Pervasives.Native.option",
"FStar.Printf.sprintf",
"Ast.ident_name",
"Target.print_out_expr'",
"Target.__proj__Mkoutput_expr__item__oe_expr",
"Target.print_as_c_type",
"Target.__proj__Mkoutput_expr__item__oe_t",
"Ast.ident",
"Target.base_id_of_output_expr",
"Target.__proj__Mkoutput_expr__item__oe_bt",
"Hashtable.insert",
"Hashtable.try_find",
"Target.pascal_case",
"Target.out_fn_name"
] | [] | false | true | false | false | false | let print_out_expr_get (tbl: set) (oe: output_expr) : ML string =
| let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn =
Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body
in
Printf.sprintf "\n\n%s\n\n" fn | false |
Target.fst | Target.output_getter_name | val output_getter_name (lhs:output_expr) : ML string | val output_getter_name (lhs:output_expr) : ML string | let output_getter_name lhs = Printf.sprintf "get_%s" (out_fn_name lhs) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 70,
"end_line": 1197,
"start_col": 0,
"start_line": 1197
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*)
let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | lhs: Target.output_expr -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.output_expr",
"FStar.Printf.sprintf",
"Prims.string",
"Target.out_fn_name"
] | [] | false | true | false | false | false | let output_getter_name lhs =
| Printf.sprintf "get_%s" (out_fn_name lhs) | false |
LowParse.Low.FLData.fst | LowParse.Low.FLData.valid_fldata_strong_gen | val valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz))
))
(ensures
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'))) | val valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
(#rrel #rel: _)
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz))
))
(ensures
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'))) | let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'
)))
= valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | {
"file_name": "src/lowparse/LowParse.Low.FLData.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 38,
"end_line": 162,
"start_col": 0,
"start_line": 134
} | module LowParse.Low.FLData
include LowParse.Low.Combinators
include LowParse.Spec.FLData
module B = LowStar.Buffer
module U32 = FStar.UInt32
module HST = FStar.HyperStack.ST
module HS = FStar.HyperStack
module Cast = FStar.Int.Cast
module U64 = FStar.UInt64
let valid_fldata_gen
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
U32.v pos + sz < 4294967296 /\
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz)
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
let valid_fldata_gen_elim
(#k: parser_kind)
(#t: Type)
(p: parser k t)
(sz: nat)
#rrel #rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires (
valid (parse_fldata p sz) h input pos
))
(ensures (
U32.v pos + sz < 4294967296 /\ (
let pos' = pos `U32.add` U32.uint_to_t sz in
valid_exact p h input pos (pos `U32.add` U32.uint_to_t sz) /\
valid_content_pos (parse_fldata p sz) h input pos (contents_exact p h input pos pos') pos'
)))
= valid_facts (parse_fldata p sz) h input pos;
let pos' = pos `U32.add` U32.uint_to_t sz in
let input' = { base = input.base; len = pos'; } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos'
inline_for_extraction
let validate_fldata_gen
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ = valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos) in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else
if pos' `U64.sub` pos <> Cast.uint32_to_uint64 sz32
then validator_error_generic
else pos'
inline_for_extraction
let validate_fldata_consumes_all
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
(sq: squash (k.parser_kind_subkind == Some ParserConsumesAll))
: Tot (validator (parse_fldata p sz))
= fun #rrel #rel input pos ->
let h = HST.get () in
[@inline_let] let _ =
valid_facts (parse_fldata p sz) h input (uint64_to_uint32 pos);
parse_fldata_consumes_all_correct p sz (bytes_of_slice_from h input (uint64_to_uint32 pos))
in
if (Cast.uint32_to_uint64 input.len `U64.sub` pos) `U64.lt` Cast.uint32_to_uint64 sz32
then validator_error_not_enough_data
else
[@inline_let] let input' = { base = input.base; len = uint64_to_uint32 pos `U32.add` sz32; } in
[@inline_let] let _ = valid_facts p h input' (uint64_to_uint32 pos) in
let pos' = v input' pos in
if is_error pos'
then
if pos' = validator_error_not_enough_data
then validator_error_generic (* the size was fixed ahead of time, so if the parser runs out of data, then that size was wrong in the first place. *)
else pos' // error propagation
else pos'
inline_for_extraction
let validate_fldata
(#k: parser_kind)
(#t: Type)
(#p: parser k t)
(v: validator p)
(sz: nat)
(sz32: U32.t { U32.v sz32 == sz } )
: Tot (validator (parse_fldata p sz))
= if k.parser_kind_subkind = Some ParserConsumesAll
then validate_fldata_consumes_all v sz sz32 ()
else validate_fldata_gen v sz sz32 | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"LowStar.Buffer.fst.checked",
"LowParse.Spec.FLData.fst.checked",
"LowParse.Low.Combinators.fsti.checked",
"FStar.UInt64.fsti.checked",
"FStar.UInt32.fsti.checked",
"FStar.Seq.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.Int.Cast.fst.checked",
"FStar.HyperStack.ST.fsti.checked",
"FStar.HyperStack.fst.checked"
],
"interface_file": false,
"source_file": "LowParse.Low.FLData.fst"
} | [
{
"abbrev": true,
"full_module": "FStar.UInt64",
"short_module": "U64"
},
{
"abbrev": true,
"full_module": "FStar.Int.Cast",
"short_module": "Cast"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack",
"short_module": "HS"
},
{
"abbrev": true,
"full_module": "FStar.HyperStack.ST",
"short_module": "HST"
},
{
"abbrev": true,
"full_module": "FStar.UInt32",
"short_module": "U32"
},
{
"abbrev": true,
"full_module": "LowStar.Buffer",
"short_module": "B"
},
{
"abbrev": false,
"full_module": "LowParse.Spec.FLData",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low.Combinators",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "LowParse.Low",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Pervasives",
"short_module": null
},
{
"abbrev": false,
"full_module": "Prims",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar",
"short_module": null
}
] | {
"detail_errors": false,
"detail_hint_replay": false,
"initial_fuel": 2,
"initial_ifuel": 1,
"max_fuel": 8,
"max_ifuel": 2,
"no_plugins": false,
"no_smt": false,
"no_tactics": false,
"quake_hi": 1,
"quake_keep": false,
"quake_lo": 1,
"retry": false,
"reuse_hint_for": null,
"smtencoding_elim_box": false,
"smtencoding_l_arith_repr": "boxwrap",
"smtencoding_nl_arith_repr": "boxwrap",
"smtencoding_valid_elim": false,
"smtencoding_valid_intro": true,
"tcnorm": true,
"trivial_pre_for_unannotated_effectful_fns": true,
"z3cliopt": [],
"z3refresh": false,
"z3rlimit": 5,
"z3rlimit_factor": 1,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false |
s: LowParse.Spec.Base.serializer p ->
sz: Prims.nat ->
input: LowParse.Slice.slice rrel rel ->
pos: FStar.UInt32.t ->
h: FStar.Monotonic.HyperStack.mem
-> FStar.Pervasives.Lemma
(requires
FStar.UInt32.v pos + sz < 4294967296 /\
LowParse.Low.Base.Spec.valid_exact p
h
input
pos
(FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz)))
(ensures
FStar.UInt32.v pos + sz < 4294967296 /\
LowParse.Low.Base.Spec.valid_exact p
h
input
pos
(FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz)) /\
(let pos' = FStar.UInt32.add pos (FStar.UInt32.uint_to_t sz) in
let x = LowParse.Low.Base.Spec.contents_exact p h input pos pos' in
FStar.Seq.Base.length (LowParse.Spec.Base.serialize s x) == sz /\
LowParse.Low.Base.Spec.valid_content_pos (LowParse.Spec.FLData.parse_fldata_strong s sz)
h
input
pos
x
pos')) | FStar.Pervasives.Lemma | [
"lemma"
] | [] | [
"LowParse.Spec.Base.parser_kind",
"LowParse.Spec.Base.parser",
"LowParse.Spec.Base.serializer",
"Prims.nat",
"LowParse.Slice.srel",
"LowParse.Bytes.byte",
"LowParse.Slice.slice",
"FStar.UInt32.t",
"FStar.Monotonic.HyperStack.mem",
"LowParse.Low.Base.Spec.contents_exact_eq",
"Prims.unit",
"LowParse.Low.Base.Spec.valid_exact_equiv",
"LowParse.Low.Base.Spec.valid_facts",
"LowParse.Slice.Mkslice",
"LowParse.Slice.__proj__Mkslice__item__base",
"FStar.UInt32.add",
"FStar.UInt32.uint_to_t",
"LowParse.Spec.FLData.parse_fldata_kind",
"LowParse.Spec.FLData.parse_fldata_strong_t",
"LowParse.Spec.FLData.parse_fldata_strong",
"Prims.l_and",
"Prims.b2t",
"Prims.op_LessThan",
"Prims.op_Addition",
"FStar.UInt32.v",
"LowParse.Low.Base.Spec.valid_exact",
"Prims.squash",
"Prims.eq2",
"FStar.Seq.Base.length",
"LowParse.Spec.Base.serialize",
"LowParse.Low.Base.Spec.valid_content_pos",
"LowParse.Low.Base.Spec.contents_exact",
"Prims.Nil",
"FStar.Pervasives.pattern"
] | [] | true | false | true | false | false | let valid_fldata_strong_gen
(#k: parser_kind)
(#t: Type0)
(#p: parser k t)
(s: serializer p)
(sz: nat)
#rrel
#rel
(input: slice rrel rel)
(pos: U32.t)
(h: HS.mem)
: Lemma
(requires
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz))
))
(ensures
(U32.v pos + sz < 4294967296 /\ valid_exact p h input pos (pos `U32.add` (U32.uint_to_t sz)) /\
(let pos' = pos `U32.add` (U32.uint_to_t sz) in
let x = contents_exact p h input pos pos' in
Seq.length (serialize s x) == sz /\
valid_content_pos (parse_fldata_strong s sz) h input pos x pos'))) =
| valid_facts (parse_fldata_strong s sz) h input pos;
let pos' = pos `U32.add` (U32.uint_to_t sz) in
let input' = { base = input.base; len = pos' } in
valid_facts p h input' pos;
valid_exact_equiv p h input pos pos';
contents_exact_eq p h input pos pos' | false |
Target.fst | Target.print_out_expr_get_fstar | val print_out_expr_get_fstar (tbl: set) (mname: string) (oe: output_expr) : ML string | val print_out_expr_get_fstar (tbl: set) (mname: string) (oe: output_expr) : ML string | let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 71,
"end_line": 1172,
"start_col": 0,
"start_line": 1164
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | tbl: Target.set -> mname: Prims.string -> oe: Target.output_expr -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Target.set",
"Prims.string",
"Target.output_expr",
"Prims.unit",
"FStar.Pervasives.Native.option",
"FStar.Printf.sprintf",
"Target.print_typ",
"Target.__proj__Mkoutput_expr__item__oe_t",
"Target.__proj__Mkoutput_expr__item__oe_bt",
"Hashtable.insert",
"Hashtable.try_find",
"Target.out_fn_name"
] | [] | false | true | false | false | false | let print_out_expr_get_fstar (tbl: set) (mname: string) (oe: output_expr) : ML string =
| let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res | false |
Target.fst | Target.print_out_typ | val print_out_typ (ot: A.out_typ) : ML string | val print_out_typ (ot: A.out_typ) : ML string | let print_out_typ (ot:A.out_typ) : ML string =
let open A in
Printf.sprintf
"\ntypedef %s %s {\n%s\n} %s;\n"
(if ot.out_typ_is_union then "union" else "struct")
(uppercase (A.ident_name ot.out_typ_names.typedef_name))
(print_output_types_fields ot.out_typ_fields)
(uppercase (A.ident_name ot.out_typ_names.typedef_abbrev)) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 62,
"end_line": 1352,
"start_col": 0,
"start_line": 1345
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*)
let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
let output_setter_name lhs = Printf.sprintf "set_%s" (out_fn_name lhs)
let output_getter_name lhs = Printf.sprintf "get_%s" (out_fn_name lhs)
let output_base_var lhs = base_id_of_output_expr lhs
let print_external_types_fstar_interpreter (modul:string) (ds:decls) : ML string =
let tbl = H.create 10 in
let s = String.concat "" (ds |> List.map (fun d ->
match fst d with
| Output_type ot ->
let t = T_app ot.out_typ_names.typedef_abbrev A.KindOutput [] in
Printf.sprintf "%s%s"
(print_output_type_val tbl t)
(print_output_type_val tbl (T_pointer t))
| Extern_type i ->
Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| _ -> "")) in
Printf.sprintf
"module %s.ExternalTypes\n\n\
open EverParse3d.Prelude\n\
open EverParse3d.Actions.All\n\n%s"
modul
s
let print_external_api_fstar_interpreter (modul:string) (ds:decls) : ML string =
let tbl = H.create 10 in
let s = String.concat "" (ds |> List.map (fun d ->
match fst d with
// | Output_type ot ->
// let t = T_app ot.out_typ_names.typedef_name A.KindOutput [] in
// Printf.sprintf "%s%s"
// (print_output_type_val tbl t)
// (print_output_type_val tbl (T_pointer t))
| Output_type_expr oe is_get ->
Printf.sprintf "%s"
// (print_output_type_val tbl oe.oe_bt)
// (print_output_type_val tbl oe.oe_t)
(if not is_get then print_out_expr_set_fstar tbl modul oe
else print_out_expr_get_fstar tbl modul oe)
| Extern_type i ->
Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| Extern_fn f ret params ->
Printf.sprintf "\n\nval %s %s : extern_action (NonTrivial output_loc)\n"
(print_ident f)
(String.concat " " (params |> List.map (fun (i, t) -> Printf.sprintf "(%s:%s)"
(print_ident i)
(print_typ modul t))))
| Extern_probe f ->
Printf.sprintf "\n\nval %s : EverParse3d.CopyBuffer.probe_fn\n\n" (print_ident f)
| _ -> "")) in
let external_types_include =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "include %s.ExternalTypes\n\n" modul
else "" in
Printf.sprintf
"module %s.ExternalAPI\n\n\
open EverParse3d.Prelude\n\
open EverParse3d.Actions.All\n\
open EverParse3d.Interpreter\n\
%s\n\
noextract val output_loc : eloc\n\n%s"
modul
external_types_include
s
//
// When printing output expressions in C,
// the output types may be coming from some other module
// This function gets all the dependencies from output expressions
// so that they can be added in the M_OutputTypes.c file
//
let get_out_exprs_deps (modul:string) (ds:decls) : ML (list string) =
let maybe_add_dep (deps:list string) (s:option string) : list string =
match s with
| None -> deps
| Some s -> if List.mem s deps then deps else deps@[s] in
List.fold_left (fun deps (d, _) ->
match d with
| Output_type_expr oe _ ->
maybe_add_dep (maybe_add_dep deps (get_output_typ_dep modul oe.oe_bt))
(get_output_typ_dep modul oe.oe_t)
| _ -> deps) [] ds
let print_out_exprs_c modul (ds:decls) : ML string =
let tbl = H.create 10 in
let deps = get_out_exprs_deps modul ds in
let emit_output_types_defs = Options.get_emit_output_types_defs () in
let dep_includes =
if List.length deps = 0 || not emit_output_types_defs
then ""
else
String.concat ""
(List.map (fun s -> FStar.Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" s) deps) in
let self_external_typedef_include =
if has_output_types ds && emit_output_types_defs
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" modul
else "" in
(Printf.sprintf
"%s#include<stdint.h>\n\n\
%s\
%s\
#if defined(__cplusplus)\n\
extern \"C\" {\n\
#endif\n\n"
(Options.make_includes ())
dep_includes
self_external_typedef_include)
^
(String.concat "" (ds |> List.map (fun d ->
match fst d with
| Output_type_expr oe is_get ->
if not is_get then print_out_expr_set tbl oe
else print_out_expr_get tbl oe
| _ -> "")))
^
("#if defined(__cplusplus)\n\
}\n\
#endif\n\n")
let rec atyp_to_ttyp (t:A.typ) : ML typ =
match t.v with
| A.Pointer t ->
let t = atyp_to_ttyp t in
T_pointer t
| A.Type_app hd _b _args ->
T_app hd _b []
let rec print_output_types_fields (flds:list A.out_field) : ML string =
List.fold_left (fun s fld ->
let fld_s =
match fld with
| A.Out_field_named id t bopt ->
Printf.sprintf "%s %s%s;\n"
(print_as_c_type (atyp_to_ttyp t))
(A.ident_name id)
(match bopt with
| None -> ""
| Some n -> ":" ^ (string_of_int n))
| A.Out_field_anon flds is_union ->
Printf.sprintf "%s {\n %s };\n"
(if is_union then "union" else "struct")
(print_output_types_fields flds) in
s ^ fld_s) "" flds | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | ot: Ast.out_typ -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Ast.out_typ",
"Target.uppercase",
"Ast.ident_name",
"Ast.__proj__Mktypedef_names__item__typedef_abbrev",
"Ast.__proj__Mkout_typ__item__out_typ_names",
"Prims.string",
"FStar.Printf.sprintf",
"Ast.__proj__Mkout_typ__item__out_typ_is_union",
"Prims.bool",
"Ast.__proj__Mktypedef_names__item__typedef_name",
"Target.print_output_types_fields",
"Ast.__proj__Mkout_typ__item__out_typ_fields"
] | [] | false | true | false | false | false | let print_out_typ (ot: A.out_typ) : ML string =
| let open A in
Printf.sprintf "\ntypedef %s %s {\n%s\n} %s;\n"
(if ot.out_typ_is_union then "union" else "struct")
(uppercase (A.ident_name ot.out_typ_names.typedef_name))
(print_output_types_fields ot.out_typ_fields)
(uppercase (A.ident_name ot.out_typ_names.typedef_abbrev)) | false |
Target.fst | Target.print_external_types_fstar_interpreter | val print_external_types_fstar_interpreter (modul:string) (ds:decls) : ML string | val print_external_types_fstar_interpreter (modul:string) (ds:decls) : ML string | let print_external_types_fstar_interpreter (modul:string) (ds:decls) : ML string =
let tbl = H.create 10 in
let s = String.concat "" (ds |> List.map (fun d ->
match fst d with
| Output_type ot ->
let t = T_app ot.out_typ_names.typedef_abbrev A.KindOutput [] in
Printf.sprintf "%s%s"
(print_output_type_val tbl t)
(print_output_type_val tbl (T_pointer t))
| Extern_type i ->
Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| _ -> "")) in
Printf.sprintf
"module %s.ExternalTypes\n\n\
open EverParse3d.Prelude\n\
open EverParse3d.Actions.All\n\n%s"
modul
s | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 5,
"end_line": 1217,
"start_col": 0,
"start_line": 1200
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*)
let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
let output_setter_name lhs = Printf.sprintf "set_%s" (out_fn_name lhs)
let output_getter_name lhs = Printf.sprintf "get_%s" (out_fn_name lhs)
let output_base_var lhs = base_id_of_output_expr lhs | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | modul: Prims.string -> ds: Target.decls -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.decls",
"FStar.Printf.sprintf",
"FStar.String.concat",
"Prims.list",
"FStar.List.map",
"FStar.Pervasives.Native.tuple2",
"Target.decl'",
"Target.decl_attributes",
"FStar.Pervasives.Native.fst",
"Ast.out_typ",
"Target.print_output_type_val",
"Target.T_pointer",
"Target.typ",
"Target.T_app",
"Ast.__proj__Mktypedef_names__item__typedef_abbrev",
"Ast.__proj__Mkout_typ__item__out_typ_names",
"Ast.KindOutput",
"Prims.Nil",
"FStar.Pervasives.either",
"Target.expr",
"Ast.ident",
"Target.print_ident",
"Hashtable.t",
"Prims.unit",
"Hashtable.create"
] | [] | false | true | false | false | false | let print_external_types_fstar_interpreter (modul: string) (ds: decls) : ML string =
| let tbl = H.create 10 in
let s =
String.concat ""
(ds |>
List.map (fun d ->
match fst d with
| Output_type ot ->
let t = T_app ot.out_typ_names.typedef_abbrev A.KindOutput [] in
Printf.sprintf "%s%s"
(print_output_type_val tbl t)
(print_output_type_val tbl (T_pointer t))
| Extern_type i -> Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| _ -> ""))
in
Printf.sprintf "module %s.ExternalTypes\n\nopen EverParse3d.Prelude\nopen EverParse3d.Actions.All\n\n%s"
modul
s | false |
Target.fst | Target.is_output_type | val is_output_type (t: typ) : bool | val is_output_type (t: typ) : bool | let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 14,
"end_line": 370,
"start_col": 0,
"start_line": 366
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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: Target.typ -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Target.typ",
"Ast.ident",
"Target.is_output_type",
"Prims.bool"
] | [
"recursion"
] | false | false | false | true | false | let rec is_output_type (t: typ) : bool =
| match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false | false |
Target.fst | Target.output_base_var | val output_base_var (lhs:output_expr) : ML A.ident | val output_base_var (lhs:output_expr) : ML A.ident | let output_base_var lhs = base_id_of_output_expr lhs | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 52,
"end_line": 1198,
"start_col": 0,
"start_line": 1198
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*)
let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
let output_setter_name lhs = Printf.sprintf "set_%s" (out_fn_name lhs) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | lhs: Target.output_expr -> FStar.All.ML Ast.ident | FStar.All.ML | [
"ml"
] | [] | [
"Target.output_expr",
"Target.base_id_of_output_expr",
"Ast.ident"
] | [] | false | true | false | false | false | let output_base_var lhs =
| base_id_of_output_expr lhs | false |
Target.fst | Target.is_type_abbreviation | val is_type_abbreviation (td: type_decl) : bool | val is_type_abbreviation (td: type_decl) : bool | let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 24,
"end_line": 683,
"start_col": 0,
"start_line": 680
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | td: Target.type_decl -> Prims.bool | Prims.Tot | [
"total"
] | [] | [
"Target.type_decl",
"Target.__proj__Mktype_decl__item__decl_typ",
"Target.typ",
"Prims.list",
"Target.field",
"Prims.bool"
] | [] | false | false | false | true | false | let is_type_abbreviation (td: type_decl) : bool =
| match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false | false |
Target.fst | Target.print_output_type | val print_output_type (qual: bool) (t: typ) : ML string | val print_output_type (qual: bool) (t: typ) : ML string | let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 8,
"end_line": 399,
"start_col": 0,
"start_line": 383
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | qual: Prims.bool -> t: Target.typ -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.bool",
"Target.typ",
"FStar.Pervasives.Native.option",
"Prims.string",
"FStar.Printf.sprintf",
"FStar.Pervasives.Native.tuple2",
"Ast.ident",
"Ast.t_kind",
"Prims.list",
"FStar.Pervasives.either",
"Target.expr",
"FStar.Pervasives.Native.Mktuple2",
"Ast.__proj__Mkident'__item__modul_name",
"Ast.__proj__Mkwith_meta_t__item__v",
"Ast.ident'",
"Target.print_ident",
"FStar.All.failwith"
] | [] | false | true | false | false | false | let print_output_type (qual: bool) (t: typ) : ML string =
| let rec aux (t: typ) : ML (option string & string) =
match t with
| T_app id _ _ -> id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then
match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i | false |
Target.fst | Target.print_external_api_fstar_interpreter | val print_external_api_fstar_interpreter (modul:string) (ds:decls) : ML string | val print_external_api_fstar_interpreter (modul:string) (ds:decls) : ML string | let print_external_api_fstar_interpreter (modul:string) (ds:decls) : ML string =
let tbl = H.create 10 in
let s = String.concat "" (ds |> List.map (fun d ->
match fst d with
// | Output_type ot ->
// let t = T_app ot.out_typ_names.typedef_name A.KindOutput [] in
// Printf.sprintf "%s%s"
// (print_output_type_val tbl t)
// (print_output_type_val tbl (T_pointer t))
| Output_type_expr oe is_get ->
Printf.sprintf "%s"
// (print_output_type_val tbl oe.oe_bt)
// (print_output_type_val tbl oe.oe_t)
(if not is_get then print_out_expr_set_fstar tbl modul oe
else print_out_expr_get_fstar tbl modul oe)
| Extern_type i ->
Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| Extern_fn f ret params ->
Printf.sprintf "\n\nval %s %s : extern_action (NonTrivial output_loc)\n"
(print_ident f)
(String.concat " " (params |> List.map (fun (i, t) -> Printf.sprintf "(%s:%s)"
(print_ident i)
(print_typ modul t))))
| Extern_probe f ->
Printf.sprintf "\n\nval %s : EverParse3d.CopyBuffer.probe_fn\n\n" (print_ident f)
| _ -> "")) in
let external_types_include =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "include %s.ExternalTypes\n\n" modul
else "" in
Printf.sprintf
"module %s.ExternalAPI\n\n\
open EverParse3d.Prelude\n\
open EverParse3d.Actions.All\n\
open EverParse3d.Interpreter\n\
%s\n\
noextract val output_loc : eloc\n\n%s"
modul
external_types_include
s | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 5,
"end_line": 1260,
"start_col": 0,
"start_line": 1219
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*)
let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
let output_setter_name lhs = Printf.sprintf "set_%s" (out_fn_name lhs)
let output_getter_name lhs = Printf.sprintf "get_%s" (out_fn_name lhs)
let output_base_var lhs = base_id_of_output_expr lhs
let print_external_types_fstar_interpreter (modul:string) (ds:decls) : ML string =
let tbl = H.create 10 in
let s = String.concat "" (ds |> List.map (fun d ->
match fst d with
| Output_type ot ->
let t = T_app ot.out_typ_names.typedef_abbrev A.KindOutput [] in
Printf.sprintf "%s%s"
(print_output_type_val tbl t)
(print_output_type_val tbl (T_pointer t))
| Extern_type i ->
Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| _ -> "")) in
Printf.sprintf
"module %s.ExternalTypes\n\n\
open EverParse3d.Prelude\n\
open EverParse3d.Actions.All\n\n%s"
modul
s | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | modul: Prims.string -> ds: Target.decls -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.decls",
"FStar.Printf.sprintf",
"Prims.op_BarBar",
"Target.has_output_types",
"Target.has_extern_types",
"Prims.bool",
"FStar.String.concat",
"Prims.list",
"FStar.List.map",
"FStar.Pervasives.Native.tuple2",
"Target.decl'",
"Target.decl_attributes",
"FStar.Pervasives.Native.fst",
"Target.output_expr",
"Prims.op_Negation",
"Target.print_out_expr_set_fstar",
"Target.print_out_expr_get_fstar",
"Ast.ident",
"Target.print_ident",
"Target.typ",
"Target.param",
"Target.print_typ",
"Hashtable.t",
"Prims.unit",
"Hashtable.create"
] | [] | false | true | false | false | false | let print_external_api_fstar_interpreter (modul: string) (ds: decls) : ML string =
| let tbl = H.create 10 in
let s =
String.concat ""
(ds |>
List.map (fun d ->
match fst d with
| Output_type_expr oe is_get ->
Printf.sprintf "%s"
(if not is_get
then print_out_expr_set_fstar tbl modul oe
else print_out_expr_get_fstar tbl modul oe)
| Extern_type i -> Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| Extern_fn f ret params ->
Printf.sprintf "\n\nval %s %s : extern_action (NonTrivial output_loc)\n"
(print_ident f)
(String.concat " "
(params |>
List.map (fun (i, t) ->
Printf.sprintf "(%s:%s)" (print_ident i) (print_typ modul t))))
| Extern_probe f ->
Printf.sprintf "\n\nval %s : EverParse3d.CopyBuffer.probe_fn\n\n" (print_ident f)
| _ -> ""))
in
let external_types_include =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "include %s.ExternalTypes\n\n" modul
else ""
in
Printf.sprintf "module %s.ExternalAPI\n\nopen EverParse3d.Prelude\nopen EverParse3d.Actions.All\nopen EverParse3d.Interpreter\n%s\nnoextract val output_loc : eloc\n\n%s"
modul
external_types_include
s | false |
Steel.GhostMonotonicHigherReference.fst | Steel.GhostMonotonicHigherReference.pts_to' | val pts_to' : r: Steel.GhostMonotonicHigherReference.ref a p -> f: Steel.FractionalPermission.perm -> v: a
-> Steel.Effect.Common.vprop | let pts_to' (#a:Type) (#p:Preorder.preorder a) (r:ref a p) (f:perm) (v: a) =
h_exists (pts_to_body r f v) | {
"file_name": "lib/steel/Steel.GhostMonotonicHigherReference.fst",
"git_rev": "f984200f79bdc452374ae994a5ca837496476c41",
"git_url": "https://github.com/FStarLang/steel.git",
"project_name": "steel"
} | {
"end_col": 32,
"end_line": 45,
"start_col": 0,
"start_line": 44
} | (*
Copyright 2020 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 Steel.GhostMonotonicHigherReference
open FStar.Ghost
open FStar.PCM
open Steel.Memory
open Steel.Effect.Atomic
open Steel.Effect
open Steel.GhostPCMReference
open Steel.FractionalPermission
open Steel.Preorder
module Preorder = FStar.Preorder
module Q = Steel.Preorder
module M = Steel.Memory
module PR = Steel.GhostPCMReference
module A = Steel.Effect.Atomic
open FStar.Real
#set-options "--ide_id_info_off"
let ref a p = PR.ref (history a p) pcm_history
[@@__reduce__]
let pts_to_body #a #p (r:ref a p) (f:perm) (v:a) (h:history a p) =
PR.pts_to r h `star`
pure (history_val h v f) | {
"checked_file": "/",
"dependencies": [
"Steel.Preorder.fst.checked",
"Steel.Memory.fsti.checked",
"Steel.GhostPCMReference.fsti.checked",
"Steel.FractionalPermission.fst.checked",
"Steel.Effect.Atomic.fsti.checked",
"Steel.Effect.fsti.checked",
"prims.fst.checked",
"FStar.Real.fsti.checked",
"FStar.Preorder.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.PCM.fst.checked",
"FStar.Ghost.fsti.checked"
],
"interface_file": true,
"source_file": "Steel.GhostMonotonicHigherReference.fst"
} | [
{
"abbrev": false,
"full_module": "FStar.Real",
"short_module": null
},
{
"abbrev": true,
"full_module": "Steel.Effect.Atomic",
"short_module": "A"
},
{
"abbrev": true,
"full_module": "Steel.GhostPCMReference",
"short_module": "PR"
},
{
"abbrev": true,
"full_module": "Steel.Memory",
"short_module": "M"
},
{
"abbrev": true,
"full_module": "Steel.Preorder",
"short_module": "Q"
},
{
"abbrev": true,
"full_module": "FStar.Preorder",
"short_module": "Preorder"
},
{
"abbrev": false,
"full_module": "Steel.Preorder",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.FractionalPermission",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.GhostPCMReference",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect.Atomic",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Memory",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.PCM",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Ghost",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.Preorder",
"short_module": "Preorder"
},
{
"abbrev": false,
"full_module": "Steel.Effect",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect.Atomic",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Memory",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.FractionalPermission",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Ghost",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.PCM",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"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 | r: Steel.GhostMonotonicHigherReference.ref a p -> f: Steel.FractionalPermission.perm -> v: a
-> Steel.Effect.Common.vprop | Prims.Tot | [
"total"
] | [] | [
"FStar.Preorder.preorder",
"Steel.GhostMonotonicHigherReference.ref",
"Steel.FractionalPermission.perm",
"Steel.Effect.Atomic.h_exists",
"Steel.Preorder.history",
"Steel.GhostMonotonicHigherReference.pts_to_body",
"Steel.Effect.Common.vprop"
] | [] | false | false | false | false | false | let pts_to' (#a: Type) (#p: Preorder.preorder a) (r: ref a p) (f: perm) (v: a) =
| h_exists (pts_to_body r f v) | false |
|
Steel.GhostMonotonicHigherReference.fst | Steel.GhostMonotonicHigherReference.pts_to_body | val pts_to_body : r: Steel.GhostMonotonicHigherReference.ref a p ->
f: Steel.FractionalPermission.perm ->
v: a ->
h: Steel.Preorder.history a p
-> Steel.Effect.Common.vprop | let pts_to_body #a #p (r:ref a p) (f:perm) (v:a) (h:history a p) =
PR.pts_to r h `star`
pure (history_val h v f) | {
"file_name": "lib/steel/Steel.GhostMonotonicHigherReference.fst",
"git_rev": "f984200f79bdc452374ae994a5ca837496476c41",
"git_url": "https://github.com/FStarLang/steel.git",
"project_name": "steel"
} | {
"end_col": 30,
"end_line": 42,
"start_col": 0,
"start_line": 40
} | (*
Copyright 2020 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 Steel.GhostMonotonicHigherReference
open FStar.Ghost
open FStar.PCM
open Steel.Memory
open Steel.Effect.Atomic
open Steel.Effect
open Steel.GhostPCMReference
open Steel.FractionalPermission
open Steel.Preorder
module Preorder = FStar.Preorder
module Q = Steel.Preorder
module M = Steel.Memory
module PR = Steel.GhostPCMReference
module A = Steel.Effect.Atomic
open FStar.Real
#set-options "--ide_id_info_off"
let ref a p = PR.ref (history a p) pcm_history | {
"checked_file": "/",
"dependencies": [
"Steel.Preorder.fst.checked",
"Steel.Memory.fsti.checked",
"Steel.GhostPCMReference.fsti.checked",
"Steel.FractionalPermission.fst.checked",
"Steel.Effect.Atomic.fsti.checked",
"Steel.Effect.fsti.checked",
"prims.fst.checked",
"FStar.Real.fsti.checked",
"FStar.Preorder.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.PCM.fst.checked",
"FStar.Ghost.fsti.checked"
],
"interface_file": true,
"source_file": "Steel.GhostMonotonicHigherReference.fst"
} | [
{
"abbrev": false,
"full_module": "FStar.Real",
"short_module": null
},
{
"abbrev": true,
"full_module": "Steel.Effect.Atomic",
"short_module": "A"
},
{
"abbrev": true,
"full_module": "Steel.GhostPCMReference",
"short_module": "PR"
},
{
"abbrev": true,
"full_module": "Steel.Memory",
"short_module": "M"
},
{
"abbrev": true,
"full_module": "Steel.Preorder",
"short_module": "Q"
},
{
"abbrev": true,
"full_module": "FStar.Preorder",
"short_module": "Preorder"
},
{
"abbrev": false,
"full_module": "Steel.Preorder",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.FractionalPermission",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.GhostPCMReference",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect.Atomic",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Memory",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.PCM",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Ghost",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.Preorder",
"short_module": "Preorder"
},
{
"abbrev": false,
"full_module": "Steel.Effect",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect.Atomic",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Memory",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.FractionalPermission",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Ghost",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.PCM",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"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 |
r: Steel.GhostMonotonicHigherReference.ref a p ->
f: Steel.FractionalPermission.perm ->
v: a ->
h: Steel.Preorder.history a p
-> Steel.Effect.Common.vprop | Prims.Tot | [
"total"
] | [] | [
"FStar.Preorder.preorder",
"Steel.GhostMonotonicHigherReference.ref",
"Steel.FractionalPermission.perm",
"Steel.Preorder.history",
"Steel.Effect.Common.star",
"Steel.GhostPCMReference.pts_to",
"Steel.Preorder.pcm_history",
"Steel.Effect.Common.pure",
"Steel.Preorder.history_val",
"FStar.Ghost.hide",
"Steel.Effect.Common.vprop"
] | [] | false | false | false | false | false | let pts_to_body #a #p (r: ref a p) (f: perm) (v: a) (h: history a p) =
| (PR.pts_to r h) `star` (pure (history_val h v f)) | false |
|
Target.fst | Target.print_definition | val print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string | val print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string | let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 29,
"end_line": 638,
"start_col": 0,
"start_line": 613
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else "" | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> d: Target.decl{Definition? (FStar.Pervasives.Native.fst d)}
-> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.decl",
"Prims.b2t",
"Target.uu___is_Definition",
"FStar.Pervasives.Native.fst",
"Target.decl'",
"Target.decl_attributes",
"Ast.ident",
"FStar.Pervasives.Native.option",
"Ast.range",
"Ast.comments",
"Ast.t_kind",
"Prims.list",
"FStar.Pervasives.either",
"Target.typ",
"Target.expr",
"Ast.constant",
"Ast.print_constant",
"FStar.Printf.sprintf",
"Target.print_comments",
"Target.__proj__Mkdecl_attributes__item__comments",
"FStar.Pervasives.Native.snd",
"Target.print_field_id_name",
"Target.print_ident",
"Target.print_typ",
"Target.param",
"Target.print_attributes",
"Target.print_typedef_name",
"Target.print_expr",
"Target.typedef_name",
"Target.Mktypedef_name"
] | [] | false | true | false | false | false | let print_definition (mname: string) (d: decl{Definition? (fst d)}) : ML string =
| match fst d with
| Definition (x, [], T_app { Ast.v = { Ast.name = "field_id" } } _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = { td_name = x; td_params = params; td_entrypoint = false } in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr) | false |
Target.fst | Target.print_typ | val print_typ (mname:string) (t:typ) : ML string | val print_typ (mname:string) (t:typ) : ML string | let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 59,
"end_line": 435,
"start_col": 0,
"start_line": 401
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> t: Target.typ -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [
"print_typ",
"print_indexes"
] | [
"Prims.string",
"Target.typ",
"Target.is_output_type",
"Target.print_output_type",
"Prims.bool",
"Ast.ident",
"Ast.t_kind",
"Prims.list",
"FStar.Pervasives.either",
"Target.expr",
"FStar.Printf.sprintf",
"Target.print_maybe_qualified_ident",
"FStar.String.concat",
"Target.print_indexes",
"Target.print_ident",
"Target.print_typ",
"Target.lam",
"Target.print_expr_lam",
"Target.print_expr",
"Target.action",
"Ast.comments"
] | [
"mutual recursion"
] | false | true | false | false | false | let rec print_typ (mname: string) (t: typ) : ML string =
| if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args ->
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)" (print_ident x) (print_typ mname t1) (print_typ mname t2)
| T_refine t e -> Printf.sprintf "(refine %s %s)" (print_typ mname t) (print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _ | T_with_dep_action t _ | T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t) | false |
Steel.GhostMonotonicHigherReference.fst | Steel.GhostMonotonicHigherReference.ref | val ref (a:Type u#1) (p:Preorder.preorder a)
: Type u#0 | val ref (a:Type u#1) (p:Preorder.preorder a)
: Type u#0 | let ref a p = PR.ref (history a p) pcm_history | {
"file_name": "lib/steel/Steel.GhostMonotonicHigherReference.fst",
"git_rev": "f984200f79bdc452374ae994a5ca837496476c41",
"git_url": "https://github.com/FStarLang/steel.git",
"project_name": "steel"
} | {
"end_col": 46,
"end_line": 37,
"start_col": 0,
"start_line": 37
} | (*
Copyright 2020 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 Steel.GhostMonotonicHigherReference
open FStar.Ghost
open FStar.PCM
open Steel.Memory
open Steel.Effect.Atomic
open Steel.Effect
open Steel.GhostPCMReference
open Steel.FractionalPermission
open Steel.Preorder
module Preorder = FStar.Preorder
module Q = Steel.Preorder
module M = Steel.Memory
module PR = Steel.GhostPCMReference
module A = Steel.Effect.Atomic
open FStar.Real
#set-options "--ide_id_info_off" | {
"checked_file": "/",
"dependencies": [
"Steel.Preorder.fst.checked",
"Steel.Memory.fsti.checked",
"Steel.GhostPCMReference.fsti.checked",
"Steel.FractionalPermission.fst.checked",
"Steel.Effect.Atomic.fsti.checked",
"Steel.Effect.fsti.checked",
"prims.fst.checked",
"FStar.Real.fsti.checked",
"FStar.Preorder.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.PCM.fst.checked",
"FStar.Ghost.fsti.checked"
],
"interface_file": true,
"source_file": "Steel.GhostMonotonicHigherReference.fst"
} | [
{
"abbrev": false,
"full_module": "FStar.Real",
"short_module": null
},
{
"abbrev": true,
"full_module": "Steel.Effect.Atomic",
"short_module": "A"
},
{
"abbrev": true,
"full_module": "Steel.GhostPCMReference",
"short_module": "PR"
},
{
"abbrev": true,
"full_module": "Steel.Memory",
"short_module": "M"
},
{
"abbrev": true,
"full_module": "Steel.Preorder",
"short_module": "Q"
},
{
"abbrev": false,
"full_module": "Steel.Preorder",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.GhostPCMReference",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.Preorder",
"short_module": "Preorder"
},
{
"abbrev": false,
"full_module": "Steel.Effect",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect.Atomic",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Memory",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.FractionalPermission",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Ghost",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.PCM",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"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 -> p: FStar.Preorder.preorder a -> Type0 | Prims.Tot | [
"total"
] | [] | [
"FStar.Preorder.preorder",
"Steel.GhostPCMReference.ref",
"Steel.Preorder.history",
"Steel.Preorder.pcm_history"
] | [] | false | false | false | true | true | let ref a p =
| PR.ref (history a p) pcm_history | false |
Target.fst | Target.print_typedef_body | val print_typedef_body (mname: string) (b: typedef_body) : ML string | val print_typedef_body (mname: string) (b: typedef_body) : ML string | let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 36,
"end_line": 542,
"start_col": 0,
"start_line": 531
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params)) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> b: Target.typedef_body -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.typedef_body",
"Target.typ",
"Target.print_typ",
"Prims.list",
"Target.field",
"FStar.Printf.sprintf",
"FStar.String.concat",
"FStar.List.map",
"Target.__proj__Mkstruct_field__item__sf_dependence",
"Prims.bool",
"Target.print_ident",
"Target.__proj__Mkstruct_field__item__sf_ident",
"Target.__proj__Mkstruct_field__item__sf_typ"
] | [] | false | true | false | false | false | let print_typedef_body (mname: string) (b: typedef_body) : ML string =
| match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf: field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields | false |
Steel.GhostMonotonicHigherReference.fst | Steel.GhostMonotonicHigherReference.pts_to_sl | val pts_to_sl (#a:Type) (#p:Preorder.preorder a) (r:ref a p) (f:perm) (v:a)
: slprop u#1 | val pts_to_sl (#a:Type) (#p:Preorder.preorder a) (r:ref a p) (f:perm) (v:a)
: slprop u#1 | let pts_to_sl r f v = hp_of (pts_to' r f v) | {
"file_name": "lib/steel/Steel.GhostMonotonicHigherReference.fst",
"git_rev": "f984200f79bdc452374ae994a5ca837496476c41",
"git_url": "https://github.com/FStarLang/steel.git",
"project_name": "steel"
} | {
"end_col": 43,
"end_line": 47,
"start_col": 0,
"start_line": 47
} | (*
Copyright 2020 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 Steel.GhostMonotonicHigherReference
open FStar.Ghost
open FStar.PCM
open Steel.Memory
open Steel.Effect.Atomic
open Steel.Effect
open Steel.GhostPCMReference
open Steel.FractionalPermission
open Steel.Preorder
module Preorder = FStar.Preorder
module Q = Steel.Preorder
module M = Steel.Memory
module PR = Steel.GhostPCMReference
module A = Steel.Effect.Atomic
open FStar.Real
#set-options "--ide_id_info_off"
let ref a p = PR.ref (history a p) pcm_history
[@@__reduce__]
let pts_to_body #a #p (r:ref a p) (f:perm) (v:a) (h:history a p) =
PR.pts_to r h `star`
pure (history_val h v f)
let pts_to' (#a:Type) (#p:Preorder.preorder a) (r:ref a p) (f:perm) (v: a) =
h_exists (pts_to_body r f v) | {
"checked_file": "/",
"dependencies": [
"Steel.Preorder.fst.checked",
"Steel.Memory.fsti.checked",
"Steel.GhostPCMReference.fsti.checked",
"Steel.FractionalPermission.fst.checked",
"Steel.Effect.Atomic.fsti.checked",
"Steel.Effect.fsti.checked",
"prims.fst.checked",
"FStar.Real.fsti.checked",
"FStar.Preorder.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.PCM.fst.checked",
"FStar.Ghost.fsti.checked"
],
"interface_file": true,
"source_file": "Steel.GhostMonotonicHigherReference.fst"
} | [
{
"abbrev": false,
"full_module": "FStar.Real",
"short_module": null
},
{
"abbrev": true,
"full_module": "Steel.Effect.Atomic",
"short_module": "A"
},
{
"abbrev": true,
"full_module": "Steel.GhostPCMReference",
"short_module": "PR"
},
{
"abbrev": true,
"full_module": "Steel.Memory",
"short_module": "M"
},
{
"abbrev": true,
"full_module": "Steel.Preorder",
"short_module": "Q"
},
{
"abbrev": false,
"full_module": "Steel.Preorder",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.GhostPCMReference",
"short_module": null
},
{
"abbrev": true,
"full_module": "FStar.Preorder",
"short_module": "Preorder"
},
{
"abbrev": false,
"full_module": "Steel.Effect",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Effect.Atomic",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.Memory",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel.FractionalPermission",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.Ghost",
"short_module": null
},
{
"abbrev": false,
"full_module": "FStar.PCM",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"short_module": null
},
{
"abbrev": false,
"full_module": "Steel",
"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 | r: Steel.GhostMonotonicHigherReference.ref a p -> f: Steel.FractionalPermission.perm -> v: a
-> Steel.Memory.slprop | Prims.Tot | [
"total"
] | [] | [
"FStar.Preorder.preorder",
"Steel.GhostMonotonicHigherReference.ref",
"Steel.FractionalPermission.perm",
"Steel.Effect.Common.hp_of",
"Steel.GhostMonotonicHigherReference.pts_to'",
"Steel.Memory.slprop"
] | [] | false | false | false | false | false | let pts_to_sl r f v =
| hp_of (pts_to' r f v) | false |
Target.fst | Target.print_output_types_defs | val print_output_types_defs (modul:string) (ds:decls) : ML string | val print_output_types_defs (modul:string) (ds:decls) : ML string | let print_output_types_defs (modul:string) (ds:decls) : ML string =
let defs =
String.concat "\n\n" (List.map (fun (d, _) ->
match d with
| Output_type ot -> print_out_typ ot
| _ -> "") ds) in
Printf.sprintf
"#ifndef __%s_OutputTypesDefs_H\n\
#define __%s_OutputTypesDefs_H\n\n\
#if defined(__cplusplus)\n\
extern \"C\" {\n\
#endif\n\n\n\
%s%s\n\n\n\
#if defined(__cplusplus)\n\
}\n\
#endif\n\n\
#define __%s_OutputTypes_H_DEFINED\n\
#endif\n"
modul
modul
(Options.make_includes ())
defs
modul | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 9,
"end_line": 1378,
"start_col": 0,
"start_line": 1354
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr)
let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t)
let print_decl_for_types (mname:string) (d:decl) : ML string =
match fst d with
| Assumption _ -> ""
| Definition _ ->
print_definition mname d
| Type_decl td ->
Printf.sprintf "noextract\ninline_for_extraction\ntype %s = %s\n\n"
(print_typedef_name mname td.decl_name)
(print_typedef_body mname td.decl_typ)
`strcat`
maybe_print_type_equality mname td
| Output_type _
| Output_type_expr _ _
| Extern_type _
| Extern_fn _ _ _
| Extern_probe _ -> ""
/// Print a decl for M.fst
///
/// No need to print Definition(s), they are `include`d from M.Types.fst
///
/// For a Type_decl, if it is an entry point, we need to emit a definition since
/// there is a corresponding declaration in the .fsti
/// We make the definition as simply the definition in M.Types.fst
let is_type_abbreviation (td:type_decl) : bool =
match td.decl_typ with
| TD_abbrev _ -> true
| TD_struct _ -> false
let external_api_include (modul:string) (ds:list decl) : string =
if has_external_api ds
then Printf.sprintf "open %s.ExternalAPI\n\n" modul
else ""
#push-options "--z3rlimit_factor 4"
let pascal_case name : ML string =
let chars = String.list_of_string name in
let has_underscore = List.mem '_' chars in
let keep, up, low = 0, 1, 2 in
if has_underscore then
let what_next : ref int = alloc up in
let rewrite_char c : ML (list FStar.Char.char) =
match c with
| '_' ->
what_next := up;
[]
| c ->
let c_next =
let n = !what_next in
if n = keep then c
else if n = up then FStar.Char.uppercase c
else FStar.Char.lowercase c
in
let _ =
if Char.uppercase c = c
then what_next := low
else if Char.lowercase c = c
then what_next := keep
in
[c_next]
in
let chars = List.collect rewrite_char (String.list_of_string name) in
String.string_of_list chars
else if String.length name = 0
then name
else String.uppercase (String.sub name 0 1) ^ String.sub name 1 (String.length name - 1)
let uppercase (name:string) : string = String.uppercase name
let rec print_as_c_type (t:typ) : ML string =
let open Ast in
match t with
| T_pointer t ->
Printf.sprintf "%s*" (print_as_c_type t)
| T_app {v={name="Bool"}} _ [] ->
"BOOLEAN"
| T_app {v={name="UINT8"}} _ [] ->
"uint8_t"
| T_app {v={name="UINT16"}} _ [] ->
"uint16_t"
| T_app {v={name="UINT32"}} _ [] ->
"uint32_t"
| T_app {v={name="UINT64"}} _ [] ->
"uint64_t"
| T_app {v={name="PUINT8"}} _ [] ->
"uint8_t*"
| T_app {v={name=x}} KindSpec [] ->
x
| T_app {v={name=x}} _ [] ->
uppercase x
| _ ->
"__UNKNOWN__"
let error_code_macros =
//To be kept consistent with EverParse3d.ErrorCode.error_reason_of_result
"#define EVERPARSE_ERROR_GENERIC 1uL\n\
#define EVERPARSE_ERROR_NOT_ENOUGH_DATA 2uL\n\
#define EVERPARSE_ERROR_IMPOSSIBLE 3uL\n\
#define EVERPARSE_ERROR_LIST_SIZE_NOT_MULTIPLE 4uL\n\
#define EVERPARSE_ERROR_ACTION_FAILED 5uL\n\
#define EVERPARSE_ERROR_CONSTRAINT_FAILED 6uL\n\
#define EVERPARSE_ERROR_UNEXPECTED_PADDING 7uL\n"
let rec get_output_typ_dep (modul:string) (t:typ) : ML (option string) =
match t with
| T_app {v={modul_name=None}} _ _ -> None
| T_app {v={modul_name=Some m}} _ _ ->
if m = modul then None
else Some m
| T_pointer t -> get_output_typ_dep modul t
| _ -> failwith "get_typ_deps: unexpected output type"
let wrapper_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_check_%s"
modul
fn
|> pascal_case
let validator_name
(modul: string)
(fn: string)
: ML string
= Printf.sprintf "%s_validate_%s"
modul
fn
|> pascal_case
let print_c_entry
(produce_everparse_error: opt_produce_everparse_error)
(modul: string)
(env: global_env)
(ds:list decl)
: ML (string & string)
= let default_error_handler =
"static\n\
void DefaultErrorHandler(\n\t\
const char *typename_s,\n\t\
const char *fieldname,\n\t\
const char *reason,\n\t\
uint64_t error_code,\n\t\
uint8_t *context,\n\t\
EVERPARSE_INPUT_BUFFER input,\n\t\
uint64_t start_pos)\n\
{\n\t\
EVERPARSE_ERROR_FRAME *frame = (EVERPARSE_ERROR_FRAME*)context;\n\t\
EverParseDefaultErrorHandler(\n\t\t\
typename_s,\n\t\t\
fieldname,\n\t\t\
reason,\n\t\t\
error_code,\n\t\t\
frame,\n\t\t\
input,\n\t\t\
start_pos\n\t\
);\n\
}"
in
let input_stream_binding = Options.get_input_stream_binding () in
let is_input_stream_buffer = HashingOptions.InputStreamBuffer? input_stream_binding in
let wrapped_call_buffer name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame;\n\t\
frame.filled = FALSE;\n\t\
%s\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, base, len, 0);\n\t\
if (EverParseIsError(result))\n\t\
{\n\t\t\
if (frame.filled)\n\t\t\
{\n\t\t\t\
%sEverParseError(frame.typename_s, frame.fieldname, frame.reason);\n\t\t\
}\n\t\t\
return FALSE;\n\t\
}\n\t\
return TRUE;"
(if is_input_stream_buffer then ""
else "EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t")
name
params
modul
in
let wrapped_call_stream name params =
Printf.sprintf
"EVERPARSE_ERROR_FRAME frame =\n\t\
{ .filled = FALSE,\n\t\
.typename_s = \"UNKNOWN\",\n\t\
.fieldname = \"UNKNOWN\",\n\t\
.reason = \"UNKNOWN\",\n\t\
.error_code = 0uL\n\
};\n\
EVERPARSE_INPUT_BUFFER input = EverParseMakeInputBuffer(base);\n\t\
uint64_t result = %s(%s (uint8_t*)&frame, &DefaultErrorHandler, input, 0);\n\t\
uint64_t parsedSize = EverParseGetValidatorErrorPos(result);\n\
if (EverParseIsError(result))\n\t\
{\n\t\t\
EverParseHandleError(_extra, parsedSize, frame.typename_s, frame.fieldname, frame.reason, frame.error_code);\n\t\t\
}\n\t\
EverParseRetreat(_extra, base, parsedSize);\n\
return parsedSize;"
name
params
in
let mk_param (name: string) (typ: string) : Tot param =
(A.with_range (A.to_ident' name) A.dummy_range, T_app (A.with_range (A.to_ident' typ) A.dummy_range) A.KindSpec [])
in
let print_one_validator (d:type_decl) : ML (string & string) =
let params =
d.decl_name.td_params @
(if is_input_stream_buffer then [] else [mk_param "_extra" "EVERPARSE_EXTRA_T"])
in
let print_params (ps:list param) : ML string =
let params =
String.concat
", "
(List.map
(fun (id, t) -> Printf.sprintf "%s %s" (print_as_c_type t) (print_ident id))
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let print_arguments (ps:list param) : Tot string =
let params =
String.concat
", "
(List.Tot.map
(fun (id, t) ->
if is_output_type t //output type pointers are uint8_t* in the F* generated code
then (print_ident id)
else print_ident id)
ps)
in
match ps with
| [] -> params
| _ -> params ^ ", "
in
let wrapper_name = wrapper_name modul d.decl_name.td_name.A.v.A.name in
let signature =
if is_input_stream_buffer
then Printf.sprintf
"BOOLEAN %s(%suint8_t *base, uint32_t len)"
wrapper_name
(print_params params)
else Printf.sprintf
"uint64_t %s(%sEVERPARSE_INPUT_STREAM_BASE base)"
wrapper_name
(print_params params)
in
let validator_name = validator_name modul d.decl_name.td_name.A.v.A.name in
let impl =
let body =
if is_input_stream_buffer
then wrapped_call_buffer validator_name (print_arguments params)
else wrapped_call_stream validator_name (print_arguments params)
in
Printf.sprintf "%s {\n\t%s\n}"
signature body
in
signature ^";",
impl
in
let signatures_output_typ_deps =
List.fold_left (fun deps (d, _) ->
match d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then let params = d.decl_name.td_params in
List.fold_left (fun deps (_, t) ->
match get_output_typ_dep modul t with
| Some dep -> if List.mem dep deps then deps else deps@[dep]
| _ -> deps) deps params
else deps
| _ -> deps) [] ds in
let signatures, impls =
List.split
(List.collect
(fun d ->
match fst d with
| Type_decl d ->
if d.decl_name.td_entrypoint
then [print_one_validator d]
else []
| _ -> [])
ds)
in
let external_defs_includes =
if not (Options.get_emit_output_types_defs ()) then "" else
let deps =
if List.length signatures_output_typ_deps = 0
then ""
else
String.concat
""
(List.map
(fun dep -> Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" dep)
signatures_output_typ_deps) in
let self =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n" modul
else "" in
Printf.sprintf "%s\n%s\n\n" deps self in
let header =
Printf.sprintf
"#include \"EverParseEndianness.h\"\n\
%s\n\
%s\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
%s\n\
#ifdef __cplusplus\n\
}\n\
#endif\n"
error_code_macros
external_defs_includes
(signatures |> String.concat "\n\n")
in
let input_stream_include = HashingOptions.input_stream_include input_stream_binding in
let header =
if input_stream_include = ""
then header
else Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
header
in
let add_includes = Options.make_includes () in
let header = Printf.sprintf "%s%s" add_includes header in
let error_callback_proto =
if HashingOptions.InputStreamBuffer? input_stream_binding
then Printf.sprintf
"void %sEverParseError(const char *StructName, const char *FieldName, const char *Reason)%s"
modul
(if produce_everparse_error = Some ProduceEverParseError
then "{(void) StructName; (void) FieldName; (void) Reason;}"
else ";")
else ""
in
let impl =
Printf.sprintf
"#include \"%sWrapper.h\"\n\
#include \"EverParse.h\"\n\
#include \"%s.h\"\n\
%s\n\n\
%s\n\n\
%s\n"
modul
modul
error_callback_proto
default_error_handler
(impls |> String.concat "\n\n")
in
let impl =
if input_stream_include = ""
then impl
else
Printf.sprintf
"#include \"%s\"\n\
%s"
input_stream_include
impl
in
let impl = Printf.sprintf "%s%s" add_includes impl in
header,
impl
/// Functions for printing setters and getters for output expressions
let rec out_bt_name (t:typ) : ML string =
match t with
| T_app i _ _ -> A.ident_name i
| T_pointer t -> out_bt_name t
| _ -> failwith "Impossible, out_bt_name received a non output type!"
let out_expr_bt_name (oe:output_expr) : ML string = out_bt_name oe.oe_bt
(*
* Walks over the output expressions AST and constructs a string
*)
let rec out_fn_name (oe:output_expr) : ML string =
match oe.oe_expr with
| T_OE_id _ -> out_expr_bt_name oe
| T_OE_star oe -> Printf.sprintf "%s_star" (out_fn_name oe)
| T_OE_addrof oe -> Printf.sprintf "%s_addrof" (out_fn_name oe)
| T_OE_deref oe f -> Printf.sprintf "%s_deref_%s" (out_fn_name oe) (A.ident_name f)
| T_OE_dot oe f -> Printf.sprintf "%s_dot_%s" (out_fn_name oe) (A.ident_name f)
module H = Hashtable
type set = H.t string unit
(*
* In the printing functions, a hashtable tracks that we print a defn. only once
*
* E.g. multiple output expressions may require a val decl. for types,
* we need to print them only once each
*)
let rec base_output_type (t:typ) : ML A.ident =
match t with
| T_app id A.KindOutput [] -> id
| T_pointer t -> base_output_type t
| _ -> failwith "Target.base_output_type called with a non-output type"
#push-options "--fuel 1"
let rec print_output_type_val (tbl:set) (t:typ) : ML string =
let open A in
if is_output_type t
then let s = print_output_type false t in
if H.try_find tbl s <> None then ""
else let _ = H.insert tbl s () in
assert (is_output_type t);
match t with
| T_app id KindOutput [] ->
Printf.sprintf "\n\nval %s : Type0\n\n" s
| T_pointer bt ->
let bs = print_output_type_val tbl bt in
bs ^ (Printf.sprintf "\n\ninline_for_extraction noextract type %s = bpointer %s\n\n" s (print_output_type false bt))
else ""
#pop-options
let rec print_out_expr' (oe:output_expr') : ML string =
match oe with
| T_OE_id id -> A.ident_to_string id
| T_OE_star o -> Printf.sprintf "*(%s)" (print_out_expr' o.oe_expr)
| T_OE_addrof o -> Printf.sprintf "&(%s)" (print_out_expr' o.oe_expr)
| T_OE_deref o i -> Printf.sprintf "(%s)->%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
| T_OE_dot o i -> Printf.sprintf "(%s).%s" (print_out_expr' o.oe_expr) (A.ident_to_string i)
(*
* F* val for the setter for the output expression
*)
let print_out_expr_set_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "set_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
//TODO: module name?
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_arg2_t =
(*
* If bitwidth is not None,
* then output the size restriction in the refinement
* Is there a better way to output it?
*)
if oe.oe_bitwidth = None
then print_typ mname oe.oe_t
else begin
Printf.sprintf "(i:%s{FStar.UInt.size (FStar.Integers.v i) %d})"
(print_typ mname oe.oe_t)
(Some?.v oe.oe_bitwidth)
end in
Printf.sprintf
"\n\nval %s (_:%s) (_:%s) : extern_action (NonTrivial output_loc)\n\n"
fn_name
fn_arg1_t
fn_arg2_t
let rec base_id_of_output_expr (oe:output_expr) : A.ident =
match oe.oe_expr with
| T_OE_id id -> id
| T_OE_star oe
| T_OE_addrof oe
| T_OE_deref oe _
| T_OE_dot oe _ -> base_id_of_output_expr oe
(*
* C defn. for the setter for the output expression
*)
let print_out_expr_set (tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "set_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_arg2_t = print_as_c_type oe.oe_t in
let fn_arg2_name = "__v" in
let fn_body = Printf.sprintf
"%s = %s;"
(print_out_expr' oe.oe_expr)
fn_arg2_name in
let fn = Printf.sprintf
"void %s (%s %s, %s %s){\n %s;\n}\n"
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_arg2_t
fn_arg2_name
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
(*
* F* val for the getter for the output expression
*)
let print_out_expr_get_fstar (tbl:set) (mname:string) (oe:output_expr) : ML string =
let fn_name = Printf.sprintf "get_%s" (out_fn_name oe) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_typ mname oe.oe_bt in
let fn_res = print_typ mname oe.oe_t in //No bitfields, we could enforce?
Printf.sprintf "\n\nval %s : %s -> %s\n\n" fn_name fn_arg1_t fn_res
(*
* C defn. for the getter for the output expression
*)
let print_out_expr_get(tbl:set) (oe:output_expr) : ML string =
let fn_name = pascal_case (Printf.sprintf "get_%s" (out_fn_name oe)) in
match H.try_find tbl fn_name with
| Some _ -> ""
| _ ->
H.insert tbl fn_name ();
let fn_arg1_t = print_as_c_type oe.oe_bt in
let fn_arg1_name = base_id_of_output_expr oe in
let fn_res = print_as_c_type oe.oe_t in
let fn_body = Printf.sprintf "return %s;" (print_out_expr' oe.oe_expr) in
let fn = Printf.sprintf "%s %s (%s %s){\n %s;\n}\n"
fn_res
fn_name
fn_arg1_t
(A.ident_name fn_arg1_name)
fn_body in
Printf.sprintf "\n\n%s\n\n" fn
let output_setter_name lhs = Printf.sprintf "set_%s" (out_fn_name lhs)
let output_getter_name lhs = Printf.sprintf "get_%s" (out_fn_name lhs)
let output_base_var lhs = base_id_of_output_expr lhs
let print_external_types_fstar_interpreter (modul:string) (ds:decls) : ML string =
let tbl = H.create 10 in
let s = String.concat "" (ds |> List.map (fun d ->
match fst d with
| Output_type ot ->
let t = T_app ot.out_typ_names.typedef_abbrev A.KindOutput [] in
Printf.sprintf "%s%s"
(print_output_type_val tbl t)
(print_output_type_val tbl (T_pointer t))
| Extern_type i ->
Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| _ -> "")) in
Printf.sprintf
"module %s.ExternalTypes\n\n\
open EverParse3d.Prelude\n\
open EverParse3d.Actions.All\n\n%s"
modul
s
let print_external_api_fstar_interpreter (modul:string) (ds:decls) : ML string =
let tbl = H.create 10 in
let s = String.concat "" (ds |> List.map (fun d ->
match fst d with
// | Output_type ot ->
// let t = T_app ot.out_typ_names.typedef_name A.KindOutput [] in
// Printf.sprintf "%s%s"
// (print_output_type_val tbl t)
// (print_output_type_val tbl (T_pointer t))
| Output_type_expr oe is_get ->
Printf.sprintf "%s"
// (print_output_type_val tbl oe.oe_bt)
// (print_output_type_val tbl oe.oe_t)
(if not is_get then print_out_expr_set_fstar tbl modul oe
else print_out_expr_get_fstar tbl modul oe)
| Extern_type i ->
Printf.sprintf "\n\nval %s : Type0\n\n" (print_ident i)
| Extern_fn f ret params ->
Printf.sprintf "\n\nval %s %s : extern_action (NonTrivial output_loc)\n"
(print_ident f)
(String.concat " " (params |> List.map (fun (i, t) -> Printf.sprintf "(%s:%s)"
(print_ident i)
(print_typ modul t))))
| Extern_probe f ->
Printf.sprintf "\n\nval %s : EverParse3d.CopyBuffer.probe_fn\n\n" (print_ident f)
| _ -> "")) in
let external_types_include =
if has_output_types ds || has_extern_types ds
then Printf.sprintf "include %s.ExternalTypes\n\n" modul
else "" in
Printf.sprintf
"module %s.ExternalAPI\n\n\
open EverParse3d.Prelude\n\
open EverParse3d.Actions.All\n\
open EverParse3d.Interpreter\n\
%s\n\
noextract val output_loc : eloc\n\n%s"
modul
external_types_include
s
//
// When printing output expressions in C,
// the output types may be coming from some other module
// This function gets all the dependencies from output expressions
// so that they can be added in the M_OutputTypes.c file
//
let get_out_exprs_deps (modul:string) (ds:decls) : ML (list string) =
let maybe_add_dep (deps:list string) (s:option string) : list string =
match s with
| None -> deps
| Some s -> if List.mem s deps then deps else deps@[s] in
List.fold_left (fun deps (d, _) ->
match d with
| Output_type_expr oe _ ->
maybe_add_dep (maybe_add_dep deps (get_output_typ_dep modul oe.oe_bt))
(get_output_typ_dep modul oe.oe_t)
| _ -> deps) [] ds
let print_out_exprs_c modul (ds:decls) : ML string =
let tbl = H.create 10 in
let deps = get_out_exprs_deps modul ds in
let emit_output_types_defs = Options.get_emit_output_types_defs () in
let dep_includes =
if List.length deps = 0 || not emit_output_types_defs
then ""
else
String.concat ""
(List.map (fun s -> FStar.Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" s) deps) in
let self_external_typedef_include =
if has_output_types ds && emit_output_types_defs
then Printf.sprintf "#include \"%s_ExternalTypedefs.h\"\n\n" modul
else "" in
(Printf.sprintf
"%s#include<stdint.h>\n\n\
%s\
%s\
#if defined(__cplusplus)\n\
extern \"C\" {\n\
#endif\n\n"
(Options.make_includes ())
dep_includes
self_external_typedef_include)
^
(String.concat "" (ds |> List.map (fun d ->
match fst d with
| Output_type_expr oe is_get ->
if not is_get then print_out_expr_set tbl oe
else print_out_expr_get tbl oe
| _ -> "")))
^
("#if defined(__cplusplus)\n\
}\n\
#endif\n\n")
let rec atyp_to_ttyp (t:A.typ) : ML typ =
match t.v with
| A.Pointer t ->
let t = atyp_to_ttyp t in
T_pointer t
| A.Type_app hd _b _args ->
T_app hd _b []
let rec print_output_types_fields (flds:list A.out_field) : ML string =
List.fold_left (fun s fld ->
let fld_s =
match fld with
| A.Out_field_named id t bopt ->
Printf.sprintf "%s %s%s;\n"
(print_as_c_type (atyp_to_ttyp t))
(A.ident_name id)
(match bopt with
| None -> ""
| Some n -> ":" ^ (string_of_int n))
| A.Out_field_anon flds is_union ->
Printf.sprintf "%s {\n %s };\n"
(if is_union then "union" else "struct")
(print_output_types_fields flds) in
s ^ fld_s) "" flds
let print_out_typ (ot:A.out_typ) : ML string =
let open A in
Printf.sprintf
"\ntypedef %s %s {\n%s\n} %s;\n"
(if ot.out_typ_is_union then "union" else "struct")
(uppercase (A.ident_name ot.out_typ_names.typedef_name))
(print_output_types_fields ot.out_typ_fields)
(uppercase (A.ident_name ot.out_typ_names.typedef_abbrev)) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": true,
"full_module": "Hashtable",
"short_module": "H"
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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": 4,
"z3seed": 0,
"z3smtopt": [],
"z3version": "4.8.5"
} | false | modul: Prims.string -> ds: Target.decls -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.decls",
"FStar.Printf.sprintf",
"Options.make_includes",
"FStar.String.concat",
"Prims.list",
"FStar.List.map",
"FStar.Pervasives.Native.tuple2",
"Target.decl'",
"Target.decl_attributes",
"Ast.out_typ",
"Target.print_out_typ"
] | [] | false | true | false | false | false | let print_output_types_defs (modul: string) (ds: decls) : ML string =
| let defs =
String.concat "\n\n"
(List.map (fun (d, _) ->
match d with
| Output_type ot -> print_out_typ ot
| _ -> "")
ds)
in
Printf.sprintf "#ifndef __%s_OutputTypesDefs_H\n#define __%s_OutputTypesDefs_H\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n\n%s%s\n\n\n#if defined(__cplusplus)\n}\n#endif\n\n#define __%s_OutputTypes_H_DEFINED\n#endif\n"
modul
modul
(Options.make_includes ())
defs
modul | false |
Target.fst | Target.print_kind | val print_kind (mname:string) (k:parser_kind) : Tot string | val print_kind (mname:string) (k:parser_kind) : Tot string | let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 23,
"end_line": 465,
"start_col": 0,
"start_line": 437
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> k: Target.parser_kind -> Prims.string | Prims.Tot | [
"total"
] | [] | [
"Prims.string",
"Target.parser_kind",
"Target.__proj__Mkparser_kind__item__pk_kind",
"Ast.ident",
"FStar.Printf.sprintf",
"Target.maybe_mname_prefix",
"Target.print_ident",
"Target.print_kind"
] | [
"recursion"
] | false | false | false | true | false | let rec print_kind (mname: string) (k: parser_kind) : Tot string =
| match k.pk_kind with
| PK_base hd -> Printf.sprintf "%skind_%s" (maybe_mname_prefix mname hd) (print_ident hd)
| PK_list -> "kind_nlist"
| PK_t_at_most -> "kind_t_at_most"
| PK_t_exact -> "kind_t_exact"
| PK_return -> "ret_kind"
| PK_impos -> "impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)" (print_kind mname k1) (print_kind mname k2)
| PK_glb k1 k2 -> Printf.sprintf "(glb %s %s)" (print_kind mname k1) (print_kind mname k2)
| PK_filter k -> Printf.sprintf "(filter_kind %s)" (print_kind mname k)
| PK_string -> "parse_string_kind" | false |
Target.fst | Target.maybe_print_type_equality | val maybe_print_type_equality (mname: string) (td: type_decl) : ML string | val maybe_print_type_equality (mname: string) (td: type_decl) : ML string | let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else "" | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 9,
"end_line": 611,
"start_col": 0,
"start_line": 601
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> td: Target.type_decl -> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.type_decl",
"Target.__proj__Mktypedef_name__item__td_entrypoint",
"Target.__proj__Mktype_decl__item__decl_name",
"FStar.Printf.sprintf",
"Ast.ident_name",
"Target.__proj__Mktypedef_name__item__td_name",
"FStar.Pervasives.Native.option",
"FStar.Pervasives.Native.tuple2",
"FStar.List.tryFind",
"Prims.op_Equality",
"Prims.bool",
"Prims.list",
"Options.get_equate_types_list"
] | [] | false | true | false | false | false | let maybe_print_type_equality (mname: string) (td: type_decl) : ML string =
| if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a
typname
typname
| None -> "")
else "" | false |
Target.fst | Target.print_indexes | val print_indexes (mname: string) (is: list index) : ML (list string) | val print_indexes (mname: string) (is: list index) : ML (list string) | let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 59,
"end_line": 435,
"start_col": 0,
"start_line": 401
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> is: Prims.list Target.index -> FStar.All.ML (Prims.list Prims.string) | FStar.All.ML | [
"ml"
] | [
"print_typ",
"print_indexes"
] | [
"Prims.string",
"Prims.list",
"Target.index",
"Prims.Nil",
"Target.typ",
"Prims.Cons",
"Target.print_indexes",
"Target.print_typ",
"Target.expr",
"Target.print_expr"
] | [
"mutual recursion"
] | false | true | false | false | false | let rec print_indexes (mname: string) (is: list index) : ML (list string) =
| match is with
| [] -> []
| Inl t :: is -> print_typ mname t :: print_indexes mname is
| Inr e :: is -> print_expr mname e :: print_indexes mname is | false |
Target.fst | Target.print_assumption | val print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string | val print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string | let print_assumption (mname:string) (d:decl { Assumption? (fst d) } ) : ML string =
match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t) | {
"file_name": "src/3d/Target.fst",
"git_rev": "00217c4a89f5ba56002ba9aa5b4a9d5903bfe9fa",
"git_url": "https://github.com/project-everest/everparse.git",
"project_name": "everparse"
} | {
"end_col": 25,
"end_line": 646,
"start_col": 0,
"start_line": 640
} | (*
Copyright 2019 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 Target
(* The abstract syntax for the code produced by 3d *)
open FStar.All
module A = Ast
open Binding
let lookup (s:subst) (i:A.ident) : option expr =
List.Tot.assoc i.v s
let rec subst_expr (s:subst) (e:expr)
: expr
= match fst e with
| Constant _ -> e
| Identifier i -> (
match lookup s i with
| Some e' -> e'
| None -> e
)
| App hd args -> (
App hd (subst_exprs s args), snd e
)
| Record tn fields -> (
Record tn (subst_fields s fields), snd e
)
and subst_exprs s es =
match es with
| [] -> []
| e::es -> subst_expr s e :: subst_exprs s es
and subst_fields s fs =
match fs with
| [] -> []
| (i, e)::fs -> (i, subst_expr s e)::subst_fields s fs
let rec expr_eq e1 e2 =
match fst e1, fst e2 with
| Constant c1, Constant c2 -> c1=c2
| Identifier i1, Identifier i2 -> A.(i1.v = i2.v)
| App hd1 args1, App hd2 args2 -> hd1 = hd2 && exprs_eq args1 args2
| Record t1 fields1, Record t2 fields2 -> A.(t1.v = t2.v) && fields_eq fields1 fields2
| _ -> false
and exprs_eq es1 es2 =
match es1, es2 with
| [], [] -> true
| e1::es1, e2::es2 -> expr_eq e1 e2 && exprs_eq es1 es2
| _ -> false
and fields_eq fs1 fs2 =
match fs1, fs2 with
| [], [] -> true
| (i1, e1)::fs1, (i2, e2)::fs2 ->
A.(i1.v = i2.v)
&& fields_eq fs1 fs2
| _ -> false
let rec parser_kind_eq k k' =
match k.pk_kind, k'.pk_kind with
| PK_return, PK_return -> true
| PK_impos, PK_impos -> true
| PK_list, PK_list -> true
| PK_t_at_most, PK_t_at_most -> true
| PK_t_exact, PK_t_exact -> true
| PK_base hd1, PK_base hd2 -> A.(hd1.v = hd2.v)
| PK_filter k, PK_filter k' -> parser_kind_eq k k'
| PK_and_then k1 k2, PK_and_then k1' k2'
| PK_glb k1 k2, PK_glb k1' k2' ->
parser_kind_eq k1 k1'
&& parser_kind_eq k2 k2'
| _ -> false
let has_output_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type? d) ds
let has_output_type_exprs (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Output_type_expr? d) ds
let has_extern_types (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_type? d) ds
let has_extern_functions (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_fn? d) ds
let has_extern_probes (ds:list decl) : bool =
List.Tot.existsb (fun (d, _) -> Extern_probe? d) ds
let has_external_api (ds:list decl) : bool =
has_output_type_exprs ds
|| has_extern_types ds
|| has_extern_functions ds
|| has_extern_probes ds
// Some constants
let default_attrs = {
is_hoisted = false;
is_if_def = false;
is_exported = false;
should_inline = false;
comments = []
}
let error_handler_name =
let open A in
let id' = {
modul_name = None;
name = "handle_error";
} in
let id = with_range id' dummy_range in
id
let error_handler_decl =
let open A in
let error_handler_id' = {
modul_name = Some "EverParse3d.Actions.Base";
name = "error_handler"
} in
let error_handler_id = with_range error_handler_id' dummy_range in
let typ = T_app error_handler_id KindSpec [] in
let a = Assumption (error_handler_name, typ) in
a, default_attrs
////////////////////////////////////////////////////////////////////////////////
// Printing the target AST in F* concrete syntax
////////////////////////////////////////////////////////////////////////////////
let maybe_mname_prefix (mname:string) (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> ""
| Some s -> if s = mname then "" else Printf.sprintf "%s." s
let print_ident (i:A.ident) =
let open A in
match String.list_of_string i.v.name with
| [] -> i.v.name
| c0::_ ->
if FStar.Char.lowercase c0 = c0
then i.v.name
else Ast.reserved_prefix^i.v.name
let print_maybe_qualified_ident (mname:string) (i:A.ident) =
Printf.sprintf "%s%s" (maybe_mname_prefix mname i) (print_ident i)
let print_field_id_name (i:A.ident) =
let open A in
match i.v.modul_name with
| None -> failwith "Unexpected: module name missing from the field id"
| Some m -> Printf.sprintf "%s_%s" (String.lowercase m) i.v.name
let print_integer_type =
let open A in
function
| UInt8 -> "uint8"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| UInt64 -> "uint64"
let namespace_of_integer_type =
let open A in
function
| UInt8 -> "UInt8"
| UInt16 -> "UInt16"
| UInt32 -> "UInt32"
| UInt64 -> "UInt64"
let print_range (r:A.range) : string =
let open A in
Printf.sprintf "(FStar.Range.mk_range \"%s\" %d %d %d %d)"
(fst r).filename
(fst r).line
(fst r).col
(snd r).line
(snd r).col
let arith_op (o:op) =
match o with
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> true
| _ -> false
let integer_type_of_arith_op (o:op{arith_op o}) =
match o with
| Plus t
| Minus t
| Mul t
| Division t
| Remainder t
| ShiftLeft t
| ShiftRight t
| BitwiseAnd t
| BitwiseOr t
| BitwiseXor t
| BitwiseNot t -> t
let print_arith_op_range () : ML bool =
List.length (Options.get_equate_types_list ()) = 0
let print_arith_op
(o:op{arith_op o})
(r:option A.range) : ML string
= let fn =
match o with
| Plus _ -> "add"
| Minus _ -> "sub"
| Mul _ -> "mul"
| Division _ -> "div"
| Remainder _ -> "rem"
| ShiftLeft _ -> "shift_left"
| ShiftRight _ -> "shift_right"
| BitwiseAnd _ -> "logand"
| BitwiseOr _ -> "logor"
| BitwiseXor _ -> "logxor"
| BitwiseNot _ -> "lognot"
in
if print_arith_op_range ()
then
let t =
match integer_type_of_arith_op o with
| A.UInt8 -> "u8"
| A.UInt16 -> "u16"
| A.UInt32 -> "u32"
| A.UInt64 -> "u64"
in
let r = match r with | Some r -> r | None -> A.dummy_range in
Printf.sprintf "EverParse3d.Prelude.%s_%s %s"
t fn (print_range r)
else
let m =
match integer_type_of_arith_op o with
| A.UInt8 -> "FStar.UInt8"
| A.UInt16 -> "FStar.UInt16"
| A.UInt32 -> "FStar.UInt32"
| A.UInt64 -> "FStar.UInt64"
in
Printf.sprintf "%s.%s" m fn
let is_infix =
function
| Eq
| Neq
| And
| Or -> true
| _ -> false
// Bitfield operators from EverParse3d.Prelude.StaticHeader are least
// significant bit first by default, following MSVC
// (https://learn.microsoft.com/en-us/cpp/c-language/c-bit-fields)
let print_bitfield_bit_order = function
| A.LSBFirst -> ""
| A.MSBFirst -> "_msb_first"
let print_op_with_range ropt o =
match o with
| Eq -> "="
| Neq -> "<>"
| And -> "&&"
| Or -> "||"
| Not -> "not"
| Plus _
| Minus _
| Mul _
| Division _
| Remainder _
| ShiftLeft _
| ShiftRight _
| BitwiseAnd _
| BitwiseOr _
| BitwiseXor _
| BitwiseNot _ -> print_arith_op o ropt
| LT t -> Printf.sprintf "FStar.%s.lt" (namespace_of_integer_type t)
| GT t -> Printf.sprintf "FStar.%s.gt" (namespace_of_integer_type t)
| LE t -> Printf.sprintf "FStar.%s.lte" (namespace_of_integer_type t)
| GE t -> Printf.sprintf "FStar.%s.gte" (namespace_of_integer_type t)
| IfThenElse -> "ite"
| BitFieldOf i order -> Printf.sprintf "get_bitfield%d%s" i (print_bitfield_bit_order order)
| Cast from to ->
let tfrom = print_integer_type from in
let tto = print_integer_type to in
if tfrom = tto
then "EverParse3d.Prelude.id"
else Printf.sprintf "EverParse3d.Prelude.%s_to_%s" tfrom tto
| Ext s -> s
let print_op = print_op_with_range None
let rec print_expr (mname:string) (e:expr) : ML string =
match fst e with
| Constant c ->
A.print_constant c
| Identifier i -> print_maybe_qualified_ident mname i
| Record nm fields ->
Printf.sprintf "{ %s }" (String.concat "; " (print_fields mname fields))
| App op [e1;e2] ->
if is_infix op
then
Printf.sprintf "(%s %s %s)"
(print_expr mname e1)
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e2)
else
Printf.sprintf "(%s %s %s)"
(print_op_with_range (Some (snd e)) (App?.hd (fst e)))
(print_expr mname e1)
(print_expr mname e2)
| App Not [e1]
| App (BitwiseNot _) [e1] ->
Printf.sprintf "(%s %s)" (print_op (App?.hd (fst e))) (print_expr mname e1)
| App IfThenElse [e1;e2;e3] ->
Printf.sprintf
"(if %s then %s else %s)"
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App (BitFieldOf i order) [e1;e2;e3] ->
Printf.sprintf
"(%s %s %s %s)"
(print_op (BitFieldOf i order))
(print_expr mname e1) (print_expr mname e2) (print_expr mname e3)
| App op [] ->
print_op op
| App op es ->
Printf.sprintf "(%s %s)" (print_op op) (String.concat " " (print_exprs mname es))
and print_exprs (mname:string) (es:list expr) : ML (list string) =
match es with
| [] -> []
| hd::tl -> print_expr mname hd :: print_exprs mname tl
and print_fields (mname:string) (fs:_) : ML (list string) =
match fs with
| [] -> []
| (x, e)::tl ->
Printf.sprintf "%s = %s" (print_ident x) (print_expr mname e)
:: print_fields mname tl
let print_lam (#a:Type) (f:a -> ML string) (x:lam a) : ML string =
match x with
| Some x, y ->
Printf.sprintf ("(fun %s -> %s)")
(print_ident x)
(f y)
| None, y -> f y
let print_expr_lam (mname:string) (x:lam expr) : ML string =
print_lam (print_expr mname) x
let rec is_output_type (t:typ) : bool =
match t with
| T_app _ A.KindOutput [] -> true
| T_pointer t -> is_output_type t
| _ -> false
let rec is_extern_type (t:typ) : bool =
match t with
| T_app _ A.KindExtern [] -> true
| T_pointer t -> is_extern_type t
| _ -> false
(*
* An output type is printed as the ident, or p_<ident>
*
* They are abstract types in the emitted F* code
*)
let print_output_type (qual:bool) (t:typ) : ML string =
let rec aux (t:typ)
: ML (option string & string)
= match t with
| T_app id _ _ ->
id.v.modul_name, print_ident id
| T_pointer t ->
let m, i = aux t in
m, Printf.sprintf "p_%s" i
| _ -> failwith "Print: not an output type"
in
let mopt, i = aux t in
if qual
then match mopt with
| None -> i
| Some m -> Printf.sprintf "%s.ExternalTypes.%s" m i
else i
let rec print_typ (mname:string) (t:typ) : ML string = //(decreases t) =
if is_output_type t
then print_output_type true t
else
match t with
| T_false -> "False"
| T_app hd _ args -> //output types are already handled at the beginning of print_typ
Printf.sprintf "(%s %s)"
(print_maybe_qualified_ident mname hd)
(String.concat " " (print_indexes mname args))
| T_dep_pair t1 (x, t2) ->
Printf.sprintf "(%s:%s & %s)"
(print_ident x)
(print_typ mname t1)
(print_typ mname t2)
| T_refine t e ->
Printf.sprintf "(refine %s %s)"
(print_typ mname t)
(print_expr_lam mname e)
| T_if_else e t1 t2 ->
Printf.sprintf "(t_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname e)
(print_typ mname t1)
(print_typ mname t2)
| T_pointer t -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
| T_with_action t _
| T_with_dep_action t _
| T_with_comment t _ -> print_typ mname t
| T_with_probe t _ _ _ -> Printf.sprintf "bpointer (%s)" (print_typ mname t)
and print_indexes (mname:string) (is:list index) : ML (list string) = //(decreases is) =
match is with
| [] -> []
| Inl t::is -> print_typ mname t::print_indexes mname is
| Inr e::is -> print_expr mname e::print_indexes mname is
let rec print_kind (mname:string) (k:parser_kind) : Tot string =
match k.pk_kind with
| PK_base hd ->
Printf.sprintf "%skind_%s"
(maybe_mname_prefix mname hd)
(print_ident hd)
| PK_list ->
"kind_nlist"
| PK_t_at_most ->
"kind_t_at_most"
| PK_t_exact ->
"kind_t_exact"
| PK_return ->
"ret_kind"
| PK_impos ->
"impos_kind"
| PK_and_then k1 k2 ->
Printf.sprintf "(and_then_kind %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_glb k1 k2 ->
Printf.sprintf "(glb %s %s)"
(print_kind mname k1)
(print_kind mname k2)
| PK_filter k ->
Printf.sprintf "(filter_kind %s)"
(print_kind mname k)
| PK_string ->
"parse_string_kind"
let rec print_action (mname:string) (a:action) : ML string =
let print_atomic_action (a:atomic_action)
: ML string
= match a with
| Action_return e ->
Printf.sprintf "(action_return %s)" (print_expr mname e)
| Action_abort -> "(action_abort())"
| Action_field_pos_64 -> "(action_field_pos_64())"
| Action_field_pos_32 -> "(action_field_pos_32 EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr -> "(action_field_ptr EverParse3d.Actions.BackendFlagValue.backend_flag_value)"
| Action_field_ptr_after sz write_to ->
Printf.sprintf "(action_field_ptr_after EverParse3d.Actions.BackendFlagValue.backend_flag_value %s %s)" (print_expr mname sz) (print_ident write_to)
| Action_field_ptr_after_with_setter sz write_to_field write_to_obj ->
Printf.sprintf "(action_field_ptr_after_with_setter EverParse3d.Actions.BackendFlagValue.backend_flag_value %s (%s %s))"
(print_expr mname sz)
(print_ident write_to_field)
(print_expr mname write_to_obj)
| Action_deref i ->
Printf.sprintf "(action_deref %s)" (print_ident i)
| Action_assignment lhs rhs ->
Printf.sprintf "(action_assignment %s %s)" (print_ident lhs) (print_expr mname rhs)
| Action_call f args ->
Printf.sprintf "(mk_extern_action (%s %s))" (print_ident f) (String.concat " " (List.map (print_expr mname) args))
in
match a with
| Atomic_action a ->
print_atomic_action a
| Action_seq hd tl ->
Printf.sprintf "(action_seq %s %s)"
(print_atomic_action hd)
(print_action mname tl)
| Action_ite hd then_ else_ ->
Printf.sprintf "(action_ite %s (fun _ -> %s) (fun _ -> %s))"
(print_expr mname hd)
(print_action mname then_)
(print_action mname else_)
| Action_let i a k ->
Printf.sprintf "(action_bind \"%s\" %s (fun %s -> %s))"
(print_ident i)
(print_atomic_action a)
(print_ident i)
(print_action mname k)
| Action_act a ->
Printf.sprintf "(action_act %s)"
(print_action mname a)
let print_typedef_name (mname:string) (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map
(fun (id, t) ->
Printf.sprintf "(%s:%s)"
(print_ident id)
(print_typ mname t))
tdn.td_params))
let print_typedef_typ (tdn:typedef_name) : ML string =
Printf.sprintf "%s %s"
(print_ident tdn.td_name)
(String.concat " "
(List.map (fun (id, t) -> (print_ident id)) tdn.td_params))
let print_typedef_body (mname:string) (b:typedef_body) : ML string =
match b with
| TD_abbrev t -> print_typ mname t
| TD_struct fields ->
let print_field (sf:field) : ML string =
Printf.sprintf "%s : %s%s"
(print_ident sf.sf_ident)
(print_typ mname sf.sf_typ)
(if sf.sf_dependence then " (*dep*)" else "")
in
let fields = String.concat ";\n" (List.map print_field fields) in
Printf.sprintf "{\n%s\n}" fields
let print_typedef_actions_inv_and_fp (td:type_decl) =
//we need to add output loc to the modifies locs
//if there is an output type type parameter
let should_add_output_loc =
List.Tot.existsb (fun (_, t) -> is_output_type t || is_extern_type t) td.decl_name.td_params in
let pointers = //get only non output type pointers
List.Tot.filter (fun (x, t) -> T_pointer? t && not (is_output_type t || is_extern_type t)) td.decl_name.td_params
in
let inv =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "((ptr_inv %s) `conj_inv` %s)"
(print_ident x)
out)
pointers
"true_inv"
in
let fp =
List.Tot.fold_right
(fun (x, t) out ->
Printf.sprintf "(eloc_union (ptr_loc %s) %s)"
(print_ident x)
out)
pointers
(if should_add_output_loc then "output_loc" else "eloc_none")
in
inv, fp
let print_comments (cs:list string) : string =
match cs with
| [] -> ""
| _ ->
let c = String.concat "\\n\\\n" cs in
Printf.sprintf " (Comment \"%s\")" c
let print_attributes (entrypoint:bool) (attrs:decl_attributes) : string =
match attrs.comments with
| [] ->
if entrypoint || attrs.is_exported
then ""
else if attrs.should_inline
then "inline_for_extraction noextract\n"
else "[@ (CInline)]\n"
| cs ->
Printf.sprintf "[@ %s %s]\n%s"
(print_comments cs)
(if not entrypoint &&
not attrs.is_exported &&
not attrs.should_inline
then "(CInline)" else "")
(if attrs.should_inline then "inline_for_extraction\n" else "")
/// Printing a decl for M.Types.fst
///
/// Print all the definitions, and for a Type_decl, only the type definition
let maybe_print_type_equality (mname:string) (td:type_decl) : ML string =
if td.decl_name.td_entrypoint
then
let equate_types_list = Options.get_equate_types_list () in
(match (List.tryFind (fun (_, m) -> m = mname) equate_types_list) with
| Some (a, _) ->
let typname = A.ident_name td.decl_name.td_name in
Printf.sprintf "\n\nlet _ = assert (%s.Types.%s == %s) by (FStar.Tactics.trefl ())\n\n"
a typname typname
| None -> "")
else ""
let print_definition (mname:string) (d:decl { Definition? (fst d)} ) : ML string =
match fst d with
| Definition (x, [], T_app ({Ast.v={Ast.name="field_id"}}) _ _, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot field_id by (FStar.Tactics.trivial())\n\n"
(print_comments (snd d).comments)
(print_field_id_name x)
(A.print_constant c)
| Definition (x, [], t, (Constant c, _)) ->
Printf.sprintf "[@(CMacro)%s]\nlet %s = %s <: Tot %s\n\n"
(print_comments (snd d).comments)
(print_ident x)
(A.print_constant c)
(print_typ mname t)
| Definition (x, params, typ, expr) ->
let x_ps = {
td_name = x;
td_params = params;
td_entrypoint = false
} in
Printf.sprintf "%slet %s : %s = %s\n\n"
(print_attributes false (snd d))
(print_typedef_name mname x_ps)
(print_typ mname typ)
(print_expr mname expr) | {
"checked_file": "/",
"dependencies": [
"prims.fst.checked",
"Options.fsti.checked",
"Hashtable.fsti.checked",
"HashingOptions.fst.checked",
"FStar.String.fsti.checked",
"FStar.Printf.fst.checked",
"FStar.Pervasives.Native.fst.checked",
"FStar.Pervasives.fsti.checked",
"FStar.List.Tot.fst.checked",
"FStar.List.fst.checked",
"FStar.Char.fsti.checked",
"FStar.All.fst.checked",
"Binding.fsti.checked",
"Ast.fst.checked"
],
"interface_file": true,
"source_file": "Target.fst"
} | [
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"short_module": null
},
{
"abbrev": false,
"full_module": "Binding",
"short_module": null
},
{
"abbrev": true,
"full_module": "Ast",
"short_module": "A"
},
{
"abbrev": false,
"full_module": "FStar.All",
"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 | mname: Prims.string -> d: Target.decl{Assumption? (FStar.Pervasives.Native.fst d)}
-> FStar.All.ML Prims.string | FStar.All.ML | [
"ml"
] | [] | [
"Prims.string",
"Target.decl",
"Prims.b2t",
"Target.uu___is_Assumption",
"FStar.Pervasives.Native.fst",
"Target.decl'",
"Target.decl_attributes",
"Ast.ident",
"Target.typ",
"FStar.Printf.sprintf",
"Target.__proj__Mkdecl_attributes__item__is_if_def",
"FStar.Pervasives.Native.snd",
"Prims.bool",
"Target.print_ident",
"Target.print_typ"
] | [] | false | true | false | false | false | let print_assumption (mname: string) (d: decl{Assumption? (fst d)}) : ML string =
| match fst d with
| Assumption (x, t) ->
Printf.sprintf "%sassume\nval %s : %s\n\n"
(if (snd d).is_if_def then "[@@ CIfDef ]\n" else "")
(print_ident x)
(print_typ mname t) | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.